diff --git a/.github/workflows/analyze.yaml b/.github/workflows/analyze.yaml index e5bb25d..c66aad8 100644 --- a/.github/workflows/analyze.yaml +++ b/.github/workflows/analyze.yaml @@ -31,7 +31,7 @@ jobs: - uses: actions/checkout@44c2b7a8a4ea60a981eaca3cf939b5f4305c123b - uses: subosito/flutter-action@44ac965b96f18d999802d4b807e3256d5a3f9fa1 with: - flutter-version: "3.22.x" + flutter-version: "3.32.x" channel: "stable" cache: true - uses: bluefireteam/melos-action@6085791af7036f6366c9a4b9d55105c0ef9c6388 @@ -56,13 +56,14 @@ jobs: path: /home/linuxbrew/.linuxbrew key: ${{ runner.os }}-linuxbrew - uses: Homebrew/actions/setup-homebrew@master - - name: "Install swiftformat v0.53" - if: steps.cache.outputs.cache-hit != 'true' + - name: Install swift-format 600.0.0 + #if: steps.cache.outputs.cache-hit != 'true' run: | + eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)" export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=1 - curl -O https://raw.githubusercontent.com/Homebrew/homebrew-core/86f85aaa82beba49f8a5aabf3a22508c9249f188/Formula/s/swiftformat.rb - grep -qxF 'brew "swiftformat.rb"' Brewfile || echo 'brew "swiftformat.rb"' >> Brewfile - brew bundle --force + curl -O https://raw.githubusercontent.com/Homebrew/homebrew-core/402e262f48947bad849ea7793752ff16b7038406/Formula/s/swift-format.rb + echo 'brew "swift-format.rb"' > Brewfile + brew bundle - name: Save Cache uses: actions/cache/save@v4 if: steps.cache.outputs.cache-hit != 'true' @@ -71,7 +72,7 @@ jobs: key: ${{ runner.os }}-linuxbrew - uses: subosito/flutter-action@44ac965b96f18d999802d4b807e3256d5a3f9fa1 with: - flutter-version: "3.22.x" + flutter-version: "3.32.x" channel: "stable" cache: true - uses: bluefireteam/melos-action@6085791af7036f6366c9a4b9d55105c0ef9c6388 @@ -79,7 +80,8 @@ jobs: melos-version: "6.0.0" - name: "Formatter version" run: | - swiftformat --version + eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)" + swift-format --version - name: "Run format" if: ${{ success() || failure() }} run: | diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 6cb8943..99f3d3c 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -37,7 +37,7 @@ jobs: cache: "gradle" - uses: subosito/flutter-action@44ac965b96f18d999802d4b807e3256d5a3f9fa1 with: - flutter-version: "3.22.x" + flutter-version: "3.32.x" channel: "stable" cache: true - uses: bluefireteam/melos-action@6085791af7036f6366c9a4b9d55105c0ef9c6388 @@ -59,7 +59,7 @@ jobs: cache: "gradle" - uses: subosito/flutter-action@44ac965b96f18d999802d4b807e3256d5a3f9fa1 with: - flutter-version: "3.22.x" + flutter-version: "3.32.x" channel: "stable" cache: true - uses: bluefireteam/melos-action@6085791af7036f6366c9a4b9d55105c0ef9c6388 @@ -85,17 +85,19 @@ jobs: ${{ runner.os }}-pods- - uses: subosito/flutter-action@44ac965b96f18d999802d4b807e3256d5a3f9fa1 with: - flutter-version: "3.22.x" + flutter-version: "3.32.x" channel: "stable" cache: true - uses: bluefireteam/melos-action@6085791af7036f6366c9a4b9d55105c0ef9c6388 with: melos-version: "6.0.0" + - name: Select XCode 16.1 + run: sudo xcode-select -s '/Applications/Xcode_16.1.0.app/Contents/Developer' - name: Generate necessary files with flutter build working-directory: ${{ matrix.working_directory }} run: flutter build ios --config-only - name: "Run iOS native unit tests" - run: DEVICE='iPhone 14 Pro' melos run test:ios + run: TEST_DEVICE='iPhone 16 Pro' TEST_OS='18.1' melos run test:ios build-android: needs: [test-dart, test-android, test-ios] @@ -114,7 +116,7 @@ jobs: cache: "gradle" - uses: subosito/flutter-action@44ac965b96f18d999802d4b807e3256d5a3f9fa1 with: - flutter-version: "3.22.x" + flutter-version: "3.32.x" channel: "stable" cache: true - uses: bluefireteam/melos-action@6085791af7036f6366c9a4b9d55105c0ef9c6388 @@ -134,7 +136,7 @@ jobs: - uses: actions/checkout@44c2b7a8a4ea60a981eaca3cf939b5f4305c123b - uses: subosito/flutter-action@44ac965b96f18d999802d4b807e3256d5a3f9fa1 with: - flutter-version: "3.22.x" + flutter-version: "3.32.x" channel: "stable" cache: true architecture: x64 @@ -147,5 +149,7 @@ jobs: key: ${{ runner.os }}-pods-${{ hashFiles('**/*.podspec') }} restore-keys: | ${{ runner.os }}-pods- + - name: Select XCode 16.1 + run: sudo xcode-select -s '/Applications/Xcode_16.1.0.app/Contents/Developer' - name: "Run build for iOS" run: melos run flutter-build-ios diff --git a/.github/workflows/licence-check.yaml b/.github/workflows/licence-check.yaml index 7286b0c..1d3f49b 100644 --- a/.github/workflows/licence-check.yaml +++ b/.github/workflows/licence-check.yaml @@ -38,7 +38,7 @@ jobs: - name: Install Flutter uses: subosito/flutter-action@44ac965b96f18d999802d4b807e3256d5a3f9fa1 with: - flutter-version: "3.22.x" + flutter-version: "3.32.x" channel: "stable" cache: true - name: Install Melos diff --git a/.swiftformat b/.swiftformat deleted file mode 100644 index bca6f1d..0000000 --- a/.swiftformat +++ /dev/null @@ -1,6 +0,0 @@ ---indent 2 ---maxwidth 100 ---wrapparameters afterfirst ---disable sortedImports,unusedArguments,wrapMultilineStatementBraces ---exclude Pods,**/MainFlutterWindow.swift,**/AppDelegate.swift,**/.symlinks/**,**/example/build/** ---swiftversion 5.7 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index aa52527..ceb0ed1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,13 +7,13 @@ _See also: [Flutter's code of conduct](https://flutter.io/design-principles/#cod - **Operating System:** Linux, macOS, or Windows. - **Version Control:** [git](https://git-scm.com). - **Development Environment:** An IDE such as [Android Studio](https://developer.android.com/studio) or [Visual Studio Code](https://code.visualstudio.com/). -- **Code Formatting:** [`swiftformat`](https://github.com/nicklockwood/SwiftFormat) (available via brew on macOS, on Windows install Swift toolchain and build SwiftFormat from git sources). +- **Code Formatting:** [`swift-format`](https://formulae.brew.sh/formula/swift-formatt). -### 1.1. Installing swiftformat -The CI is locked to swiftformat 0.53 version which you can install with the command below: +### 1.1. Installing swift-format +The CI is locked to swift-format 600.0.0 version which you can install with the command below: ```bash -curl -O https://raw.githubusercontent.com/Homebrew/homebrew-core/86f85aaa82beba49f8a5aabf3a22508c9249f188/Formula/s/swiftformat.rb -brew install swiftformat.rb +curl -O https://raw.githubusercontent.com/Homebrew/homebrew-core/402e262f48947bad849ea7793752ff16b7038406/Formula/s/swift-format.rb +brew install swift-format.rb ``` ## 2. Setting Up Your Local Repository diff --git a/README.md b/README.md index 374b806..dad6e36 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ This repository contains a Flutter plugin that allows users to use the [Google M | | Android | iOS | | ----------- | ------- | --------- | -| **Support** | SDK 23+ | iOS 14.0+ | +| **Support** | SDK 23+ | iOS 16.0+ | * A Flutter project * A Google Cloud project with the [Navigation SDK enabled](https://developers.google.com/maps/documentation/navigation/android-sdk/set-up-project), the [Maps SDK for iOS enabled](https://developers.google.com/maps/documentation/navigation/ios-sdk/config) and the [Local Rides and Deliveries API enabled](https://console.developers.google.com/apis/library/fleetengine.googleapis.com) diff --git a/analysis_options.yaml b/analysis_options.yaml index 92abca7..c72b223 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -19,224 +19,16 @@ # "DIFFERENT FROM FLUTTER/FLUTTER" below. The file is expected to # be kept in sync with the master file from the flutter repo. +include: package:flutter_lints/flutter.yaml + analyzer: language: strict-casts: true strict-raw-types: true errors: - # allow self-reference to deprecated members (we do this because otherwise we have - # to annotate every member in every test, assert, etc, when we deprecate something) + # allow self-reference to deprecated members deprecated_member_use_from_same_package: ignore - exclude: # DIFFERENT FROM FLUTTER/FLUTTER + exclude: # Ignore generated files - - '**/*.g.dart' - - '**/*.mocks.dart' # Mockito @GenerateMocks - -linter: - rules: - # This list is derived from the list of all available lints located at - # https://github.com/dart-lang/linter/blob/master/example/all.yaml - - always_declare_return_types - - always_put_control_body_on_new_line - - always_specify_types - # - always_use_package_imports - - annotate_overrides - # - avoid_annotating_with_dynamic # conflicts with always_specify_types - - 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_classes_with_only_static_members - - avoid_double_and_int_checks - - avoid_dynamic_calls - - avoid_empty_else - - 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 - - avoid_function_literals_in_foreach_calls - - avoid_implementing_value_types - - avoid_init_to_null - - avoid_js_rounded_ints - # - avoid_multiple_declarations_per_line - - avoid_null_checks_in_equality_operators - # - avoid_positional_boolean_parameters - - avoid_print - # - avoid_private_typedef_functions # project prefers having typedef - - avoid_redundant_argument_values - - avoid_relative_lib_imports - - avoid_renaming_method_parameters - - avoid_return_types_on_setters - - avoid_returning_null_for_void - # - avoid_returning_this - - avoid_setters_without_getters - - avoid_shadowing_type_parameters - - avoid_single_cascade_in_expression_statements - - avoid_slow_async_io - - avoid_type_to_string - - avoid_types_as_parameter_names - # - avoid_types_on_closure_parameters # conflicts with always_specify_types - - avoid_unnecessary_containers - - avoid_unused_constructor_parameters - - avoid_void_async - - avoid_web_libraries_in_flutter - - await_only_futures - - camel_case_extensions - - camel_case_types - - cancel_subscriptions - # - cascade_invocations # doesn't match the typical style of this repo - - cast_nullable_to_non_nullable - # - close_sinks # not reliable enough - - collection_methods_unrelated_type - # - combinators_ordering # DIFFERENT FROM FLUTTER/FLUTTER: This isn't available on stable yet. - # - comment_references # blocked on https://github.com/dart-lang/linter/issues/1142 - - conditional_uri_does_not_exist - # - constant_identifier_names # needs an opt-out https://github.com/dart-lang/linter/issues/204 - - control_flow_in_finally - - curly_braces_in_flow_control_structures - - dangling_library_doc_comments - # - depend_on_referenced_packages # project uses dependency overrides - - deprecated_consistency - # - diagnostic_describe_all_properties # enabled only at the framework level (packages/flutter/lib) - - directives_ordering - # - discarded_futures # not yet tested - # - do_not_use_environment # there are appropriate times to use the environment, especially in our tests and build logic - - empty_catches - - empty_constructor_bodies - - empty_statements - - eol_at_end_of_file - - exhaustive_cases - - file_names - - flutter_style_todos - - hash_and_equals - - implementation_imports - - implicit_call_tearoffs - # - join_return_with_assignment # not required by flutter style - - leading_newlines_in_multiline_strings - - library_names - - library_prefixes - - library_private_types_in_public_api - # - lines_longer_than_80_chars # not required by flutter style - # - literal_only_boolean_expressions # too many false positives: https://github.com/dart-lang/linter/issues/453 - - missing_whitespace_between_adjacent_strings - - no_adjacent_strings_in_list - - no_default_cases - - no_duplicate_case_values - - no_leading_underscores_for_library_prefixes - - no_leading_underscores_for_local_identifiers - - no_logic_in_create_state - - no_runtimeType_toString # DIFFERENT FROM FLUTTER/FLUTTER - - non_constant_identifier_names - - noop_primitive_operations - - null_check_on_nullable_type_parameter - - null_closures - # - omit_local_variable_types # opposite of always_specify_types - # - 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 - - package_names - - package_prefixed_library_names - # - parameter_assignments # we do this commonly - - prefer_adjacent_string_concatenation - - prefer_asserts_in_initializer_lists - # - prefer_asserts_with_message # not required by flutter style - - prefer_collection_literals - - prefer_conditional_assignment - - prefer_const_constructors - - prefer_const_constructors_in_immutables - - prefer_const_declarations - - prefer_const_literals_to_create_immutables - # - 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/wiki/Style-guide-for-Flutter-repo#consider-using--for-short-functions-and-methods - - prefer_final_fields - - prefer_final_in_for_each - - prefer_final_locals - # - prefer_final_parameters # we should enable this one day when it can be auto-fixed (https://github.com/dart-lang/linter/issues/3104), see also parameter_assignments - - prefer_for_elements_to_map_fromIterable - - prefer_foreach - - prefer_function_declarations_over_variables - - prefer_generic_function_type_aliases - - prefer_if_elements_to_conditional_expressions - - prefer_if_null_operators - - prefer_initializing_formals - - prefer_inlined_adds - # - prefer_int_literals # conflicts with https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#use-double-literals-for-double-constants - - prefer_interpolation_to_compose_strings - - prefer_is_empty - - prefer_is_not_empty - - prefer_is_not_operator - - prefer_iterable_whereType - # - prefer_mixin # Has false positives, see https://github.com/dart-lang/linter/issues/3018 - # - prefer_null_aware_method_calls # "call()" is confusing to people new to the language since it's not documented anywhere - - prefer_null_aware_operators - - prefer_relative_imports - - prefer_single_quotes - - prefer_spread_collections - - prefer_typing_uninitialized_variables - - provide_deprecation_message - - public_member_api_docs # DIFFERENT FROM FLUTTER/FLUTTER - - recursive_getters - # - require_trailing_commas # blocked on https://github.com/dart-lang/sdk/issues/47441 - - secure_pubspec_urls - - sized_box_for_whitespace - # - sized_box_shrink_expand # not yet tested - - slash_for_doc_comments - - sort_child_properties_last - - sort_constructors_first - - sort_pub_dependencies # DIFFERENT FROM FLUTTER/FLUTTER: Flutter's use case for not sorting does not apply to this repository. - - sort_unnamed_constructors_first - - test_types_in_equals - - throw_in_finally - - tighten_type_of_initializing_formals - # - type_annotate_public_apis # subset of always_specify_types - - type_init_formals - - type_literal_in_constant_pattern - - 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 - - unnecessary_brace_in_string_interps - - unnecessary_const - - unnecessary_constructor_name - # - unnecessary_final # conflicts with prefer_final_locals - - unnecessary_getters_setters - # - unnecessary_lambdas # has false positives: https://github.com/dart-lang/linter/issues/498 - - unnecessary_late - - unnecessary_new - - unnecessary_null_aware_assignments - - unnecessary_null_aware_operator_on_extension_on_nullable - - unnecessary_null_checks - - unnecessary_null_in_if_null_operators - - unnecessary_nullable_for_final_variable_declarations - - unnecessary_overrides - - unnecessary_parenthesis - # - unnecessary_raw_strings # what's "necessary" is a matter of opinion; consistency across strings can help readability more than this lint - - unnecessary_statements - - unnecessary_string_escapes - - unnecessary_string_interpolations - - unnecessary_this - - unnecessary_to_list_in_spreads - - unrelated_type_equality_checks - - unsafe_html - - use_build_context_synchronously - # - use_colored_box # not yet tested - # - use_decorated_box # not yet tested - # - use_enums # not yet tested - - use_full_hex_values_for_flutter_colors - - use_function_type_syntax_for_parameters - - use_if_null_to_convert_nulls_to_bools - - use_is_even_rather_than_modulo - - use_key_in_widget_constructors - - use_late_for_private_fields_and_variables - - use_named_constants - - use_raw_strings - - use_rethrow_when_possible - - use_setters_to_change_properties - # - use_string_buffers # has false positives: https://github.com/dart-lang/sdk/issues/34182 - - use_string_in_part_of_directives - - 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 - - valid_regexps - - void_checks - \ No newline at end of file + - "**/*.g.dart" + - "**/*.mocks.dart" # Mockito @GenerateMocks diff --git a/android/build.gradle b/android/build.gradle index 2cfdafe..8230a5a 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -16,7 +16,7 @@ group 'com.google.maps.flutter.driver' version '1.0-SNAPSHOT' buildscript { - ext.kotlin_version = '1.9.22' + ext.kotlin_version = '2.1.0' repositories { google() mavenCentral() @@ -24,9 +24,9 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:8.2.2' + classpath 'com.android.tools.build:gradle:8.8.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - classpath 'com.ncorti.ktfmt.gradle:plugin:0.17.0' + classpath 'com.ncorti.ktfmt.gradle:plugin:0.21.0' } } @@ -50,15 +50,15 @@ android { namespace 'com.google.maps.flutter.driver' } - compileSdk 33 + compileSdk 34 compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 + sourceCompatibility JavaVersion.VERSION_11 + targetCompatibility JavaVersion.VERSION_11 } kotlinOptions { - jvmTarget = '1.8' + jvmTarget = '11' } sourceSets { @@ -71,7 +71,7 @@ android { } dependencies { - implementation 'com.google.android.libraries.mapsplatform.transportation:transportation-driver:5.0.0' + implementation 'com.google.android.libraries.mapsplatform.transportation:transportation-driver:6.2.0' testImplementation 'org.jetbrains.kotlin:kotlin-test' testImplementation 'io.mockk:mockk:1.13.9' testImplementation 'junit:junit:4.13.2' diff --git a/android/src/main/kotlin/com/google/maps/flutter/driver/Convert.kt b/android/src/main/kotlin/com/google/maps/flutter/driver/Convert.kt index c61fbf9..4903bf5 100644 --- a/android/src/main/kotlin/com/google/maps/flutter/driver/Convert.kt +++ b/android/src/main/kotlin/com/google/maps/flutter/driver/Convert.kt @@ -93,7 +93,7 @@ object Convert { convertLatLngToDto(waypoint.position), waypoint.placeId, waypoint.preferSameSideOfRoad, - waypoint.preferredHeading.takeIf { it != -1 }?.toLong() + waypoint.preferredHeading.takeIf { it != -1 }?.toLong(), ) } @@ -128,8 +128,8 @@ object Convert { */ fun convertVehicleStopStateFromDto(vehicleStopState: VehicleStopStateDto): Int { return when (vehicleStopState) { - VehicleStopStateDto.STATEUNSPECIFIED -> VehicleStop.VehicleStopState.UNSPECIFIED - VehicleStopStateDto.NEWSTOP -> VehicleStop.VehicleStopState.NEW + VehicleStopStateDto.STATE_UNSPECIFIED -> VehicleStop.VehicleStopState.UNSPECIFIED + VehicleStopStateDto.NEW_STOP -> VehicleStop.VehicleStopState.NEW VehicleStopStateDto.ENROUTE -> VehicleStop.VehicleStopState.ENROUTE VehicleStopStateDto.ARRIVED -> VehicleStop.VehicleStopState.ARRIVED } @@ -143,12 +143,12 @@ object Convert { */ fun convertVehicleStopStateToDto(googleVehicleStopState: Int): VehicleStopStateDto { return when (googleVehicleStopState) { - VehicleStop.VehicleStopState.UNSPECIFIED -> VehicleStopStateDto.STATEUNSPECIFIED - VehicleStop.VehicleStopState.NEW -> VehicleStopStateDto.NEWSTOP + VehicleStop.VehicleStopState.UNSPECIFIED -> VehicleStopStateDto.STATE_UNSPECIFIED + VehicleStop.VehicleStopState.NEW -> VehicleStopStateDto.NEW_STOP VehicleStop.VehicleStopState.ENROUTE -> VehicleStopStateDto.ENROUTE VehicleStop.VehicleStopState.ARRIVED -> VehicleStopStateDto.ARRIVED else -> { - VehicleStopStateDto.STATEUNSPECIFIED + VehicleStopStateDto.STATE_UNSPECIFIED } } } @@ -165,7 +165,7 @@ object Convert { convertWaypointToDto(stop.waypoint), Lists.transform(stop.taskInfoList) { task: TaskInfo -> convertTaskInfoToDto(task) - } + }, ) } @@ -222,14 +222,14 @@ object Convert { "driverException", t.message?.replace("java.lang.RuntimeException: Exception: ", "") ?: "Token retrieval from the backend failed.", - "UNAUTHENTICATED" + "UNAUTHENTICATED", ) } else -> { return FlutterError( "driverException", extractErrorMessage(t) ?: "Driver API call failed.", - extractErrorCode(t) ?: "UNKNOWN" + extractErrorCode(t) ?: "UNKNOWN", ) } } @@ -296,7 +296,7 @@ object Convert { longitude = location.longitude, isMock = isMock, speed = location.speed.toDouble(), - time = location.time + time = location.time, ) } @@ -311,7 +311,7 @@ object Convert { providerId = deliveryVehicle.providerId, id = deliveryVehicle.vehicleId, name = deliveryVehicle.vehicleName, - stops = deliveryVehicle.vehicleStops.map { convertVehicleStopToDto(it) } + stops = deliveryVehicle.vehicleStops.map { convertVehicleStopToDto(it) }, ) } @@ -344,21 +344,21 @@ object Convert { statusCode: DriverContext.DriverStatusListener.StatusCode ): DriverStatusCodeDto { return when (statusCode) { - DriverContext.DriverStatusListener.StatusCode.DEFAULT -> DriverStatusCodeDto.DEFAULTSTATUS + DriverContext.DriverStatusListener.StatusCode.DEFAULT -> DriverStatusCodeDto.DEFAULT_STATUS DriverContext.DriverStatusListener.StatusCode.UNKNOWN_ERROR -> - DriverStatusCodeDto.UNKNOWNERROR + DriverStatusCodeDto.UNKNOWN_ERROR DriverContext.DriverStatusListener.StatusCode.VEHICLE_NOT_FOUND -> - DriverStatusCodeDto.VEHICLENOTFOUND + DriverStatusCodeDto.VEHICLE_NOT_FOUND DriverContext.DriverStatusListener.StatusCode.BACKEND_CONNECTIVITY_ERROR -> - DriverStatusCodeDto.BACKENDCONNECTIVITYERROR + DriverStatusCodeDto.BACKEND_CONNECTIVITY_ERROR DriverContext.DriverStatusListener.StatusCode.PERMISSION_DENIED -> - DriverStatusCodeDto.PERMISSIONDENIED + DriverStatusCodeDto.PERMISSION_DENIED DriverContext.DriverStatusListener.StatusCode.SERVICE_ERROR -> - DriverStatusCodeDto.SERVICEERROR + DriverStatusCodeDto.SERVICE_ERROR DriverContext.DriverStatusListener.StatusCode.FILE_ACCESS_ERROR -> - DriverStatusCodeDto.FILEACCESSERROR + DriverStatusCodeDto.FILE_ACCESS_ERROR DriverContext.DriverStatusListener.StatusCode.TRAVELED_ROUTE_ERROR -> - DriverStatusCodeDto.TRAVELEDROUTEERROR + DriverStatusCodeDto.TRAVELED_ROUTE_ERROR } } } diff --git a/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsBaseDriver.kt b/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsBaseDriver.kt index 4ee749d..e77a3fe 100644 --- a/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsBaseDriver.kt +++ b/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsBaseDriver.kt @@ -29,7 +29,7 @@ import java.util.concurrent.TimeUnit abstract class GoogleMapsBaseDriver( private val messenger: BinaryMessenger, - private val _authTokenEventApi: AuthTokenEventApi = AuthTokenEventApi(messenger) + private val _authTokenEventApi: AuthTokenEventApi = AuthTokenEventApi(messenger), ) { protected var driverContext: DriverContext? = null @@ -68,7 +68,7 @@ abstract class GoogleMapsBaseDriver( abstract fun initialize( providerId: String, vehicleId: String, - abnormalTerminationReportingEnabled: Boolean + abnormalTerminationReportingEnabled: Boolean, ) abstract fun isInitialized(): Boolean diff --git a/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsCommonDriverApiHandler.kt b/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsCommonDriverApiHandler.kt index 9bf16be..9cf341a 100644 --- a/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsCommonDriverApiHandler.kt +++ b/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsCommonDriverApiHandler.kt @@ -38,18 +38,18 @@ class GoogleMapsCommonDriverApiHandler( type: DriverApiTypeDto, providerId: String, vehicleId: String, - abnormalTerminationReportingEnabled: Boolean + abnormalTerminationReportingEnabled: Boolean, ) { if (deliveryDriverApi.isInitialized()) { throw FlutterError( "apiAlreadyInitialized", - "DeliveryDriverAPI instance already exists, and must be disposed before $type can be initialized" + "DeliveryDriverAPI instance already exists, and must be disposed before $type can be initialized", ) } if (ridesharingDriverApi.isInitialized()) { throw FlutterError( "apiAlreadyInitialized", - "RidesharingDriverAPI instance already exists, and must be disposed before $type can be initialized" + "RidesharingDriverAPI instance already exists, and must be disposed before $type can be initialized", ) } return getApi(type).initialize(providerId, vehicleId, abnormalTerminationReportingEnabled) diff --git a/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsDeliveryDriver.kt b/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsDeliveryDriver.kt index 40afc01..3620246 100644 --- a/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsDeliveryDriver.kt +++ b/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsDeliveryDriver.kt @@ -31,9 +31,8 @@ import com.google.common.util.concurrent.MoreExecutors import com.google.maps.flutter.navigation.GoogleMapsNavigationSessionManager import io.flutter.plugin.common.BinaryMessenger -class GoogleMapsDeliveryDriver( - private val messenger: BinaryMessenger, -) : GoogleMapsBaseDriver(messenger), DeliveryDriverApi { +class GoogleMapsDeliveryDriver(private val messenger: BinaryMessenger) : + GoogleMapsBaseDriver(messenger), DeliveryDriverApi { private var _deliveryDriverApi: NativeDeliveryDriverApi? = null private var _statusListener: GoogleMapsDriverStatusListener? = null @@ -44,13 +43,13 @@ class GoogleMapsDeliveryDriver( override fun initialize( providerId: String, vehicleId: String, - abnormalTerminationReportingEnabled: Boolean + abnormalTerminationReportingEnabled: Boolean, ) { val navigator: Navigator = GoogleMapsNavigationSessionManager.getInstance().getNavigatorWithoutError() ?: throw FlutterError( "sessionNotInitialized", - "Cannot access navigation functionality before the navigation session has been initialized." + "Cannot access navigation functionality before the navigation session has been initialized.", ) _statusListener = GoogleMapsDriverStatusListener(messenger, getActivity()) @@ -89,7 +88,7 @@ class GoogleMapsDeliveryDriver( } else { throw FlutterError( "driverNotInitialized", - "Cannot access DeliveryVehicleReporter before the DeliveryDriver has been initialized." + "Cannot access DeliveryVehicleReporter before the DeliveryDriver has been initialized.", ) } } @@ -100,7 +99,7 @@ class GoogleMapsDeliveryDriver( } else { throw FlutterError( "driverNotInitialized", - "Cannot access DeliveryVehicleManager before the DeliveryDriver has been initialized." + "Cannot access DeliveryVehicleManager before the DeliveryDriver has been initialized.", ) } } @@ -126,7 +125,7 @@ class GoogleMapsDeliveryDriver( callback(Result.failure(Convert.convertToDriverException(t))) } }, - MoreExecutors.directExecutor() + MoreExecutors.directExecutor(), ) } catch (error: Throwable) { callback(Result.failure(error)) @@ -148,7 +147,7 @@ class GoogleMapsDeliveryDriver( callback(Result.failure(Convert.convertToDriverException(t))) } }, - MoreExecutors.directExecutor() + MoreExecutors.directExecutor(), ) } catch (error: Throwable) { callback(Result.failure(error)) @@ -170,7 +169,7 @@ class GoogleMapsDeliveryDriver( callback(Result.failure(Convert.convertToDriverException(t))) } }, - MoreExecutors.directExecutor() + MoreExecutors.directExecutor(), ) } catch (error: Throwable) { callback(Result.failure(error)) @@ -192,7 +191,7 @@ class GoogleMapsDeliveryDriver( callback(Result.failure(Convert.convertToDriverException(t))) } }, - MoreExecutors.directExecutor() + MoreExecutors.directExecutor(), ) } catch (error: Throwable) { callback(Result.failure(error)) @@ -201,7 +200,7 @@ class GoogleMapsDeliveryDriver( override fun setVehicleStops( stops: List, - callback: (Result>) -> Unit + callback: (Result>) -> Unit, ) { try { val future = @@ -218,7 +217,7 @@ class GoogleMapsDeliveryDriver( callback(Result.failure(Convert.convertToDriverException(t))) } }, - MoreExecutors.directExecutor() + MoreExecutors.directExecutor(), ) } catch (error: Throwable) { callback(Result.failure(error)) @@ -240,7 +239,7 @@ class GoogleMapsDeliveryDriver( callback(Result.failure(Convert.convertToDriverException(t))) } }, - MoreExecutors.directExecutor() + MoreExecutors.directExecutor(), ) } catch (error: Throwable) { callback(Result.failure(error)) diff --git a/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsDriverPlugin.kt b/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsDriverPlugin.kt index adddaa7..69ec20a 100644 --- a/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsDriverPlugin.kt +++ b/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsDriverPlugin.kt @@ -35,7 +35,7 @@ class GoogleMapsDriverPlugin : FlutterPlugin, ActivityAware { GoogleMapsCommonDriverApiHandler( flutterPluginBinding.binaryMessenger, _deliveryDriverApi!!, - _ridesharingDriverApi!! + _ridesharingDriverApi!!, ) } diff --git a/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsDriverStatusListener.kt b/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsDriverStatusListener.kt index defc2fe..498fb5c 100644 --- a/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsDriverStatusListener.kt +++ b/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsDriverStatusListener.kt @@ -23,7 +23,7 @@ import io.flutter.plugin.common.BinaryMessenger internal class GoogleMapsDriverStatusListener( private val messenger: BinaryMessenger, - private val activity: Activity + private val activity: Activity, ) : DriverContext.DriverStatusListener { private val _statusListener: DriverStatusListenerApi = DriverStatusListenerApi(messenger) @@ -31,7 +31,7 @@ internal class GoogleMapsDriverStatusListener( level: DriverStatusListener.StatusLevel, code: DriverStatusListener.StatusCode, message: String, - error: Throwable? + error: Throwable?, ) { var errorCode: String? = null var errorMessage: String? = null @@ -45,7 +45,7 @@ internal class GoogleMapsDriverStatusListener( Convert.convertStatusCodeToDto(code), message, errorCode, - errorMessage + errorMessage, ) {} } } diff --git a/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsRidesharingDriver.kt b/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsRidesharingDriver.kt index f00d682..199fd47 100644 --- a/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsRidesharingDriver.kt +++ b/android/src/main/kotlin/com/google/maps/flutter/driver/GoogleMapsRidesharingDriver.kt @@ -24,9 +24,8 @@ import com.google.android.libraries.navigation.Navigator import com.google.maps.flutter.navigation.GoogleMapsNavigationSessionManager import io.flutter.plugin.common.BinaryMessenger -class GoogleMapsRidesharingDriver( - private val messenger: BinaryMessenger, -) : GoogleMapsBaseDriver(messenger), RidesharingDriverApi { +class GoogleMapsRidesharingDriver(private val messenger: BinaryMessenger) : + GoogleMapsBaseDriver(messenger), RidesharingDriverApi { private var _ridesharingDriverApi: NativeRidesharingDriverApi? = null private var _statusListener: GoogleMapsDriverStatusListener? = null @@ -37,13 +36,13 @@ class GoogleMapsRidesharingDriver( override fun initialize( providerId: String, vehicleId: String, - abnormalTerminationReportingEnabled: Boolean + abnormalTerminationReportingEnabled: Boolean, ) { val navigator: Navigator = GoogleMapsNavigationSessionManager.getInstance().getNavigatorWithoutError() ?: throw FlutterError( "sessionNotInitialized", - "Cannot access navigation functionality before the navigation session has been initialized." + "Cannot access navigation functionality before the navigation session has been initialized.", ) _statusListener = GoogleMapsDriverStatusListener(messenger, getActivity()) @@ -81,7 +80,7 @@ class GoogleMapsRidesharingDriver( } else { throw FlutterError( "driverNotInitialized", - "Cannot access RidesharingVehicleReporter before the RidesharingDriver has been initialized." + "Cannot access RidesharingVehicleReporter before the RidesharingDriver has been initialized.", ) } } diff --git a/android/src/main/kotlin/com/google/maps/flutter/driver/messages.g.kt b/android/src/main/kotlin/com/google/maps/flutter/driver/messages.g.kt index 0182787..633b4c7 100644 --- a/android/src/main/kotlin/com/google/maps/flutter/driver/messages.g.kt +++ b/android/src/main/kotlin/com/google/maps/flutter/driver/messages.g.kt @@ -12,8 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. // -// Autogenerated from Pigeon (v15.0.0), do not edit directly. +// Autogenerated from Pigeon (v25.3.2), do not edit directly. // See also: https://pub.dev/packages/pigeon +@file:Suppress("UNCHECKED_CAST", "ArrayInDataClass") package com.google.maps.flutter.driver @@ -25,28 +26,57 @@ import io.flutter.plugin.common.StandardMessageCodec import java.io.ByteArrayOutputStream import java.nio.ByteBuffer -private fun wrapResult(result: Any?): List { - return listOf(result) -} +private object MessagesPigeonUtils { -private fun wrapError(exception: Throwable): List { - if (exception is FlutterError) { - return listOf(exception.code, exception.message, exception.details) - } else { - return listOf( - exception.javaClass.simpleName, - exception.toString(), - "Cause: " + exception.cause + ", Stacktrace: " + Log.getStackTraceString(exception) + fun createConnectionError(channelName: String): FlutterError { + return FlutterError( + "channel-error", + "Unable to establish connection on channel: '$channelName'.", + "", ) } -} -private fun createConnectionError(channelName: String): FlutterError { - return FlutterError( - "channel-error", - "Unable to establish connection on channel: '$channelName'.", - "" - ) + fun wrapResult(result: Any?): List { + return listOf(result) + } + + fun wrapError(exception: Throwable): List { + return if (exception is FlutterError) { + listOf(exception.code, exception.message, exception.details) + } else { + listOf( + exception.javaClass.simpleName, + exception.toString(), + "Cause: " + exception.cause + ", Stacktrace: " + Log.getStackTraceString(exception), + ) + } + } + + fun deepEquals(a: Any?, b: Any?): Boolean { + if (a is ByteArray && b is ByteArray) { + return a.contentEquals(b) + } + if (a is IntArray && b is IntArray) { + return a.contentEquals(b) + } + if (a is LongArray && b is LongArray) { + return a.contentEquals(b) + } + if (a is DoubleArray && b is DoubleArray) { + return a.contentEquals(b) + } + if (a is Array<*> && b is Array<*>) { + return a.size == b.size && a.indices.all { deepEquals(a[it], b[it]) } + } + if (a is List<*> && b is List<*>) { + return a.size == b.size && a.indices.all { deepEquals(a[it], b[it]) } + } + if (a is Map<*, *> && b is Map<*, *>) { + return a.size == b.size && + a.all { (b as Map).containsKey(it.key) && deepEquals(it.value, b[it.key]) } + } + return a == b + } } /** @@ -59,7 +89,7 @@ private fun createConnectionError(channelName: String): FlutterError { class FlutterError( val code: String, override val message: String? = null, - val details: Any? = null + val details: Any? = null, ) : Throwable() /** Indicates the API type for a driver. */ @@ -77,8 +107,8 @@ enum class DriverApiTypeDto(val raw: Int) { } enum class VehicleStopStateDto(val raw: Int) { - STATEUNSPECIFIED(0), - NEWSTOP(1), + STATE_UNSPECIFIED(0), + NEW_STOP(1), ENROUTE(2), ARRIVED(3); @@ -116,14 +146,14 @@ enum class DriverStatusLevelDto(val raw: Int) { } enum class DriverStatusCodeDto(val raw: Int) { - DEFAULTSTATUS(0), - UNKNOWNERROR(1), - VEHICLENOTFOUND(2), - BACKENDCONNECTIVITYERROR(3), - PERMISSIONDENIED(4), - SERVICEERROR(5), - FILEACCESSERROR(6), - TRAVELEDROUTEERROR(7); + DEFAULT_STATUS(0), + UNKNOWN_ERROR(1), + VEHICLE_NOT_FOUND(2), + BACKEND_CONNECTIVITY_ERROR(3), + PERMISSION_DENIED(4), + SERVICE_ERROR(5), + FILE_ACCESS_ERROR(6), + TRAVELED_ROUTE_ERROR(7); companion object { fun ofRaw(raw: Int): DriverStatusCodeDto? { @@ -134,68 +164,88 @@ enum class DriverStatusCodeDto(val raw: Int) { /** Generated class from Pigeon that represents data sent in messages. */ data class TaskInfoDto(val taskId: String, val durationSeconds: Long) { - companion object { - @Suppress("UNCHECKED_CAST") - fun fromList(list: List): TaskInfoDto { - val taskId = list[0] as String - val durationSeconds = list[1].let { if (it is Int) it.toLong() else it as Long } + fun fromList(pigeonVar_list: List): TaskInfoDto { + val taskId = pigeonVar_list[0] as String + val durationSeconds = pigeonVar_list[1] as Long return TaskInfoDto(taskId, durationSeconds) } } fun toList(): List { - return listOf( - taskId, - durationSeconds, - ) + return listOf(taskId, durationSeconds) + } + + override fun equals(other: Any?): Boolean { + if (other !is TaskInfoDto) { + return false + } + if (this === other) { + return true + } + return MessagesPigeonUtils.deepEquals(toList(), other.toList()) } + + override fun hashCode(): Int = toList().hashCode() } /** Generated class from Pigeon that represents data sent in messages. */ data class VehicleStopDto( val vehicleStopState: VehicleStopStateDto, val waypoint: NavigationWaypointDto? = null, - val taskInfoList: List + val taskInfoList: List, ) { companion object { - @Suppress("UNCHECKED_CAST") - fun fromList(list: List): VehicleStopDto { - val vehicleStopState = VehicleStopStateDto.ofRaw(list[0] as Int)!! - val waypoint: NavigationWaypointDto? = - (list[1] as List?)?.let { NavigationWaypointDto.fromList(it) } - val taskInfoList = list[2] as List + fun fromList(pigeonVar_list: List): VehicleStopDto { + val vehicleStopState = pigeonVar_list[0] as VehicleStopStateDto + val waypoint = pigeonVar_list[1] as NavigationWaypointDto? + val taskInfoList = pigeonVar_list[2] as List return VehicleStopDto(vehicleStopState, waypoint, taskInfoList) } } fun toList(): List { - return listOf( - vehicleStopState.raw, - waypoint?.toList(), - taskInfoList, - ) + return listOf(vehicleStopState, waypoint, taskInfoList) + } + + override fun equals(other: Any?): Boolean { + if (other !is VehicleStopDto) { + return false + } + if (this === other) { + return true + } + return MessagesPigeonUtils.deepEquals(toList(), other.toList()) } + + override fun hashCode(): Int = toList().hashCode() } /** Generated class from Pigeon that represents data sent in messages. */ data class LatLngDto(val latitude: Double, val longitude: Double) { - companion object { - @Suppress("UNCHECKED_CAST") - fun fromList(list: List): LatLngDto { - val latitude = list[0] as Double - val longitude = list[1] as Double + fun fromList(pigeonVar_list: List): LatLngDto { + val latitude = pigeonVar_list[0] as Double + val longitude = pigeonVar_list[1] as Double return LatLngDto(latitude, longitude) } } fun toList(): List { - return listOf( - latitude, - longitude, - ) + return listOf(latitude, longitude) } + + override fun equals(other: Any?): Boolean { + if (other !is LatLngDto) { + return false + } + if (this === other) { + return true + } + return MessagesPigeonUtils.deepEquals(toList(), other.toList()) + } + + override fun hashCode(): Int = toList().hashCode() } /** Generated class from Pigeon that represents data sent in messages. */ @@ -204,35 +254,40 @@ data class NavigationWaypointDto( val target: LatLngDto? = null, val placeID: String? = null, val preferSameSideOfRoad: Boolean? = null, - val preferredSegmentHeading: Long? = null + val preferredSegmentHeading: Long? = null, ) { companion object { - @Suppress("UNCHECKED_CAST") - fun fromList(list: List): NavigationWaypointDto { - val title = list[0] as String - val target: LatLngDto? = (list[1] as List?)?.let { LatLngDto.fromList(it) } - val placeID = list[2] as String? - val preferSameSideOfRoad = list[3] as Boolean? - val preferredSegmentHeading = list[4].let { if (it is Int) it.toLong() else it as Long? } + fun fromList(pigeonVar_list: List): NavigationWaypointDto { + val title = pigeonVar_list[0] as String + val target = pigeonVar_list[1] as LatLngDto? + val placeID = pigeonVar_list[2] as String? + val preferSameSideOfRoad = pigeonVar_list[3] as Boolean? + val preferredSegmentHeading = pigeonVar_list[4] as Long? return NavigationWaypointDto( title, target, placeID, preferSameSideOfRoad, - preferredSegmentHeading + preferredSegmentHeading, ) } } fun toList(): List { - return listOf( - title, - target?.toList(), - placeID, - preferSameSideOfRoad, - preferredSegmentHeading, - ) + return listOf(title, target, placeID, preferSameSideOfRoad, preferredSegmentHeading) } + + override fun equals(other: Any?): Boolean { + if (other !is NavigationWaypointDto) { + return false + } + if (this === other) { + return true + } + return MessagesPigeonUtils.deepEquals(toList(), other.toList()) + } + + override fun hashCode(): Int = toList().hashCode() } /** Generated class from Pigeon that represents data sent in messages. */ @@ -246,21 +301,20 @@ data class LocationDto( val longitude: Double? = null, val provider: String? = null, val speed: Double? = null, - val time: Long? = null + val time: Long? = null, ) { companion object { - @Suppress("UNCHECKED_CAST") - fun fromList(list: List): LocationDto { - val accuracy = list[0] as Double? - val altitude = list[1] as Double? - val elapsedRealtimeNanos = list[2].let { if (it is Int) it.toLong() else it as Long? } - val bearing = list[3] as Double? - val isMock = list[4] as Boolean? - val latitude = list[5] as Double? - val longitude = list[6] as Double? - val provider = list[7] as String? - val speed = list[8] as Double? - val time = list[9].let { if (it is Int) it.toLong() else it as Long? } + fun fromList(pigeonVar_list: List): LocationDto { + val accuracy = pigeonVar_list[0] as Double? + val altitude = pigeonVar_list[1] as Double? + val elapsedRealtimeNanos = pigeonVar_list[2] as Long? + val bearing = pigeonVar_list[3] as Double? + val isMock = pigeonVar_list[4] as Boolean? + val latitude = pigeonVar_list[5] as Double? + val longitude = pigeonVar_list[6] as Double? + val provider = pigeonVar_list[7] as String? + val speed = pigeonVar_list[8] as Double? + val time = pigeonVar_list[9] as Long? return LocationDto( accuracy, altitude, @@ -271,13 +325,13 @@ data class LocationDto( longitude, provider, speed, - time + time, ) } } fun toList(): List { - return listOf( + return listOf( accuracy, altitude, elapsedRealtimeNanos, @@ -290,6 +344,18 @@ data class LocationDto( time, ) } + + override fun equals(other: Any?): Boolean { + if (other !is LocationDto) { + return false + } + if (this === other) { + return true + } + return MessagesPigeonUtils.deepEquals(toList(), other.toList()) + } + + override fun hashCode(): Int = toList().hashCode() } /** Generated class from Pigeon that represents data sent in messages. */ @@ -297,27 +363,33 @@ data class DeliveryVehicleDto( val providerId: String, val id: String, val name: String, - val stops: List + val stops: List, ) { companion object { - @Suppress("UNCHECKED_CAST") - fun fromList(list: List): DeliveryVehicleDto { - val providerId = list[0] as String - val id = list[1] as String - val name = list[2] as String - val stops = list[3] as List + fun fromList(pigeonVar_list: List): DeliveryVehicleDto { + val providerId = pigeonVar_list[0] as String + val id = pigeonVar_list[1] as String + val name = pigeonVar_list[2] as String + val stops = pigeonVar_list[3] as List return DeliveryVehicleDto(providerId, id, name, stops) } } fun toList(): List { - return listOf( - providerId, - id, - name, - stops, - ) + return listOf(providerId, id, name, stops) } + + override fun equals(other: Any?): Boolean { + if (other !is DeliveryVehicleDto) { + return false + } + if (this === other) { + return true + } + return MessagesPigeonUtils.deepEquals(toList(), other.toList()) + } + + override fun hashCode(): Int = toList().hashCode() } /** Generated class from Pigeon that represents data sent in messages. */ @@ -327,56 +399,142 @@ data class VehicleUpdateDto( val destinationWaypoint: NavigationWaypointDto? = null, val route: List? = null, val remainingTimeInSeconds: Double? = null, - val remainingDistanceInMeters: Double? = null + val remainingDistanceInMeters: Double? = null, ) { companion object { - @Suppress("UNCHECKED_CAST") - fun fromList(list: List): VehicleUpdateDto { - val vehicleState: VehicleStateDto? = (list[0] as Int?)?.let { VehicleStateDto.ofRaw(it) } - val location: LatLngDto? = (list[1] as List?)?.let { LatLngDto.fromList(it) } - val destinationWaypoint: NavigationWaypointDto? = - (list[2] as List?)?.let { NavigationWaypointDto.fromList(it) } - val route = list[3] as List? - val remainingTimeInSeconds = list[4] as Double? - val remainingDistanceInMeters = list[5] as Double? + fun fromList(pigeonVar_list: List): VehicleUpdateDto { + val vehicleState = pigeonVar_list[0] as VehicleStateDto? + val location = pigeonVar_list[1] as LatLngDto? + val destinationWaypoint = pigeonVar_list[2] as NavigationWaypointDto? + val route = pigeonVar_list[3] as List? + val remainingTimeInSeconds = pigeonVar_list[4] as Double? + val remainingDistanceInMeters = pigeonVar_list[5] as Double? return VehicleUpdateDto( vehicleState, location, destinationWaypoint, route, remainingTimeInSeconds, - remainingDistanceInMeters + remainingDistanceInMeters, ) } } fun toList(): List { - return listOf( - vehicleState?.raw, - location?.toList(), - destinationWaypoint?.toList(), + return listOf( + vehicleState, + location, + destinationWaypoint, route, remainingTimeInSeconds, remainingDistanceInMeters, ) } + + override fun equals(other: Any?): Boolean { + if (other !is VehicleUpdateDto) { + return false + } + if (this === other) { + return true + } + return MessagesPigeonUtils.deepEquals(toList(), other.toList()) + } + + override fun hashCode(): Int = toList().hashCode() } -@Suppress("UNCHECKED_CAST") -private object CommonDriverApiCodec : StandardMessageCodec() { +private open class messagesPigeonCodec : StandardMessageCodec() { override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { return when (type) { - 128.toByte() -> { + 129.toByte() -> { + return (readValue(buffer) as Long?)?.let { DriverApiTypeDto.ofRaw(it.toInt()) } + } + 130.toByte() -> { + return (readValue(buffer) as Long?)?.let { VehicleStopStateDto.ofRaw(it.toInt()) } + } + 131.toByte() -> { + return (readValue(buffer) as Long?)?.let { VehicleStateDto.ofRaw(it.toInt()) } + } + 132.toByte() -> { + return (readValue(buffer) as Long?)?.let { DriverStatusLevelDto.ofRaw(it.toInt()) } + } + 133.toByte() -> { + return (readValue(buffer) as Long?)?.let { DriverStatusCodeDto.ofRaw(it.toInt()) } + } + 134.toByte() -> { + return (readValue(buffer) as? List)?.let { TaskInfoDto.fromList(it) } + } + 135.toByte() -> { + return (readValue(buffer) as? List)?.let { VehicleStopDto.fromList(it) } + } + 136.toByte() -> { + return (readValue(buffer) as? List)?.let { LatLngDto.fromList(it) } + } + 137.toByte() -> { + return (readValue(buffer) as? List)?.let { NavigationWaypointDto.fromList(it) } + } + 138.toByte() -> { return (readValue(buffer) as? List)?.let { LocationDto.fromList(it) } } + 139.toByte() -> { + return (readValue(buffer) as? List)?.let { DeliveryVehicleDto.fromList(it) } + } + 140.toByte() -> { + return (readValue(buffer) as? List)?.let { VehicleUpdateDto.fromList(it) } + } else -> super.readValueOfType(type, buffer) } } override fun writeValue(stream: ByteArrayOutputStream, value: Any?) { when (value) { + is DriverApiTypeDto -> { + stream.write(129) + writeValue(stream, value.raw) + } + is VehicleStopStateDto -> { + stream.write(130) + writeValue(stream, value.raw) + } + is VehicleStateDto -> { + stream.write(131) + writeValue(stream, value.raw) + } + is DriverStatusLevelDto -> { + stream.write(132) + writeValue(stream, value.raw) + } + is DriverStatusCodeDto -> { + stream.write(133) + writeValue(stream, value.raw) + } + is TaskInfoDto -> { + stream.write(134) + writeValue(stream, value.toList()) + } + is VehicleStopDto -> { + stream.write(135) + writeValue(stream, value.toList()) + } + is LatLngDto -> { + stream.write(136) + writeValue(stream, value.toList()) + } + is NavigationWaypointDto -> { + stream.write(137) + writeValue(stream, value.toList()) + } is LocationDto -> { - stream.write(128) + stream.write(138) + writeValue(stream, value.toList()) + } + is DeliveryVehicleDto -> { + stream.write(139) + writeValue(stream, value.toList()) + } + is VehicleUpdateDto -> { + stream.write(140) writeValue(stream, value.toList()) } else -> super.writeValue(stream, value) @@ -390,7 +548,7 @@ interface CommonDriverApi { type: DriverApiTypeDto, providerId: String, vehicleId: String, - abnormalTerminationReportingEnabled: Boolean + abnormalTerminationReportingEnabled: Boolean, ) fun isInitialized(type: DriverApiTypeDto): Boolean @@ -415,38 +573,45 @@ interface CommonDriverApi { companion object { /** The codec used by CommonDriverApi. */ - val codec: MessageCodec by lazy { CommonDriverApiCodec } + val codec: MessageCodec by lazy { messagesPigeonCodec() } + /** * Sets up an instance of `CommonDriverApi` to handle messages through the `binaryMessenger`. */ - @Suppress("UNCHECKED_CAST") - fun setUp(binaryMessenger: BinaryMessenger, api: CommonDriverApi?) { + @JvmOverloads + fun setUp( + binaryMessenger: BinaryMessenger, + api: CommonDriverApi?, + messageChannelSuffix: String = "", + ) { + val separatedMessageChannelSuffix = + if (messageChannelSuffix.isNotEmpty()) ".$messageChannelSuffix" else "" run { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize", - codec + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List - val typeArg = DriverApiTypeDto.ofRaw(args[0] as Int)!! + val typeArg = args[0] as DriverApiTypeDto val providerIdArg = args[1] as String val vehicleIdArg = args[2] as String val abnormalTerminationReportingEnabledArg = args[3] as Boolean - var wrapped: List - try { - api.initialize( - typeArg, - providerIdArg, - vehicleIdArg, - abnormalTerminationReportingEnabledArg - ) - wrapped = listOf(null) - } catch (exception: Throwable) { - wrapped = wrapError(exception) - } + val wrapped: List = + try { + api.initialize( + typeArg, + providerIdArg, + vehicleIdArg, + abnormalTerminationReportingEnabledArg, + ) + listOf(null) + } catch (exception: Throwable) { + MessagesPigeonUtils.wrapError(exception) + } reply.reply(wrapped) } } else { @@ -457,19 +622,19 @@ interface CommonDriverApi { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isInitialized", - codec + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isInitialized$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List - val typeArg = DriverApiTypeDto.ofRaw(args[0] as Int)!! - var wrapped: List - try { - wrapped = listOf(api.isInitialized(typeArg)) - } catch (exception: Throwable) { - wrapped = wrapError(exception) - } + val typeArg = args[0] as DriverApiTypeDto + val wrapped: List = + try { + listOf(api.isInitialized(typeArg)) + } catch (exception: Throwable) { + MessagesPigeonUtils.wrapError(exception) + } reply.reply(wrapped) } } else { @@ -480,19 +645,19 @@ interface CommonDriverApi { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getProviderId", - codec + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getProviderId$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List - val typeArg = DriverApiTypeDto.ofRaw(args[0] as Int)!! - var wrapped: List - try { - wrapped = listOf(api.getProviderId(typeArg)) - } catch (exception: Throwable) { - wrapped = wrapError(exception) - } + val typeArg = args[0] as DriverApiTypeDto + val wrapped: List = + try { + listOf(api.getProviderId(typeArg)) + } catch (exception: Throwable) { + MessagesPigeonUtils.wrapError(exception) + } reply.reply(wrapped) } } else { @@ -503,19 +668,19 @@ interface CommonDriverApi { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getVehicleId", - codec + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getVehicleId$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List - val typeArg = DriverApiTypeDto.ofRaw(args[0] as Int)!! - var wrapped: List - try { - wrapped = listOf(api.getVehicleId(typeArg)) - } catch (exception: Throwable) { - wrapped = wrapError(exception) - } + val typeArg = args[0] as DriverApiTypeDto + val wrapped: List = + try { + listOf(api.getVehicleId(typeArg)) + } catch (exception: Throwable) { + MessagesPigeonUtils.wrapError(exception) + } reply.reply(wrapped) } } else { @@ -526,19 +691,19 @@ interface CommonDriverApi { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isLocationTrackingEnabled", - codec + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isLocationTrackingEnabled$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List - val typeArg = DriverApiTypeDto.ofRaw(args[0] as Int)!! - var wrapped: List - try { - wrapped = listOf(api.isLocationTrackingEnabled(typeArg)) - } catch (exception: Throwable) { - wrapped = wrapError(exception) - } + val typeArg = args[0] as DriverApiTypeDto + val wrapped: List = + try { + listOf(api.isLocationTrackingEnabled(typeArg)) + } catch (exception: Throwable) { + MessagesPigeonUtils.wrapError(exception) + } reply.reply(wrapped) } } else { @@ -549,21 +714,21 @@ interface CommonDriverApi { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationTrackingEnabled", - codec + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationTrackingEnabled$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List - val typeArg = DriverApiTypeDto.ofRaw(args[0] as Int)!! + val typeArg = args[0] as DriverApiTypeDto val enabledArg = args[1] as Boolean - var wrapped: List - try { - api.setLocationTrackingEnabled(typeArg, enabledArg) - wrapped = listOf(null) - } catch (exception: Throwable) { - wrapped = wrapError(exception) - } + val wrapped: List = + try { + api.setLocationTrackingEnabled(typeArg, enabledArg) + listOf(null) + } catch (exception: Throwable) { + MessagesPigeonUtils.wrapError(exception) + } reply.reply(wrapped) } } else { @@ -574,19 +739,19 @@ interface CommonDriverApi { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getLocationReportingIntervalMillis", - codec + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getLocationReportingIntervalMillis$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List - val typeArg = DriverApiTypeDto.ofRaw(args[0] as Int)!! - var wrapped: List - try { - wrapped = listOf(api.getLocationReportingIntervalMillis(typeArg)) - } catch (exception: Throwable) { - wrapped = wrapError(exception) - } + val typeArg = args[0] as DriverApiTypeDto + val wrapped: List = + try { + listOf(api.getLocationReportingIntervalMillis(typeArg)) + } catch (exception: Throwable) { + MessagesPigeonUtils.wrapError(exception) + } reply.reply(wrapped) } } else { @@ -597,21 +762,21 @@ interface CommonDriverApi { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationReportingIntervalMillis", - codec + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationReportingIntervalMillis$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List - val typeArg = DriverApiTypeDto.ofRaw(args[0] as Int)!! - val millisecondsArg = args[1].let { if (it is Int) it.toLong() else it as Long } - var wrapped: List - try { - api.setLocationReportingIntervalMillis(typeArg, millisecondsArg) - wrapped = listOf(null) - } catch (exception: Throwable) { - wrapped = wrapError(exception) - } + val typeArg = args[0] as DriverApiTypeDto + val millisecondsArg = args[1] as Long + val wrapped: List = + try { + api.setLocationReportingIntervalMillis(typeArg, millisecondsArg) + listOf(null) + } catch (exception: Throwable) { + MessagesPigeonUtils.wrapError(exception) + } reply.reply(wrapped) } } else { @@ -622,20 +787,20 @@ interface CommonDriverApi { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.dispose", - codec + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.dispose$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List - val typeArg = DriverApiTypeDto.ofRaw(args[0] as Int)!! - var wrapped: List - try { - api.dispose(typeArg) - wrapped = listOf(null) - } catch (exception: Throwable) { - wrapped = wrapError(exception) - } + val typeArg = args[0] as DriverApiTypeDto + val wrapped: List = + try { + api.dispose(typeArg) + listOf(null) + } catch (exception: Throwable) { + MessagesPigeonUtils.wrapError(exception) + } reply.reply(wrapped) } } else { @@ -646,19 +811,19 @@ interface CommonDriverApi { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getDriverSdkVersion", - codec + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getDriverSdkVersion$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List - val typeArg = DriverApiTypeDto.ofRaw(args[0] as Int)!! - var wrapped: List - try { - wrapped = listOf(api.getDriverSdkVersion(typeArg)) - } catch (exception: Throwable) { - wrapped = wrapError(exception) - } + val typeArg = args[0] as DriverApiTypeDto + val wrapped: List = + try { + listOf(api.getDriverSdkVersion(typeArg)) + } catch (exception: Throwable) { + MessagesPigeonUtils.wrapError(exception) + } reply.reply(wrapped) } } else { @@ -669,21 +834,21 @@ interface CommonDriverApi { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setSupplementalLocation", - codec + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setSupplementalLocation$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List - val typeArg = DriverApiTypeDto.ofRaw(args[0] as Int)!! + val typeArg = args[0] as DriverApiTypeDto val locationArg = args[1] as LocationDto - var wrapped: List - try { - api.setSupplementalLocation(typeArg, locationArg) - wrapped = listOf(null) - } catch (exception: Throwable) { - wrapped = wrapError(exception) - } + val wrapped: List = + try { + api.setSupplementalLocation(typeArg, locationArg) + listOf(null) + } catch (exception: Throwable) { + MessagesPigeonUtils.wrapError(exception) + } reply.reply(wrapped) } } else { @@ -694,56 +859,6 @@ interface CommonDriverApi { } } -@Suppress("UNCHECKED_CAST") -private object DeliveryDriverApiCodec : StandardMessageCodec() { - override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { - return when (type) { - 128.toByte() -> { - return (readValue(buffer) as? List)?.let { DeliveryVehicleDto.fromList(it) } - } - 129.toByte() -> { - return (readValue(buffer) as? List)?.let { LatLngDto.fromList(it) } - } - 130.toByte() -> { - return (readValue(buffer) as? List)?.let { NavigationWaypointDto.fromList(it) } - } - 131.toByte() -> { - return (readValue(buffer) as? List)?.let { TaskInfoDto.fromList(it) } - } - 132.toByte() -> { - return (readValue(buffer) as? List)?.let { VehicleStopDto.fromList(it) } - } - else -> super.readValueOfType(type, buffer) - } - } - - override fun writeValue(stream: ByteArrayOutputStream, value: Any?) { - when (value) { - is DeliveryVehicleDto -> { - stream.write(128) - writeValue(stream, value.toList()) - } - is LatLngDto -> { - stream.write(129) - writeValue(stream, value.toList()) - } - is NavigationWaypointDto -> { - stream.write(130) - writeValue(stream, value.toList()) - } - is TaskInfoDto -> { - stream.write(131) - writeValue(stream, value.toList()) - } - is VehicleStopDto -> { - stream.write(132) - writeValue(stream, value.toList()) - } - else -> super.writeValue(stream, value) - } - } -} - /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ interface DeliveryDriverApi { fun arrivedAtStop(callback: (Result>) -> Unit) @@ -760,28 +875,35 @@ interface DeliveryDriverApi { companion object { /** The codec used by DeliveryDriverApi. */ - val codec: MessageCodec by lazy { DeliveryDriverApiCodec } + val codec: MessageCodec by lazy { messagesPigeonCodec() } + /** * Sets up an instance of `DeliveryDriverApi` to handle messages through the `binaryMessenger`. */ - @Suppress("UNCHECKED_CAST") - fun setUp(binaryMessenger: BinaryMessenger, api: DeliveryDriverApi?) { + @JvmOverloads + fun setUp( + binaryMessenger: BinaryMessenger, + api: DeliveryDriverApi?, + messageChannelSuffix: String = "", + ) { + val separatedMessageChannelSuffix = + if (messageChannelSuffix.isNotEmpty()) ".$messageChannelSuffix" else "" run { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.arrivedAtStop", - codec + "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.arrivedAtStop$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { _, reply -> - api.arrivedAtStop() { result: Result> -> + api.arrivedAtStop { result: Result> -> val error = result.exceptionOrNull() if (error != null) { - reply.reply(wrapError(error)) + reply.reply(MessagesPigeonUtils.wrapError(error)) } else { val data = result.getOrNull() - reply.reply(wrapResult(data)) + reply.reply(MessagesPigeonUtils.wrapResult(data)) } } } @@ -793,18 +915,18 @@ interface DeliveryDriverApi { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.completedStop", - codec + "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.completedStop$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { _, reply -> - api.completedStop() { result: Result> -> + api.completedStop { result: Result> -> val error = result.exceptionOrNull() if (error != null) { - reply.reply(wrapError(error)) + reply.reply(MessagesPigeonUtils.wrapError(error)) } else { val data = result.getOrNull() - reply.reply(wrapResult(data)) + reply.reply(MessagesPigeonUtils.wrapResult(data)) } } } @@ -816,18 +938,18 @@ interface DeliveryDriverApi { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.enrouteToNextStop", - codec + "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.enrouteToNextStop$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { _, reply -> - api.enrouteToNextStop() { result: Result> -> + api.enrouteToNextStop { result: Result> -> val error = result.exceptionOrNull() if (error != null) { - reply.reply(wrapError(error)) + reply.reply(MessagesPigeonUtils.wrapError(error)) } else { val data = result.getOrNull() - reply.reply(wrapResult(data)) + reply.reply(MessagesPigeonUtils.wrapResult(data)) } } } @@ -839,18 +961,18 @@ interface DeliveryDriverApi { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.getRemainingVehicleStops", - codec + "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.getRemainingVehicleStops$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { _, reply -> - api.getRemainingVehicleStops() { result: Result> -> + api.getRemainingVehicleStops { result: Result> -> val error = result.exceptionOrNull() if (error != null) { - reply.reply(wrapError(error)) + reply.reply(MessagesPigeonUtils.wrapError(error)) } else { val data = result.getOrNull() - reply.reply(wrapResult(data)) + reply.reply(MessagesPigeonUtils.wrapResult(data)) } } } @@ -862,8 +984,8 @@ interface DeliveryDriverApi { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.setVehicleStops", - codec + "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.setVehicleStops$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { message, reply -> @@ -872,10 +994,10 @@ interface DeliveryDriverApi { api.setVehicleStops(stopsArg) { result: Result> -> val error = result.exceptionOrNull() if (error != null) { - reply.reply(wrapError(error)) + reply.reply(MessagesPigeonUtils.wrapError(error)) } else { val data = result.getOrNull() - reply.reply(wrapResult(data)) + reply.reply(MessagesPigeonUtils.wrapResult(data)) } } } @@ -887,18 +1009,18 @@ interface DeliveryDriverApi { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.getDeliveryVehicle", - codec + "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.getDeliveryVehicle$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { _, reply -> - api.getDeliveryVehicle() { result: Result -> + api.getDeliveryVehicle { result: Result -> val error = result.exceptionOrNull() if (error != null) { - reply.reply(wrapError(error)) + reply.reply(MessagesPigeonUtils.wrapError(error)) } else { val data = result.getOrNull() - reply.reply(wrapResult(data)) + reply.reply(MessagesPigeonUtils.wrapResult(data)) } } } @@ -909,37 +1031,45 @@ interface DeliveryDriverApi { } } } + /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ interface RidesharingDriverApi { fun setVehicleState(state: VehicleStateDto) companion object { /** The codec used by RidesharingDriverApi. */ - val codec: MessageCodec by lazy { StandardMessageCodec() } + val codec: MessageCodec by lazy { messagesPigeonCodec() } + /** * Sets up an instance of `RidesharingDriverApi` to handle messages through the * `binaryMessenger`. */ - @Suppress("UNCHECKED_CAST") - fun setUp(binaryMessenger: BinaryMessenger, api: RidesharingDriverApi?) { + @JvmOverloads + fun setUp( + binaryMessenger: BinaryMessenger, + api: RidesharingDriverApi?, + messageChannelSuffix: String = "", + ) { + val separatedMessageChannelSuffix = + if (messageChannelSuffix.isNotEmpty()) ".$messageChannelSuffix" else "" run { val channel = BasicMessageChannel( binaryMessenger, - "dev.flutter.pigeon.google_driver_flutter.RidesharingDriverApi.setVehicleState", - codec + "dev.flutter.pigeon.google_driver_flutter.RidesharingDriverApi.setVehicleState$separatedMessageChannelSuffix", + codec, ) if (api != null) { channel.setMessageHandler { message, reply -> val args = message as List - val stateArg = VehicleStateDto.ofRaw(args[0] as Int)!! - var wrapped: List - try { - api.setVehicleState(stateArg) - wrapped = listOf(null) - } catch (exception: Throwable) { - wrapped = wrapError(exception) - } + val stateArg = args[0] as VehicleStateDto + val wrapped: List = + try { + api.setVehicleState(stateArg) + listOf(null) + } catch (exception: Throwable) { + MessagesPigeonUtils.wrapError(exception) + } reply.reply(wrapped) } } else { @@ -949,16 +1079,22 @@ interface RidesharingDriverApi { } } } + /** Generated class from Pigeon that represents Flutter messages that can be called from Kotlin. */ -@Suppress("UNCHECKED_CAST") -class AuthTokenEventApi(private val binaryMessenger: BinaryMessenger) { +class AuthTokenEventApi( + private val binaryMessenger: BinaryMessenger, + private val messageChannelSuffix: String = "", +) { companion object { /** The codec used by AuthTokenEventApi. */ - val codec: MessageCodec by lazy { StandardMessageCodec() } + val codec: MessageCodec by lazy { messagesPigeonCodec() } } fun getToken(taskIdArg: String?, vehicleIdArg: String?, callback: (Result) -> Unit) { - val channelName = "dev.flutter.pigeon.google_driver_flutter.AuthTokenEventApi.getToken" + val separatedMessageChannelSuffix = + if (messageChannelSuffix.isNotEmpty()) ".$messageChannelSuffix" else "" + val channelName = + "dev.flutter.pigeon.google_driver_flutter.AuthTokenEventApi.getToken$separatedMessageChannelSuffix" val channel = BasicMessageChannel(binaryMessenger, channelName, codec) channel.send(listOf(taskIdArg, vehicleIdArg)) { if (it is List<*>) { @@ -970,7 +1106,7 @@ class AuthTokenEventApi(private val binaryMessenger: BinaryMessenger) { FlutterError( "null-error", "Flutter api returned null value for non-null return value.", - "" + "", ) ) ) @@ -979,66 +1115,27 @@ class AuthTokenEventApi(private val binaryMessenger: BinaryMessenger) { callback(Result.success(output)) } } else { - callback(Result.failure(createConnectionError(channelName))) - } - } - } -} - -@Suppress("UNCHECKED_CAST") -private object VehicleReporterListenerApiCodec : StandardMessageCodec() { - override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { - return when (type) { - 128.toByte() -> { - return (readValue(buffer) as? List)?.let { LatLngDto.fromList(it) } - } - 129.toByte() -> { - return (readValue(buffer) as? List)?.let { LatLngDto.fromList(it) } - } - 130.toByte() -> { - return (readValue(buffer) as? List)?.let { NavigationWaypointDto.fromList(it) } - } - 131.toByte() -> { - return (readValue(buffer) as? List)?.let { VehicleUpdateDto.fromList(it) } + callback(Result.failure(MessagesPigeonUtils.createConnectionError(channelName))) } - else -> super.readValueOfType(type, buffer) - } - } - - override fun writeValue(stream: ByteArrayOutputStream, value: Any?) { - when (value) { - is LatLngDto -> { - stream.write(128) - writeValue(stream, value.toList()) - } - is LatLngDto -> { - stream.write(129) - writeValue(stream, value.toList()) - } - is NavigationWaypointDto -> { - stream.write(130) - writeValue(stream, value.toList()) - } - is VehicleUpdateDto -> { - stream.write(131) - writeValue(stream, value.toList()) - } - else -> super.writeValue(stream, value) } } } /** Generated class from Pigeon that represents Flutter messages that can be called from Kotlin. */ -@Suppress("UNCHECKED_CAST") -class VehicleReporterListenerApi(private val binaryMessenger: BinaryMessenger) { +class VehicleReporterListenerApi( + private val binaryMessenger: BinaryMessenger, + private val messageChannelSuffix: String = "", +) { companion object { /** The codec used by VehicleReporterListenerApi. */ - val codec: MessageCodec by lazy { VehicleReporterListenerApiCodec } + val codec: MessageCodec by lazy { messagesPigeonCodec() } } fun onDidSucceed(vehicleUpdateArg: VehicleUpdateDto, callback: (Result) -> Unit) { + val separatedMessageChannelSuffix = + if (messageChannelSuffix.isNotEmpty()) ".$messageChannelSuffix" else "" val channelName = - "dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidSucceed" + "dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidSucceed$separatedMessageChannelSuffix" val channel = BasicMessageChannel(binaryMessenger, channelName, codec) channel.send(listOf(vehicleUpdateArg)) { if (it is List<*>) { @@ -1048,7 +1145,7 @@ class VehicleReporterListenerApi(private val binaryMessenger: BinaryMessenger) { callback(Result.success(Unit)) } } else { - callback(Result.failure(createConnectionError(channelName))) + callback(Result.failure(MessagesPigeonUtils.createConnectionError(channelName))) } } } @@ -1057,10 +1154,12 @@ class VehicleReporterListenerApi(private val binaryMessenger: BinaryMessenger) { vehicleUpdateArg: VehicleUpdateDto, errorCodeArg: String, errorMessageArg: String, - callback: (Result) -> Unit + callback: (Result) -> Unit, ) { + val separatedMessageChannelSuffix = + if (messageChannelSuffix.isNotEmpty()) ".$messageChannelSuffix" else "" val channelName = - "dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidFail" + "dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidFail$separatedMessageChannelSuffix" val channel = BasicMessageChannel(binaryMessenger, channelName, codec) channel.send(listOf(vehicleUpdateArg, errorCodeArg, errorMessageArg)) { if (it is List<*>) { @@ -1070,17 +1169,20 @@ class VehicleReporterListenerApi(private val binaryMessenger: BinaryMessenger) { callback(Result.success(Unit)) } } else { - callback(Result.failure(createConnectionError(channelName))) + callback(Result.failure(MessagesPigeonUtils.createConnectionError(channelName))) } } } } + /** Generated class from Pigeon that represents Flutter messages that can be called from Kotlin. */ -@Suppress("UNCHECKED_CAST") -class DriverStatusListenerApi(private val binaryMessenger: BinaryMessenger) { +class DriverStatusListenerApi( + private val binaryMessenger: BinaryMessenger, + private val messageChannelSuffix: String = "", +) { companion object { /** The codec used by DriverStatusListenerApi. */ - val codec: MessageCodec by lazy { StandardMessageCodec() } + val codec: MessageCodec by lazy { messagesPigeonCodec() } } fun onStatusUpdate( @@ -1089,12 +1191,14 @@ class DriverStatusListenerApi(private val binaryMessenger: BinaryMessenger) { messageArg: String, errorCodeArg: String?, errorMessageArg: String?, - callback: (Result) -> Unit + callback: (Result) -> Unit, ) { + val separatedMessageChannelSuffix = + if (messageChannelSuffix.isNotEmpty()) ".$messageChannelSuffix" else "" val channelName = - "dev.flutter.pigeon.google_driver_flutter.DriverStatusListenerApi.onStatusUpdate" + "dev.flutter.pigeon.google_driver_flutter.DriverStatusListenerApi.onStatusUpdate$separatedMessageChannelSuffix" val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(levelArg.raw, codeArg.raw, messageArg, errorCodeArg, errorMessageArg)) { + channel.send(listOf(levelArg, codeArg, messageArg, errorCodeArg, errorMessageArg)) { if (it is List<*>) { if (it.size > 1) { callback(Result.failure(FlutterError(it[0] as String, it[1] as String, it[2] as String?))) @@ -1102,7 +1206,7 @@ class DriverStatusListenerApi(private val binaryMessenger: BinaryMessenger) { callback(Result.success(Unit)) } } else { - callback(Result.failure(createConnectionError(channelName))) + callback(Result.failure(MessagesPigeonUtils.createConnectionError(channelName))) } } } diff --git a/android/src/test/kotlin/com/google/maps/flutter/driver/ConvertTest.kt b/android/src/test/kotlin/com/google/maps/flutter/driver/ConvertTest.kt index a8c33de..7bdbeda 100644 --- a/android/src/test/kotlin/com/google/maps/flutter/driver/ConvertTest.kt +++ b/android/src/test/kotlin/com/google/maps/flutter/driver/ConvertTest.kt @@ -72,39 +72,39 @@ internal class ConvertTest { fun convertVehicleStopStateFromDto_returnsExpectedValue() { assertEquals( VehicleStop.VehicleStopState.UNSPECIFIED, - Convert.convertVehicleStopStateFromDto(VehicleStopStateDto.STATEUNSPECIFIED) + Convert.convertVehicleStopStateFromDto(VehicleStopStateDto.STATE_UNSPECIFIED), ) assertEquals( VehicleStop.VehicleStopState.NEW, - Convert.convertVehicleStopStateFromDto(VehicleStopStateDto.NEWSTOP) + Convert.convertVehicleStopStateFromDto(VehicleStopStateDto.NEW_STOP), ) assertEquals( VehicleStop.VehicleStopState.ENROUTE, - Convert.convertVehicleStopStateFromDto(VehicleStopStateDto.ENROUTE) + Convert.convertVehicleStopStateFromDto(VehicleStopStateDto.ENROUTE), ) assertEquals( VehicleStop.VehicleStopState.ARRIVED, - Convert.convertVehicleStopStateFromDto(VehicleStopStateDto.ARRIVED) + Convert.convertVehicleStopStateFromDto(VehicleStopStateDto.ARRIVED), ) } @Test fun convertVehicleStopStateToDto_returnsExpectedValue() { assertEquals( - VehicleStopStateDto.STATEUNSPECIFIED, - Convert.convertVehicleStopStateToDto(VehicleStop.VehicleStopState.UNSPECIFIED) + VehicleStopStateDto.STATE_UNSPECIFIED, + Convert.convertVehicleStopStateToDto(VehicleStop.VehicleStopState.UNSPECIFIED), ) assertEquals( - VehicleStopStateDto.NEWSTOP, - Convert.convertVehicleStopStateToDto(VehicleStop.VehicleStopState.NEW) + VehicleStopStateDto.NEW_STOP, + Convert.convertVehicleStopStateToDto(VehicleStop.VehicleStopState.NEW), ) assertEquals( VehicleStopStateDto.ENROUTE, - Convert.convertVehicleStopStateToDto(VehicleStop.VehicleStopState.ENROUTE) + Convert.convertVehicleStopStateToDto(VehicleStop.VehicleStopState.ENROUTE), ) assertEquals( VehicleStopStateDto.ARRIVED, - Convert.convertVehicleStopStateToDto(VehicleStop.VehicleStopState.ARRIVED) + Convert.convertVehicleStopStateToDto(VehicleStop.VehicleStopState.ARRIVED), ) } @@ -112,11 +112,11 @@ internal class ConvertTest { fun convertRidesharingVehicleStateFromDto_returnsExpectedValue() { assertEquals( RidesharingVehicleReporter.VehicleState.OFFLINE, - Convert.convertVehicleStateFromDto(VehicleStateDto.OFFLINE) + Convert.convertVehicleStateFromDto(VehicleStateDto.OFFLINE), ) assertEquals( RidesharingVehicleReporter.VehicleState.ONLINE, - Convert.convertVehicleStateFromDto(VehicleStateDto.ONLINE) + Convert.convertVehicleStateFromDto(VehicleStateDto.ONLINE), ) } @@ -156,7 +156,7 @@ internal class ConvertTest { longitude = 20.0, speed = 40.0, time = 80L, - provider = "provider" + provider = "provider", ) val location = Convert.convertLocationFromDto(testLocation) @@ -201,65 +201,65 @@ internal class ConvertTest { fun convertStatusLevelToDto_returnsExpectedValue() { assertEquals( DriverStatusLevelDto.DEBUG, - Convert.convertStatusLevelToDto(DriverContext.DriverStatusListener.StatusLevel.DEBUG) + Convert.convertStatusLevelToDto(DriverContext.DriverStatusListener.StatusLevel.DEBUG), ) assertEquals( DriverStatusLevelDto.INFO, - Convert.convertStatusLevelToDto(DriverContext.DriverStatusListener.StatusLevel.INFO) + Convert.convertStatusLevelToDto(DriverContext.DriverStatusListener.StatusLevel.INFO), ) assertEquals( DriverStatusLevelDto.WARNING, - Convert.convertStatusLevelToDto(DriverContext.DriverStatusListener.StatusLevel.WARNING) + Convert.convertStatusLevelToDto(DriverContext.DriverStatusListener.StatusLevel.WARNING), ) assertEquals( DriverStatusLevelDto.ERROR, - Convert.convertStatusLevelToDto(DriverContext.DriverStatusListener.StatusLevel.ERROR) + Convert.convertStatusLevelToDto(DriverContext.DriverStatusListener.StatusLevel.ERROR), ) } @Test fun convertStatusCodeToDto_returnsExpectedValue() { assertEquals( - DriverStatusCodeDto.DEFAULTSTATUS, - Convert.convertStatusCodeToDto(DriverContext.DriverStatusListener.StatusCode.DEFAULT) + DriverStatusCodeDto.DEFAULT_STATUS, + Convert.convertStatusCodeToDto(DriverContext.DriverStatusListener.StatusCode.DEFAULT), ) assertEquals( - DriverStatusCodeDto.UNKNOWNERROR, - Convert.convertStatusCodeToDto(DriverContext.DriverStatusListener.StatusCode.UNKNOWN_ERROR) + DriverStatusCodeDto.UNKNOWN_ERROR, + Convert.convertStatusCodeToDto(DriverContext.DriverStatusListener.StatusCode.UNKNOWN_ERROR), ) assertEquals( - DriverStatusCodeDto.VEHICLENOTFOUND, + DriverStatusCodeDto.VEHICLE_NOT_FOUND, Convert.convertStatusCodeToDto( DriverContext.DriverStatusListener.StatusCode.VEHICLE_NOT_FOUND - ) + ), ) assertEquals( - DriverStatusCodeDto.BACKENDCONNECTIVITYERROR, + DriverStatusCodeDto.BACKEND_CONNECTIVITY_ERROR, Convert.convertStatusCodeToDto( DriverContext.DriverStatusListener.StatusCode.BACKEND_CONNECTIVITY_ERROR - ) + ), ) assertEquals( - DriverStatusCodeDto.PERMISSIONDENIED, + DriverStatusCodeDto.PERMISSION_DENIED, Convert.convertStatusCodeToDto( DriverContext.DriverStatusListener.StatusCode.PERMISSION_DENIED - ) + ), ) assertEquals( - DriverStatusCodeDto.SERVICEERROR, - Convert.convertStatusCodeToDto(DriverContext.DriverStatusListener.StatusCode.SERVICE_ERROR) + DriverStatusCodeDto.SERVICE_ERROR, + Convert.convertStatusCodeToDto(DriverContext.DriverStatusListener.StatusCode.SERVICE_ERROR), ) assertEquals( - DriverStatusCodeDto.FILEACCESSERROR, + DriverStatusCodeDto.FILE_ACCESS_ERROR, Convert.convertStatusCodeToDto( DriverContext.DriverStatusListener.StatusCode.FILE_ACCESS_ERROR - ) + ), ) assertEquals( - DriverStatusCodeDto.TRAVELEDROUTEERROR, + DriverStatusCodeDto.TRAVELED_ROUTE_ERROR, Convert.convertStatusCodeToDto( DriverContext.DriverStatusListener.StatusCode.TRAVELED_ROUTE_ERROR - ) + ), ) } } diff --git a/example/.gitignore b/example/.gitignore index 24476c5..6c31954 100644 --- a/example/.gitignore +++ b/example/.gitignore @@ -5,9 +5,11 @@ *.swp .DS_Store .atom/ +.build/ .buildlog/ .history .svn/ +.swiftpm/ migrate_working_dir/ # IntelliJ related diff --git a/example/android/app/build.gradle b/example/android/app/build.gradle deleted file mode 100644 index 5110bea..0000000 --- a/example/android/app/build.gradle +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2023 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -plugins { - id "com.android.application" - id "kotlin-android" - id "dev.flutter.flutter-gradle-plugin" - id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin' -} - -def localProperties = new Properties() -def localPropertiesFile = rootProject.file('local.properties') -if (localPropertiesFile.exists()) { - localPropertiesFile.withReader('UTF-8') { reader -> - localProperties.load(reader) - } -} - -def flutterVersionCode = localProperties.getProperty('flutter.versionCode') -if (flutterVersionCode == null) { - flutterVersionCode = '1' -} - -def flutterVersionName = localProperties.getProperty('flutter.versionName') -if (flutterVersionName == null) { - flutterVersionName = '1.0' -} - -android { - namespace "com.google.maps.flutter.driver_example" - compileSdk flutter.compileSdkVersion - ndkVersion flutter.ndkVersion - - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 - } - - kotlinOptions { - jvmTarget = '1.8' - } - - sourceSets { - main.java.srcDirs += 'src/main/kotlin' - } - - defaultConfig { - // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId "com.google.maps.flutter.driver_example" - // Navigation SDK supports SDK 23 and later. - minSdkVersion 23 - targetSdkVersion flutter.targetSdkVersion - versionCode flutterVersionCode.toInteger() - versionName flutterVersionName - testInstrumentationRunner "pl.leancode.patrol.PatrolJUnitRunner" - testInstrumentationRunnerArguments clearPackageData: "true" - - resourceConfigurations += ['en'] - - // Extract MAPS_API_KEY from Dart defines or environment variables - // and use it as manifest placeholder. - def mapsApiKey = System.env.MAPS_API_KEY ?: findDartDefineValue("MAPS_API_KEY") ?: "" - manifestPlaceholders = [MAPS_API_KEY: mapsApiKey] - } - - buildTypes { - - release { - // Run ProGuard. Note that the Navigation SDK includes its own ProGuard configuration. - // The configuration is included transitively by depending on the Navigation SDK. - // If the ProGuard step takes too long, consider enabling multidex for development work - // instead. - minifyEnabled true - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' - - // TODO: Add your own signing config for the release build. - // Signing with the debug keys for now, so `flutter run --release` works. - signingConfig signingConfigs.debug - } - } - - testOptions { - execution "ANDROIDX_TEST_ORCHESTRATOR" - } -} - -flutter { - source '../..' -} - -dependencies { - androidTestUtil "androidx.test:orchestrator:1.4.2" -} - -secrets { - // This example application employs the Gradle plugin - // com.google.android.libraries.mapsplatform.secrets-gradle-plugin - // to securely manage the Google Maps API key. - // For more information on the plugin, visit: - // https://developers.google.com/maps/documentation/android-sdk/secrets-gradle-plugin - - // To add your Maps API key to this project: - // 1. Open the root project's local.properties file - // 2. Add this line, where YOUR_API_KEY is your API key: - // MAPS_API_KEY=YOUR_API_KEY - defaultPropertiesFileName = 'local.properties' - - // Ignore all keys matching the regexp "sdk.*" - ignoreList.add("sdk.*") - // Ignore all keys matching the regexp "flutter.*" - ignoreList.add("flutter.*") -} - -// Helper function to extract specific Dart define value -def findDartDefineValue(key) { - def encodedDartDefines = project.hasProperty('dart-defines') ? project.property('dart-defines') : "" - def defines = encodedDartDefines.split(",").collectEntries { String it -> - def define = new String(it.decodeBase64(), 'UTF-8').split('=') - return [(define.first()): define.last()] - } - return defines.containsKey(key) ? defines[key] : null -} \ No newline at end of file diff --git a/example/android/app/build.gradle.kts b/example/android/app/build.gradle.kts new file mode 100644 index 0000000..ac42ff6 --- /dev/null +++ b/example/android/app/build.gradle.kts @@ -0,0 +1,127 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import java.util.Base64 + +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") + id("com.google.android.libraries.mapsplatform.secrets-gradle-plugin") +} + +// Helper function to extract specific Dart define value +fun findDartDefineValue(key: String): String? { + val encodedDartDefines = project.properties["dart-defines"] as? String ?: "" + val defines = encodedDartDefines.split(",").mapNotNull { + try { + val decoded = String(Base64.getDecoder().decode(it), Charsets.UTF_8).split("=") + if (decoded.size == 2) decoded[0] to decoded[1] else null + } catch (e: IllegalArgumentException) { + null + } + }.toMap() + return defines[key] +} + +android { + namespace = "com.google.maps.flutter.driver_example" + compileSdk = flutter.compileSdkVersion + ndkVersion = "27.0.12077973" + + compileOptions { + // Sets Java compatibility to Java 11 + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_11.toString() + } + + defaultConfig { + // Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.google.maps.flutter.driver_example" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = 23 + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + + // Set this to the languages you actually use, otherwise you'll include resource strings + // for all languages supported by the Navigation SDK. + multiDexEnabled = true + + testInstrumentationRunner = "pl.leancode.patrol.PatrolJUnitRunner" + + // TODO(jokerttu): Upgrade integration tests to initialize the application state for each + // test case and uncomment the following line to clear the package data before running tests. + // testInstrumentationRunnerArguments["clearPackageData"] = "true" + + resourceConfigurations.add("en") + + // Extract MAPS_API_KEY from Dart defines or environment variables + // and use it as manifest placeholder. + val mapsApiKey = System.getenv("MAPS_API_KEY") ?: findDartDefineValue("MAPS_API_KEY") ?: "" + manifestPlaceholders["MAPS_API_KEY"] = mapsApiKey + } + + testOptions { + execution = "ANDROIDX_TEST_ORCHESTRATOR" + } + + buildTypes { + getByName("release") { + // Run ProGuard. Note that the Navigation SDK includes its own ProGuard configuration. + // The configuration is included transitively by depending on the Navigation SDK. + // If the ProGuard step takes too long, consider enabling multidex for development work + // instead. + isMinifyEnabled = true + proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro") + + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} + +dependencies { + androidTestUtil("androidx.test:orchestrator:1.5.1") +} + +secrets { + // This example application employs the Gradle plugin + // com.google.android.libraries.mapsplatform.secrets-gradle-plugin + // to securely manage the Google Maps API key. + // For more information on the plugin, visit: + // https://developers.google.com/maps/documentation/android-sdk/secrets-gradle-plugin + + // To add your Maps API key to this project: + // 1. Open the root project's local.properties file + // 2. Add this line, where YOUR_API_KEY is your API key: + // MAPS_API_KEY=YOUR_API_KEY + defaultPropertiesFileName = "local.properties" + + // Ignore all keys matching the regexp "sdk.*" + ignoreList.add("sdk.*") + // Ignore all keys matching the regexp "flutter.*" + ignoreList.add("flutter.*") +} \ No newline at end of file diff --git a/example/android/build.gradle b/example/android/build.gradle.kts similarity index 54% rename from example/android/build.gradle rename to example/android/build.gradle.kts index d226271..1c22340 100644 --- a/example/android/build.gradle +++ b/example/android/build.gradle.kts @@ -12,20 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -buildscript { - ext.kotlin_version = '1.9.22' - repositories { - google() - mavenCentral() - } - - dependencies { - classpath 'com.android.tools.build:gradle:8.2.2' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - classpath("com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.1") - } -} - allprojects { repositories { google() @@ -33,14 +19,17 @@ allprojects { } } -rootProject.buildDir = '../build' +val newBuildDir: Directory = rootProject.layout.buildDirectory.dir("../../build").get() +rootProject.layout.buildDirectory.value(newBuildDir) + subprojects { - project.buildDir = "${rootProject.buildDir}/${project.name}" + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) } subprojects { - project.evaluationDependsOn(':app') + project.evaluationDependsOn(":app") } -tasks.register("clean", Delete) { - delete rootProject.buildDir +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) } diff --git a/example/android/gradle.properties b/example/android/gradle.properties index b9a9a24..0e4b7e6 100644 --- a/example/android/gradle.properties +++ b/example/android/gradle.properties @@ -1,6 +1,5 @@ -org.gradle.jvmargs=-Xmx1536M +org.gradle.jvmargs=-Xmx4096m android.useAndroidX=true android.enableJetifier=true -android.defaults.buildfeatures.buildconfig=true android.nonTransitiveRClass=false android.nonFinalResIds=false diff --git a/example/android/gradle/wrapper/gradle-wrapper.properties b/example/android/gradle/wrapper/gradle-wrapper.properties index b5fc5a7..df97d72 100644 --- a/example/android/gradle/wrapper/gradle-wrapper.properties +++ b/example/android/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-all.zip diff --git a/example/android/settings.gradle b/example/android/settings.gradle index fcd530f..f6de083 100644 --- a/example/android/settings.gradle +++ b/example/android/settings.gradle @@ -19,16 +19,22 @@ pluginManagement { def flutterSdkPath = properties.getProperty("flutter.sdk") assert flutterSdkPath != null, "flutter.sdk not set in local.properties" return flutterSdkPath - } - settings.ext.flutterSdkPath = flutterSdkPath() + }() - includeBuild("${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle") + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") - plugins { - id "dev.flutter.flutter-gradle-plugin" version "1.0.0" apply false + repositories { + google() + mavenCentral() + gradlePluginPortal() } } -include ":app" +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version '8.8.1' apply false + id "org.jetbrains.kotlin.android" version "2.1.0" apply false + id "com.google.android.libraries.mapsplatform.secrets-gradle-plugin" version "2.0.1" apply false +} -apply from: "${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle/app_plugin_loader.gradle" +include ":app" \ No newline at end of file diff --git a/example/integration_test/plugin_integration_test.dart b/example/integration_test/plugin_integration_test.dart index 006d8a4..298437a 100644 --- a/example/integration_test/plugin_integration_test.dart +++ b/example/integration_test/plugin_integration_test.dart @@ -14,9 +14,14 @@ import 'dart:async'; import 'dart:io'; +import 'package:flutter_test/flutter_test.dart'; import 'package:google_driver_flutter/google_driver_flutter.dart'; import 'package:google_driver_flutter_example/api/lmfs.dart'; import 'package:google_driver_flutter_example/api/odrd.dart'; +// ignore: depend_on_referenced_packages +import 'package:google_navigation_flutter/google_navigation_flutter.dart'; +import 'package:patrol/patrol.dart'; + import 'shared.dart'; enum TokenBehavior { throwsException, emptyToken, invalidToken, validToken } @@ -69,8 +74,9 @@ void main() { target: const LatLng(latitude: 37.41914, longitude: -122.08845), ), NavigationWaypoint.withLatLngTarget( - title: 'CWF7+748, 1700 Amphitheatre Pkwy, Mountain View, CA 94043', - target: const LatLng(latitude: 37.4231613, longitude: -122.087159)) + title: 'CWF7+748, 1700 Amphitheatre Pkwy, Mountain View, CA 94043', + target: const LatLng(latitude: 37.4231613, longitude: -122.087159), + ), ], ); @@ -80,8 +86,9 @@ void main() { expect(vehicleId, isNotEmpty); }); - patrol('Test delivery driver initialization', - (PatrolIntegrationTester $) async { + patrol('Test delivery driver initialization', ( + PatrolIntegrationTester $, + ) async { // Check you can fetch the driver version without initializing the driver. expect(await DeliveryDriver.getDriverSdkVersion(), isNotEmpty); @@ -91,17 +98,20 @@ void main() { // Trying to initialize driver before navigation should throw an error. try { await DeliveryDriver.initialize( - providerId: providerId, - vehicleId: vehicleId, - onGetToken: (AuthTokenContext context) { - return Future.value(''); - }, - abnormalTerminationReportingEnabled: true); + providerId: providerId, + vehicleId: vehicleId, + onGetToken: (AuthTokenContext context) { + return Future.value(''); + }, + abnormalTerminationReportingEnabled: true, + ); fail('Expected DriverInitializationException'); } on Exception catch (e) { expect(e, const TypeMatcher()); - expect((e as DriverInitializationException).code, - DriverInitializationError.navigationNotInitialized); + expect( + (e as DriverInitializationException).code, + DriverInitializationError.navigationNotInitialized, + ); } // Trying to control vehicle reporter should throw @@ -118,8 +128,9 @@ void main() { expect(e, const TypeMatcher()); } try { - await reporter - .setLocationReportingInterval(const Duration(milliseconds: 6001)); + await reporter.setLocationReportingInterval( + const Duration(milliseconds: 6001), + ); } on Exception catch (e) { expect(e, const TypeMatcher()); } @@ -151,35 +162,39 @@ void main() { // Initialize navigation and start the simulation. await initializeNavigation($); - await GoogleMapsNavigator.simulator - .setUserLocation(manifest.vehicle.startLocation!.target); + await GoogleMapsNavigator.simulator.setUserLocation( + manifest.vehicle.startLocation!.target, + ); // Initialize the driver. final Completer tokenCompleter = Completer(); await DeliveryDriver.initialize( - providerId: providerId, - vehicleId: vehicleId, - onGetToken: (AuthTokenContext context) async { - if (tokenResponse == null || - DateTime.now().millisecondsSinceEpoch > - tokenResponse!.expirationTimestampMs) { - tokenResponse = await getLMFSApi().getToken( - LMFSTokenType.deliveryDriver, manifest.vehicle.vehicleId); - tokenCompleter.complete(); - } - - switch (tokenBehavior) { - case TokenBehavior.throwsException: - throw Exception('Token retrieval from the backend failed.'); - case TokenBehavior.emptyToken: - return ''; - case TokenBehavior.invalidToken: - return 'invalid_token'; - case TokenBehavior.validToken: - return tokenResponse!.token; - } - }, - abnormalTerminationReportingEnabled: true); + providerId: providerId, + vehicleId: vehicleId, + onGetToken: (AuthTokenContext context) async { + if (tokenResponse == null || + DateTime.now().millisecondsSinceEpoch > + tokenResponse!.expirationTimestampMs) { + tokenResponse = await getLMFSApi().getToken( + LMFSTokenType.deliveryDriver, + manifest.vehicle.vehicleId, + ); + tokenCompleter.complete(); + } + + switch (tokenBehavior) { + case TokenBehavior.throwsException: + throw Exception('Token retrieval from the backend failed.'); + case TokenBehavior.emptyToken: + return ''; + case TokenBehavior.invalidToken: + return 'invalid_token'; + case TokenBehavior.validToken: + return tokenResponse!.token; + } + }, + abnormalTerminationReportingEnabled: true, + ); await $.pumpAndSettle(); // Now the driver should be initialized. @@ -196,8 +211,9 @@ void main() { expect(await reporter.isLocationTrackingEnabled(), true); // Force token update. - await GoogleMapsNavigator.simulator - .setUserLocation(manifest.vehicle.startLocation!.target); + await GoogleMapsNavigator.simulator.setUserLocation( + manifest.vehicle.startLocation!.target, + ); // Check that the token was requested at least once. await tokenCompleter.future; @@ -248,17 +264,20 @@ void main() { // an error. try { await DeliveryDriver.initialize( - providerId: providerId, - vehicleId: vehicleId, - onGetToken: (AuthTokenContext context) { - return Future.value(''); - }, - abnormalTerminationReportingEnabled: true); + providerId: providerId, + vehicleId: vehicleId, + onGetToken: (AuthTokenContext context) { + return Future.value(''); + }, + abnormalTerminationReportingEnabled: true, + ); fail('Expected DriverInitializationException'); } on Exception catch (e) { expect(e, const TypeMatcher()); - expect((e as DriverInitializationException).code, - DriverInitializationError.apiAlreadyInitialized); + expect( + (e as DriverInitializationException).code, + DriverInitializationError.apiAlreadyInitialized, + ); } await DeliveryDriver.dispose(); @@ -268,31 +287,39 @@ void main() { patrol('Test delivery driver tracking', (PatrolIntegrationTester $) async { /// Initialize navigation and start the simulation. await initializeNavigation($); - await GoogleMapsNavigator.simulator - .setUserLocation(manifest.vehicle.startLocation!.target); + await GoogleMapsNavigator.simulator.setUserLocation( + manifest.vehicle.startLocation!.target, + ); final Completer successCompleter = Completer(); final Completer failureCompleter = Completer(); await DeliveryDriver.initialize( - providerId: providerId, - vehicleId: vehicleId, - onGetToken: (AuthTokenContext context) async { - if (tokenResponse == null || - DateTime.now().millisecondsSinceEpoch > - tokenResponse!.expirationTimestampMs) { - tokenResponse = await getLMFSApi().getToken( - LMFSTokenType.deliveryDriver, manifest.vehicle.vehicleId); - } - if (failTokenRequest) { - return 'invalid_token'; - } else { - return tokenResponse!.token; - } - }, - onStatusUpdate: Platform.isAndroid - ? (DriverStatusLevel level, DriverStatusCode code, String message, - DriverException? exception) { + providerId: providerId, + vehicleId: vehicleId, + onGetToken: (AuthTokenContext context) async { + if (tokenResponse == null || + DateTime.now().millisecondsSinceEpoch > + tokenResponse!.expirationTimestampMs) { + tokenResponse = await getLMFSApi().getToken( + LMFSTokenType.deliveryDriver, + manifest.vehicle.vehicleId, + ); + } + if (failTokenRequest) { + return 'invalid_token'; + } else { + return tokenResponse!.token; + } + }, + onStatusUpdate: + Platform.isAndroid + ? ( + DriverStatusLevel level, + DriverStatusCode code, + String message, + DriverException? exception, + ) { if (listeningStatus) { reportedLevel = level; reportedCode = code; @@ -311,8 +338,9 @@ void main() { } } } - : null, - abnormalTerminationReportingEnabled: true); + : null, + abnormalTerminationReportingEnabled: true, + ); await $.pumpAndSettle(); // Now the driver should be initialized. @@ -328,12 +356,17 @@ void main() { expect(await reporter.isLocationTrackingEnabled(), false); // Test default reporting interval returns sane values and that it can be overridden - expect((await reporter.getLocationReportingInterval()).inMilliseconds, - greaterThan(100)); - await reporter - .setLocationReportingInterval(const Duration(milliseconds: 6001)); expect( - (await reporter.getLocationReportingInterval()).inMilliseconds, 6001); + (await reporter.getLocationReportingInterval()).inMilliseconds, + greaterThan(100), + ); + await reporter.setLocationReportingInterval( + const Duration(milliseconds: 6001), + ); + expect( + (await reporter.getLocationReportingInterval()).inMilliseconds, + 6001, + ); // Trying to set less than 5 second or more than 60 second location reporting // interval throws an assertion. @@ -386,19 +419,21 @@ void main() { // Utilizes VehicleReporterListener, which is iOS-only. if (Platform.isIOS) { // Start listening to the location status updates. - reporter.setListener(VehicleReporterListener( - onDidSucceed: (VehicleUpdate vehicleUpdate) { - successCount = successCount + 1; - successCompleter.complete(); - reportedVehicleUpdate = vehicleUpdate; - }, - onDidFail: (VehicleUpdate vehicleUpdate, DriverException exception) { - failureCount = failureCount + 1; - reportedException = exception; - reportedVehicleUpdate = vehicleUpdate; - failureCompleter.complete(); - }, - )); + reporter.setListener( + VehicleReporterListener( + onDidSucceed: (VehicleUpdate vehicleUpdate) { + successCount = successCount + 1; + successCompleter.complete(); + reportedVehicleUpdate = vehicleUpdate; + }, + onDidFail: (VehicleUpdate vehicleUpdate, DriverException exception) { + failureCount = failureCount + 1; + reportedException = exception; + reportedVehicleUpdate = vehicleUpdate; + failureCompleter.complete(); + }, + ), + ); await reporter.setLocationTrackingEnabled(true); expect(await reporter.isLocationTrackingEnabled(), true); @@ -411,10 +446,14 @@ void main() { expect(failureCount, 0); expect(reportedVehicleUpdate, isNotNull); expect(reportedVehicleUpdate!.vehicleState, isNull); - expect(reportedVehicleUpdate!.location?.latitude, - closeTo(manifest.vehicle.startLocation!.target.latitude, 0.1)); - expect(reportedVehicleUpdate!.location?.longitude, - closeTo(manifest.vehicle.startLocation!.target.longitude, 0.1)); + expect( + reportedVehicleUpdate!.location?.latitude, + closeTo(manifest.vehicle.startLocation!.target.latitude, 0.1), + ); + expect( + reportedVehicleUpdate!.location?.longitude, + closeTo(manifest.vehicle.startLocation!.target.longitude, 0.1), + ); reportedVehicleUpdate = null; failTokenRequest = true; @@ -438,24 +477,28 @@ void main() { patrol('Test vehicle stop handling', (PatrolIntegrationTester $) async { /// Initialize navigation and start the simulation. await initializeNavigation($); - await GoogleMapsNavigator.simulator - .setUserLocation(manifest.vehicle.startLocation!.target); + await GoogleMapsNavigator.simulator.setUserLocation( + manifest.vehicle.startLocation!.target, + ); final Completer tokenCompleter = Completer(); await DeliveryDriver.initialize( - providerId: providerId, - vehicleId: vehicleId, - onGetToken: (AuthTokenContext context) async { - if (tokenResponse == null || - DateTime.now().millisecondsSinceEpoch > - tokenResponse!.expirationTimestampMs) { - tokenResponse = await getLMFSApi().getToken( - LMFSTokenType.deliveryDriver, manifest.vehicle.vehicleId); - tokenCompleter.complete(); - } - return tokenResponse!.token; - }, - abnormalTerminationReportingEnabled: true); + providerId: providerId, + vehicleId: vehicleId, + onGetToken: (AuthTokenContext context) async { + if (tokenResponse == null || + DateTime.now().millisecondsSinceEpoch > + tokenResponse!.expirationTimestampMs) { + tokenResponse = await getLMFSApi().getToken( + LMFSTokenType.deliveryDriver, + manifest.vehicle.vehicleId, + ); + tokenCompleter.complete(); + } + return tokenResponse!.token; + }, + abnormalTerminationReportingEnabled: true, + ); await $.pumpAndSettle(); // Now the driver should be initialized. @@ -469,8 +512,9 @@ void main() { await reporter.setLocationTrackingEnabled(true); // Force token update. - await GoogleMapsNavigator.simulator - .setUserLocation(manifest.vehicle.startLocation!.target); + await GoogleMapsNavigator.simulator.setUserLocation( + manifest.vehicle.startLocation!.target, + ); // Check that the token was requested at least once. await tokenCompleter.future; @@ -536,8 +580,9 @@ void main() { expect(await DeliveryDriver.isInitialized(), false); }); - patrol('Test Ridesharing driver initialization', - (PatrolIntegrationTester $) async { + patrol('Test Ridesharing driver initialization', ( + PatrolIntegrationTester $, + ) async { tokenResponse = null; // Check you can fetch the driver version without initializing the driver. expect(await RidesharingDriver.getDriverSdkVersion(), isNotEmpty); @@ -548,17 +593,20 @@ void main() { // Trying to initialize driver before navigation should throw an error. try { await RidesharingDriver.initialize( - providerId: providerId, - vehicleId: vehicleId, - onGetToken: (AuthTokenContext context) { - return Future.value(''); - }, - abnormalTerminationReportingEnabled: true); + providerId: providerId, + vehicleId: vehicleId, + onGetToken: (AuthTokenContext context) { + return Future.value(''); + }, + abnormalTerminationReportingEnabled: true, + ); fail('Expected DriverInitializationException'); } on Exception catch (e) { expect(e, const TypeMatcher()); - expect((e as DriverInitializationException).code, - DriverInitializationError.navigationNotInitialized); + expect( + (e as DriverInitializationException).code, + DriverInitializationError.navigationNotInitialized, + ); } // Trying to control vehicle reporter should throw @@ -578,8 +626,9 @@ void main() { expect(e, const TypeMatcher()); } try { - await reporter - .setLocationReportingInterval(const Duration(milliseconds: 6001)); + await reporter.setLocationReportingInterval( + const Duration(milliseconds: 6001), + ); fail('Expected DriverNotInitializedException'); } on Exception catch (e) { expect(e, const TypeMatcher()); @@ -592,25 +641,29 @@ void main() { /// Initialize navigation and start the simulation. await initializeNavigation($); - await GoogleMapsNavigator.simulator - .setUserLocation(manifest.vehicle.startLocation!.target); + await GoogleMapsNavigator.simulator.setUserLocation( + manifest.vehicle.startLocation!.target, + ); // Initialize the driver. final Completer tokenCompleter = Completer(); await RidesharingDriver.initialize( - providerId: providerId, - vehicleId: vehicleId, - onGetToken: (AuthTokenContext context) async { - if (tokenResponse == null || - DateTime.now().millisecondsSinceEpoch > - tokenResponse!.expirationTimestampMs) { - tokenResponse = await getODRDApi() - .getToken(ODRDTokenType.driver, manifest.vehicle.vehicleId); - tokenCompleter.complete(); - } - return tokenResponse!.token; - }, - abnormalTerminationReportingEnabled: true); + providerId: providerId, + vehicleId: vehicleId, + onGetToken: (AuthTokenContext context) async { + if (tokenResponse == null || + DateTime.now().millisecondsSinceEpoch > + tokenResponse!.expirationTimestampMs) { + tokenResponse = await getODRDApi().getToken( + ODRDTokenType.driver, + manifest.vehicle.vehicleId, + ); + tokenCompleter.complete(); + } + return tokenResponse!.token; + }, + abnormalTerminationReportingEnabled: true, + ); await $.pumpAndSettle(); // Now the driver should be initialized. @@ -627,8 +680,9 @@ void main() { expect(await reporter.isLocationTrackingEnabled(), true); // Force token update. - await GoogleMapsNavigator.simulator - .setUserLocation(manifest.vehicle.startLocation!.target); + await GoogleMapsNavigator.simulator.setUserLocation( + manifest.vehicle.startLocation!.target, + ); await $.pumpAndSettle(); // Check that the token was requested at least once. @@ -645,17 +699,20 @@ void main() { // an error. try { await RidesharingDriver.initialize( - providerId: providerId, - vehicleId: vehicleId, - onGetToken: (AuthTokenContext context) { - return Future.value(''); - }, - abnormalTerminationReportingEnabled: true); + providerId: providerId, + vehicleId: vehicleId, + onGetToken: (AuthTokenContext context) { + return Future.value(''); + }, + abnormalTerminationReportingEnabled: true, + ); fail('Expected DriverInitializationException'); } on Exception catch (e) { expect(e, const TypeMatcher()); - expect((e as DriverInitializationException).code, - DriverInitializationError.apiAlreadyInitialized); + expect( + (e as DriverInitializationException).code, + DriverInitializationError.apiAlreadyInitialized, + ); } await RidesharingDriver.dispose(); diff --git a/example/integration_test/shared.dart b/example/integration_test/shared.dart index f9f9131..9621519 100644 --- a/example/integration_test/shared.dart +++ b/example/integration_test/shared.dart @@ -26,41 +26,35 @@ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_driver_flutter/google_driver_flutter.dart'; +// ignore: depend_on_referenced_packages import 'package:google_navigation_flutter/google_navigation_flutter.dart'; import 'package:patrol/patrol.dart'; import 'package:permission_handler/permission_handler.dart'; -export 'package:flutter_test/flutter_test.dart'; -export 'package:google_navigation_flutter/google_navigation_flutter.dart'; -export 'package:patrol/patrol.dart'; - /// Pumps a [navigationView] widget in tester [$] and then waits until it settles. Future pumpNavigationView( - PatrolIntegrationTester $, GoogleMapsNavigationView navigationView) async { + PatrolIntegrationTester $, + GoogleMapsNavigationView navigationView, +) async { await $.pumpWidget(wrapNavigationView(navigationView)); await $.pumpAndSettle(); } /// Wraps a [navigationView] in widgets. Widget wrapNavigationView(GoogleMapsNavigationView navigationView) { - return MaterialApp( - home: Scaffold( - body: Center( - child: navigationView, - ), - ), - ); + return MaterialApp(home: Scaffold(body: Center(child: navigationView))); } Future checkTermsAndConditionsAcceptance( - PatrolIntegrationTester $) async { + PatrolIntegrationTester $, +) async { if (!await GoogleMapsNavigator.areTermsAccepted()) { /// Request native TOS dialog. final Future tosAccepted = GoogleMapsNavigator.showTermsAndConditionsDialog( - 'test_title', - 'test_company_name', - ); + 'test_title', + 'test_company_name', + ); await $.pumpAndSettle(); // Tap accept or cancel. @@ -96,7 +90,8 @@ Future checkLocationDialogAcceptance(PatrolIntegrationTester $) async { } Future initializeNavigation( - PatrolIntegrationTester $) async { + PatrolIntegrationTester $, +) async { await checkLocationDialogAcceptance($); await checkTermsAndConditionsAcceptance($); await GoogleMapsNavigator.initializeNavigationSession(); @@ -150,7 +145,8 @@ void patrol( patrolTest( description, timeout: const Timeout( - Duration(seconds: 240)), // Add a 4 minute timeout to tests. + Duration(seconds: 240), + ), // Add a 4 minute timeout to tests. callback, ); } diff --git a/example/ios/Podfile b/example/ios/Podfile index a6a1022..41fe678 100644 --- a/example/ios/Podfile +++ b/example/ios/Podfile @@ -1,5 +1,5 @@ # Uncomment this line to define a global platform for your project -platform :ios, '14.0' +platform :ios, '16.0' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj index a433697..141d5b0 100644 --- a/example/ios/Runner.xcodeproj/project.pbxproj +++ b/example/ios/Runner.xcodeproj/project.pbxproj @@ -613,7 +613,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 16.6; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -632,7 +632,7 @@ DEVELOPMENT_TEAM = 5LUR69Y2U9; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 16.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -654,7 +654,7 @@ CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 16.6; MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = com.google.maps.flutter.driverExample.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -674,7 +674,7 @@ CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 16.6; MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = com.google.maps.flutter.driverExample.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -692,7 +692,7 @@ CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 16.6; MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = com.google.maps.flutter.driverExample.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -750,7 +750,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 16.6; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -800,7 +800,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 16.6; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -821,7 +821,7 @@ DEVELOPMENT_TEAM = 5LUR69Y2U9; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 16.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -845,7 +845,7 @@ DEVELOPMENT_TEAM = 5LUR69Y2U9; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 16.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", @@ -875,7 +875,7 @@ ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu17; GENERATE_INFOPLIST_FILE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 16.6; LOCALIZATION_PREFERS_STRING_CATALOGS = YES; MARKETING_VERSION = 1.0; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; @@ -905,7 +905,7 @@ ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu17; GENERATE_INFOPLIST_FILE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 16.6; LOCALIZATION_PREFERS_STRING_CATALOGS = YES; MARKETING_VERSION = 1.0; MTL_FAST_MATH = YES; @@ -934,7 +934,7 @@ ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu17; GENERATE_INFOPLIST_FILE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 14.0; + IPHONEOS_DEPLOYMENT_TARGET = 16.6; LOCALIZATION_PREFERS_STRING_CATALOGS = YES; MARKETING_VERSION = 1.0; MTL_FAST_MATH = YES; diff --git a/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 5c376df..ce3f125 100644 --- a/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -26,6 +26,7 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + customLLDBInitFile = "$(SRCROOT)/Flutter/ephemeral/flutter_lldbinit" shouldUseLaunchSchemeArgsEnv = "YES"> diff --git a/example/ios/Runner/AppDelegate.swift b/example/ios/Runner/AppDelegate.swift index a8e1cb3..e8d7772 100644 --- a/example/ios/Runner/AppDelegate.swift +++ b/example/ios/Runner/AppDelegate.swift @@ -12,12 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -import UIKit import Flutter import GoogleMaps import GoogleNavigation +import UIKit -@UIApplicationMain +@main @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, @@ -26,31 +26,32 @@ import GoogleNavigation // 1. Try to find the Maps API key from the environment variables. // 2. Try to find the Maps API key from the Dart defines. // 3. Use the default Maps API key "YOUR_API_KEY". - var mapsApiKey = ProcessInfo.processInfo.environment["MAPS_API_KEY"] ?? findMapApiKeyFromDartDefines("MAPS_API_KEY") ?? "" - if (mapsApiKey.isEmpty) { - mapsApiKey = "YOUR_API_KEY" + var mapsApiKey = + ProcessInfo.processInfo.environment["MAPS_API_KEY"] ?? findMapApiKeyFromDartDefines( + "MAPS_API_KEY") ?? "" + if mapsApiKey.isEmpty { + mapsApiKey = "YOUR_API_KEY" } GMSServices.provideAPIKey(mapsApiKey) - GMSServices.setMetalRendererEnabled(true) GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } - + // Helper function to find the Maps API key from the Dart defines private func findMapApiKeyFromDartDefines(_ defineKey: String) -> String? { - if (Bundle.main.infoDictionary!["DART_DEFINES"] == nil) { - return nil - } + if Bundle.main.infoDictionary!["DART_DEFINES"] == nil { + return nil + } - let dartDefinesString = Bundle.main.infoDictionary!["DART_DEFINES"] as! String - let base64EncodedDartDefines = dartDefinesString.components(separatedBy: ",") - for base64EncodedDartDefine in base64EncodedDartDefines { - let decoded = String(data: Data(base64Encoded: base64EncodedDartDefine)!, encoding: .utf8)! - let values = decoded.components(separatedBy: "=") - if (values[0] == defineKey && values.count == 2) { - return values[1] - } + let dartDefinesString = Bundle.main.infoDictionary!["DART_DEFINES"] as! String + let base64EncodedDartDefines = dartDefinesString.components(separatedBy: ",") + for base64EncodedDartDefine in base64EncodedDartDefines { + let decoded = String(data: Data(base64Encoded: base64EncodedDartDefine)!, encoding: .utf8)! + let values = decoded.components(separatedBy: "=") + if values[0] == defineKey && values.count == 2 { + return values[1] } - return nil + } + return nil } } diff --git a/example/ios/RunnerTests/ConvertTests.swift b/example/ios/RunnerTests/ConvertTests.swift index d5fc0a1..2f25b90 100644 --- a/example/ios/RunnerTests/ConvertTests.swift +++ b/example/ios/RunnerTests/ConvertTests.swift @@ -149,7 +149,7 @@ class ConvertTests: XCTestCase { latitude: 55.0, longitude: 44.0 ) - ), + ) ] XCTAssertEqual(Convert.convertWaypoints(testWaypoints).count, 1) @@ -161,7 +161,7 @@ class ConvertTests: XCTestCase { .init( title: "test", placeID: "id" - ), + ) ] XCTAssertEqual(Convert.convertWaypoints(testWaypoints).count, 1) @@ -180,7 +180,7 @@ class ConvertTests: XCTestCase { } func testConvertTaskInfoToDto() { - let testTaskInfo = GMTSTaskInfo(taskID: "taskId", taskDuration: 100) + let testTaskInfo = GMTDTaskInfo(taskID: "taskId", taskDuration: 100) let taskInfo = Convert.convertTaskInfoToDto(task: testTaskInfo) XCTAssertEqual(taskInfo.taskId, testTaskInfo.taskID) @@ -208,7 +208,7 @@ class ConvertTests: XCTestCase { } func testConvertVehicleStopToDto() { - let testTaskInfo = GMTSTaskInfo(taskID: "taskId", taskDuration: 100) + let testTaskInfo = GMTDTaskInfo(taskID: "taskId", taskDuration: 100) let testWaypoint = GMSNavigationWaypoint(placeID: "id", title: "title") let testStop = GMTDVehicleStop( taskInfoArray: [testTaskInfo], diff --git a/example/lib/api/client.dart b/example/lib/api/client.dart index 9dbdea2..b5939c2 100644 --- a/example/lib/api/client.dart +++ b/example/lib/api/client.dart @@ -69,15 +69,18 @@ abstract class ApiClient { /// /// Returns the response body as a string Future postFile(String endpoint, String data) async { - final http.MultipartRequest request = - http.MultipartRequest('POST', Uri.parse('$baseUrl/$endpoint')); + final http.MultipartRequest request = http.MultipartRequest( + 'POST', + Uri.parse('$baseUrl/$endpoint'), + ); // Adding file data request.files.add(http.MultipartFile.fromString('file', data)); final http.StreamedResponse streamedResponse = await request.send(); - final http.Response response = - await http.Response.fromStream(streamedResponse); + final http.Response response = await http.Response.fromStream( + streamedResponse, + ); return _parseResponse(response); } @@ -88,8 +91,10 @@ abstract class ApiClient { return response.body; } else { debugPrint(response.body); - throw Exception('Failed to communicate with the server, status code: ' - '${response.statusCode}.'); + throw Exception( + 'Failed to communicate with the server, status code: ' + '${response.statusCode}.', + ); } } } diff --git a/example/lib/api/helpers.dart b/example/lib/api/helpers.dart index e0ddfc8..d183093 100644 --- a/example/lib/api/helpers.dart +++ b/example/lib/api/helpers.dart @@ -45,8 +45,10 @@ String generateRandomString(int length) { 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; final Random random = Random(); - return String.fromCharCodes(Iterable.generate( - length, - (_) => characters.codeUnitAt(random.nextInt(characters.length)), - )); + return String.fromCharCodes( + Iterable.generate( + length, + (_) => characters.codeUnitAt(random.nextInt(characters.length)), + ), + ); } diff --git a/example/lib/api/lmfs_api.dart b/example/lib/api/lmfs_api.dart index 74f4c80..935e74e 100644 --- a/example/lib/api/lmfs_api.dart +++ b/example/lib/api/lmfs_api.dart @@ -31,12 +31,15 @@ class LMFSApi extends ApiClient { final String typeStr = type.toJsonString(); final String response = await get('token/$typeStr/${id ?? ''}'); return TokenResponse.fromLMFSJson( - jsonDecode(response) as Map); + jsonDecode(response) as Map, + ); } /// Method to update the manifest for a given vehicle ID Future updateManifest( - LMFSManifestUpdate manifestDetails, String? vehicleId) async { + LMFSManifestUpdate manifestDetails, + String? vehicleId, + ) async { final String endpoint = vehicleId != null ? 'manifest/$vehicleId' : 'manifest'; final String response = await post(endpoint, manifestDetails.toJson()); @@ -79,8 +82,11 @@ class LMFSApi extends ApiClient { Future> getTasksByVehicleId(String vehicleId) async { final String response = await get('tasks?vehicleId=$vehicleId'); final List responseData = jsonDecode(response) as List; - return List.from(responseData.map( - (dynamic task) => LMFSTask.fromJson(task as Map))); + return List.from( + responseData.map( + (dynamic task) => LMFSTask.fromJson(task as Map), + ), + ); } /// Method to get task information by tracking ID diff --git a/example/lib/api/lmfs_helpers.dart b/example/lib/api/lmfs_helpers.dart index 3010601..83d5492 100644 --- a/example/lib/api/lmfs_helpers.dart +++ b/example/lib/api/lmfs_helpers.dart @@ -26,11 +26,14 @@ import 'lmfs_types.dart'; /// default value. /// See ./tools/backend/docker-compose.yml for the values of these environment /// variables. -const String _LMFSAndroidBaseUrl = String.fromEnvironment( - 'LMFS_ANDROID_HOST_URL', - defaultValue: 'http://10.0.2.2:8091'); -const String _LMFSiOSBaseUrl = String.fromEnvironment('LMFS_IOS_HOST_URL', - defaultValue: 'http://localhost:8091'); +const String _lmfsAndroidBaseUrl = String.fromEnvironment( + 'LMFS_ANDROID_HOST_URL', + defaultValue: 'http://10.0.2.2:8091', +); +const String _lmfsiOSBaseUrl = String.fromEnvironment( + 'LMFS_IOS_HOST_URL', + defaultValue: 'http://localhost:8091', +); LMFSApi? _lmfsApiInstance; LMFSDeliveryConfig? _lmfsDeliveryConfig; @@ -44,7 +47,7 @@ LMFSDeliveryConfig? get lmfsDeliveryConfig => _lmfsDeliveryConfig; LMFSApi getLMFSApi() { if (_lmfsApiInstance == null) { final String baseUrl = - Platform.isAndroid ? _LMFSAndroidBaseUrl : _LMFSiOSBaseUrl; + Platform.isAndroid ? _lmfsAndroidBaseUrl : _lmfsiOSBaseUrl; _lmfsApiInstance = LMFSApi(baseUrl); } return _lmfsApiInstance!; @@ -52,19 +55,23 @@ LMFSApi getLMFSApi() { /// Sends initial [LMFSDeliveryConfig] to the LMFS backend and returns the response /// string. -Future initLMFSBackendForVehicle( - {required String vehicleId, - required NavigationWaypoint startLocation, - required List deliveryWaypoints, - required List stopWaypoints}) async { +Future initLMFSBackendForVehicle({ + required String vehicleId, + required NavigationWaypoint startLocation, + required List deliveryWaypoints, + required List stopWaypoints, +}) async { final String clientId = getClientId(); - assert(deliveryWaypoints.length == stopWaypoints.length, - 'Equal number of delivery and stop waypoints required by the example.'); + assert( + deliveryWaypoints.length == stopWaypoints.length, + 'Equal number of delivery and stop waypoints required by the example.', + ); final LMFSVehicle vehicle = LMFSVehicle( - vehicleId: vehicleId, - providerId: getProjectId(), - startLocation: LMFSWaypoint.fromNavigationWaypoint(startLocation)); + vehicleId: vehicleId, + providerId: getProjectId(), + startLocation: LMFSWaypoint.fromNavigationWaypoint(startLocation), + ); final List tasks = []; final List stops = []; @@ -78,20 +85,24 @@ Future initLMFSBackendForVehicle( final String trackingId = '${vehicleId}_$randomString'; final String stopId = '${vehicleId}_$randomString'; - tasks.add(LMFSTask( - taskId: taskId, - plannedWaypoint: LMFSWaypoint.fromNavigationWaypoint(deliveryWaypoint), - trackingId: trackingId, - durationSeconds: 60 * 60, // 1 hour - contactName: 'John Doe', - taskType: LMFSTaskType.delivery, - )); - - stops.add(LMFSStop( - stopId: stopId, - plannedWaypoint: LMFSWaypoint.fromNavigationWaypoint(stopWaypoint), - taskIds: [taskId], - )); + tasks.add( + LMFSTask( + taskId: taskId, + plannedWaypoint: LMFSWaypoint.fromNavigationWaypoint(deliveryWaypoint), + trackingId: trackingId, + durationSeconds: 60 * 60, // 1 hour + contactName: 'John Doe', + taskType: LMFSTaskType.delivery, + ), + ); + + stops.add( + LMFSStop( + stopId: stopId, + plannedWaypoint: LMFSWaypoint.fromNavigationWaypoint(stopWaypoint), + taskIds: [taskId], + ), + ); } final LMFSManifest manifest = LMFSManifest( @@ -110,7 +121,9 @@ Future initLMFSBackendForVehicle( /// Updates the next stop state of the vehicle in the LMFS backend and returns /// the updated manifest. Future updateLMFSStopState( - LMFSManifest manifest, VehicleStopState state) async { + LMFSManifest manifest, + VehicleStopState state, +) async { final LMFSManifestUpdate update = LMFSManifestUpdate(currentStopState: state); return getLMFSApi().updateManifest(update, manifest.vehicle.vehicleId); } @@ -119,11 +132,13 @@ Future updateLMFSStopState( /// the updated manifest. Future completeFirstLMFSStop(LMFSManifest manifest) async { assert( - manifest.remainingStopIdList != null && - manifest.remainingStopIdList!.isNotEmpty, - 'There should be at least one stop remaining in the manifest.'); - final LMFSManifestUpdate update = - LMFSManifestUpdate(remainingStopIdList: manifest.remainingStopIdList); + manifest.remainingStopIdList != null && + manifest.remainingStopIdList!.isNotEmpty, + 'There should be at least one stop remaining in the manifest.', + ); + final LMFSManifestUpdate update = LMFSManifestUpdate( + remainingStopIdList: manifest.remainingStopIdList, + ); update.remainingStopIdList!.removeAt(0); update.currentStopState = update.remainingStopIdList!.isEmpty ? null : VehicleStopState.newStop; @@ -132,23 +147,31 @@ Future completeFirstLMFSStop(LMFSManifest manifest) async { /// Returns the list of [VehicleStop] objects from the given [LMFSManifest]. List getStopsFromLMFSManifest(LMFSManifest manifest) { - final List stops = manifest.stops - .where((LMFSStop stop) => - manifest.remainingStopIdList?.contains(stop.stopId) ?? false) - .map((LMFSStop stop) => VehicleStop( - vehicleStopState: stop.stopId == manifest.remainingStopIdList?.first - ? (manifest.currentStopState ?? VehicleStopState.newStop) - : VehicleStopState.newStop, - waypoint: stop.plannedWaypoint.toNavigationWaypoint(), - taskInfoList: stop.taskIds.map((String taskId) { - final LMFSTask task = manifest.tasks - .firstWhere((LMFSTask task) => task.taskId == taskId); - return TaskInfo( - taskId: taskId, - durationSeconds: task.durationSeconds, - ); - }).toList(), - )) - .toList(); + final List stops = + manifest.stops + .where( + (LMFSStop stop) => + manifest.remainingStopIdList?.contains(stop.stopId) ?? false, + ) + .map( + (LMFSStop stop) => VehicleStop( + vehicleStopState: + stop.stopId == manifest.remainingStopIdList?.first + ? (manifest.currentStopState ?? VehicleStopState.newStop) + : VehicleStopState.newStop, + waypoint: stop.plannedWaypoint.toNavigationWaypoint(), + taskInfoList: + stop.taskIds.map((String taskId) { + final LMFSTask task = manifest.tasks.firstWhere( + (LMFSTask task) => task.taskId == taskId, + ); + return TaskInfo( + taskId: taskId, + durationSeconds: task.durationSeconds, + ); + }).toList(), + ), + ) + .toList(); return stops; } diff --git a/example/lib/api/lmfs_types.dart b/example/lib/api/lmfs_types.dart index e59979a..0712314 100644 --- a/example/lib/api/lmfs_types.dart +++ b/example/lib/api/lmfs_types.dart @@ -32,7 +32,7 @@ enum LMFSTokenType { deliveryConsumer, /// Fleet reader token - fleetReader + fleetReader, } /// Helper class to convert LMFSTokenType to/from JSON. @@ -59,9 +59,10 @@ class LMFSDeliveryConfig { factory LMFSDeliveryConfig.fromJson(Map json) { return LMFSDeliveryConfig( description: json['description'] as String, - manifests: (json['manifests'] as List>) - .map((Map e) => LMFSManifest.fromJson(e)) - .toList(), + manifests: + (json['manifests'] as List>) + .map((Map e) => LMFSManifest.fromJson(e)) + .toList(), ); } @@ -158,7 +159,7 @@ class LMFSManifest { /// A list of stops for the vehicle to travel through. final List stops; - /// Converts a Manifest instance to a Map for JSON serialization. + /// Converts a Manifest instance to a Map`` for JSON serialization. Map toJson() { final Map json = { 'vehicle': vehicle.toJson(), @@ -179,21 +180,30 @@ class LMFSManifest { return json; } - /// Constructs a Manifest instance from a Map. + /// Constructs a Manifest instance from a Map``. static LMFSManifest fromJson(Map json) { return LMFSManifest( vehicle: LMFSVehicle.fromJson(json['vehicle'] as Map), clientId: json['client_id'] as String?, - currentStopState: json['current_stop_state'] != null - ? VehicleStopStateJsonConversion.fromJsonString( - json['current_stop_state'] as String) - : null, - remainingStopIdList: - List.from(json['remaining_stop_id_list'] as List), - tasks: List.from((json['tasks'] as List) - .map((dynamic t) => LMFSTask.fromJson(t as Map))), - stops: List.from((json['stops'] as List) - .map((dynamic s) => LMFSStop.fromJson(s as Map))), + currentStopState: + json['current_stop_state'] != null + ? VehicleStopStateJsonConversion.fromJsonString( + json['current_stop_state'] as String, + ) + : null, + remainingStopIdList: List.from( + json['remaining_stop_id_list'] as List, + ), + tasks: List.from( + (json['tasks'] as List).map( + (dynamic t) => LMFSTask.fromJson(t as Map), + ), + ), + stops: List.from( + (json['stops'] as List).map( + (dynamic s) => LMFSStop.fromJson(s as Map), + ), + ), ); } } @@ -201,10 +211,7 @@ class LMFSManifest { /// Object used to update the manifest for a given vehicle ID. class LMFSManifestUpdate { /// Constructs a [LMFSManifestUpdate] instance. - LMFSManifestUpdate({ - this.currentStopState, - this.remainingStopIdList, - }); + LMFSManifestUpdate({this.currentStopState, this.remainingStopIdList}); /// The current state of the vehicle as it travels to the next stop. /// @@ -226,7 +233,7 @@ class LMFSManifestUpdate { /// stops field. List? remainingStopIdList; - /// Converts a Manifest instance to a Map for JSON serialization. + /// Converts a Manifest instance to a Map`` for JSON serialization. Map toJson() { final Map json = {}; @@ -260,7 +267,7 @@ class LMFSVehicle extends Vehicle { /// Where the vehicle is located initially for simulation. final LMFSWaypoint? startLocation; - /// Converts a Vehicle instance to a Map for JSON serialization. + /// Converts a Vehicle instance to a Map`` for JSON serialization. @override Map toJson() { final Map json = { @@ -273,15 +280,17 @@ class LMFSVehicle extends Vehicle { return json; } - /// Constructs a Vehicle instance from a Map. + /// Constructs a Vehicle instance from a Map``. static LMFSVehicle fromJson(Map json) { return LMFSVehicle( vehicleId: json['vehicle_id'] as String, providerId: json['provider_id'] as String, - startLocation: json['start_location'] != null - ? LMFSWaypoint.fromJson( - json['start_location'] as Map) - : null, + startLocation: + json['start_location'] != null + ? LMFSWaypoint.fromJson( + json['start_location'] as Map, + ) + : null, ); } } @@ -304,7 +313,7 @@ class LMFSStop { /// Multiple nearby tasks may be done at this stop. final List taskIds; - /// Converts a Stop instance to a Map for JSON serialization. + /// Converts a Stop instance to a Map`` for JSON serialization. Map toJson() { return { 'stop_id': stopId, @@ -313,12 +322,13 @@ class LMFSStop { }; } - /// Constructs a Stop instance from a Map. + /// Constructs a Stop instance from a Map``. static LMFSStop fromJson(Map json) { return LMFSStop( stopId: json['stop_id'] as String, plannedWaypoint: LMFSWaypoint.fromJson( - json['planned_waypoint'] as Map), + json['planned_waypoint'] as Map, + ), taskIds: List.from(json['tasks'] as List), ); } @@ -431,7 +441,7 @@ class LMFSTask { /// A description of the task. final String? description; - /// Converts a Task instance to a Map for JSON serialization. + /// Converts a Task instance to a Map`` for JSON serialization. Map toJson() { final Map json = { 'task_id': taskId, @@ -461,22 +471,25 @@ class LMFSTask { return json; } - /// Constructs a Task instance from a Map. + /// Constructs a Task instance from a Map``. static LMFSTask fromJson(Map json) { return LMFSTask( taskId: json['task_id'] as String, trackingId: json['tracking_id'] as String, plannedWaypoint: LMFSWaypoint.fromJson( - json['planned_waypoint'] as Map), + json['planned_waypoint'] as Map, + ), contactName: json['contact_name'] as String?, plannedCompletionTime: json['planned_completion_time'] as String?, plannedCompletionTimeRangeSeconds: json['planned_completion_time_range_seconds'] as int?, durationSeconds: json['duration_seconds'] as int, - taskType: json['taskType'] != null - ? LMFSTaskTypeJsonConversion.fromJsonString( - json['taskType'] as String) - : null, + taskType: + json['taskType'] != null + ? LMFSTaskTypeJsonConversion.fromJsonString( + json['taskType'] as String, + ) + : null, description: json['description'] as String?, ); } @@ -490,18 +503,17 @@ class LMFSWaypoint { /// Greates a [LMFSWaypoint] instance from a [NavigationWaypoint]. factory LMFSWaypoint.fromNavigationWaypoint(NavigationWaypoint waypoint) { assert(waypoint.target != null, 'NavigationWaypoint target is null.'); - return LMFSWaypoint( - description: waypoint.title, - target: waypoint.target!, - ); + return LMFSWaypoint(description: waypoint.title, target: waypoint.target!); } - /// Constructs a Waypoint instance from a Map. + /// Constructs a Waypoint instance from a Map``. factory LMFSWaypoint.fromJson(Map json) { return LMFSWaypoint( description: json['description'] as String?, target: LatLng( - latitude: json['lat'] as double, longitude: json['lng'] as double), + latitude: json['lat'] as double, + longitude: json['lng'] as double, + ), ); } @@ -519,7 +531,7 @@ class LMFSWaypoint { /// The point on the map. final LatLng target; - /// Converts a Waypoint instance to a Map for JSON serialization. + /// Converts a Waypoint instance to a Map`` for JSON serialization. Map toJson() { return { 'description': description, diff --git a/example/lib/api/odrd_api.dart b/example/lib/api/odrd_api.dart index 0cf3bea..66ae55e 100644 --- a/example/lib/api/odrd_api.dart +++ b/example/lib/api/odrd_api.dart @@ -35,7 +35,8 @@ class ODRDApi extends ApiClient { final String typeStr = type.toJsonString(); final String response = await get('token/$typeStr/${vehicleId ?? ''}'); return TokenResponse.fromODRDJson( - jsonDecode(response) as Map); + jsonDecode(response) as Map, + ); } /// Creates a new vehicle in the ODRD backend with the specified details. @@ -61,8 +62,10 @@ class ODRDApi extends ApiClient { /// Fetches the details of a trip from the ODRD backend using the trip ID. Future getTrip(String tripId) async { final String response = await get('trip/$tripId'); - return ODRDTrip.fromJson((jsonDecode(response) - as Map)['trip'] as Map); + return ODRDTrip.fromJson( + (jsonDecode(response) as Map)['trip'] + as Map, + ); } /// Creates a new trip in the ODRD backend with the given trip data. diff --git a/example/lib/api/odrd_helpers.dart b/example/lib/api/odrd_helpers.dart index afd0cb0..9634315 100644 --- a/example/lib/api/odrd_helpers.dart +++ b/example/lib/api/odrd_helpers.dart @@ -25,11 +25,14 @@ import 'odrd_types.dart'; /// default value. /// See ./tools/backend/docker-compose.yml for the values of these environment /// variables. -const String _ODRDAndroidBaseUrl = String.fromEnvironment( - 'ODRD_ANDROID_HOST_URL', - defaultValue: 'http://10.0.2.2:8092'); -const String _ODRDiOSBaseUrl = String.fromEnvironment('ODRD_IOS_HOST_URL', - defaultValue: 'http://localhost:8092'); +const String _odrdAndroidBaseUrl = String.fromEnvironment( + 'ODRD_ANDROID_HOST_URL', + defaultValue: 'http://10.0.2.2:8092', +); +const String _odrdiOSBaseUrl = String.fromEnvironment( + 'ODRD_IOS_HOST_URL', + defaultValue: 'http://localhost:8092', +); ODRDApi? _odrdApiInstance; @@ -39,7 +42,7 @@ ODRDApi? _odrdApiInstance; ODRDApi getODRDApi() { if (_odrdApiInstance == null) { final String baseUrl = - Platform.isAndroid ? _ODRDAndroidBaseUrl : _ODRDiOSBaseUrl; + Platform.isAndroid ? _odrdAndroidBaseUrl : _odrdiOSBaseUrl; _odrdApiInstance = ODRDApi(baseUrl); } return _odrdApiInstance!; @@ -55,10 +58,12 @@ Future createODRDTrip({ assert(pickup.target != null, 'pickup.target is required'); assert(dropoff.target != null, 'dropoff.target is required'); assert( - intermediateDestinations == null || - intermediateDestinations - .every((NavigationWaypoint e) => e.target != null), - 'each intermediateDestinations must have target property set'); + intermediateDestinations == null || + intermediateDestinations.every( + (NavigationWaypoint e) => e.target != null, + ), + 'each intermediateDestinations must have target property set', + ); final ODRDApi odrdApi = getODRDApi(); @@ -66,9 +71,10 @@ Future createODRDTrip({ triptype: triptype ?? ODRDTripType.exclusive, pickup: pickup.target!, dropoff: dropoff.target!, - intermediateDestinations: intermediateDestinations - ?.map((NavigationWaypoint e) => e.target!) - .toList(), + intermediateDestinations: + intermediateDestinations + ?.map((NavigationWaypoint e) => e.target!) + .toList(), ); final ODRDTrip trip = await odrdApi.createTrip(createTrip); @@ -76,8 +82,10 @@ Future createODRDTrip({ } /// Updates a trip in the ODRD backend. -Future updateODRDTrip( - {required String tripId, required ODRDTripUpdate update}) async { +Future updateODRDTrip({ + required String tripId, + required ODRDTripUpdate update, +}) async { final ODRDApi odrdApi = getODRDApi(); final ODRDTrip trip = await odrdApi.updateTrip(tripId, update); return trip; @@ -102,8 +110,9 @@ Future createODRDVehicle({ maximumCapacity: maximumCapacity, ); - final ODRDVehicle initializedVehicle = - await odrdApi.createVehicle(createVehicle); + final ODRDVehicle initializedVehicle = await odrdApi.createVehicle( + createVehicle, + ); return initializedVehicle; } diff --git a/example/lib/api/odrd_types.dart b/example/lib/api/odrd_types.dart index 974fb3a..eec8819 100644 --- a/example/lib/api/odrd_types.dart +++ b/example/lib/api/odrd_types.dart @@ -93,45 +93,55 @@ class ODRDVehicle extends Vehicle { this.lastLocation, }); - /// Constructs a [ODRDVehicle] instance from a Map. + /// Constructs a [ODRDVehicle] instance from a Map``. factory ODRDVehicle.fromJson(Map json) { final String vehicleId = (json['name'] as String).split('/').last; return ODRDVehicle( vehicleId: vehicleId, vehicleState: ODRDVehicleStateJsonConversion.fromJsonString( - json['vehicleState'] as String), + json['vehicleState'] as String, + ), name: json['name'] as String?, - currentTripsIds: (json['currentTripsIds'] as List?) - ?.map((dynamic e) => e as String) - .toList(), - waypoints: (json['waypoints'] as List?) - ?.map((dynamic e) => ODRDWaypoint.fromJson(e as Map)) - .toList(), - supportedTripTypes: (json['supportedTripTypes'] as List?) - ?.map((dynamic e) => - ODRDTripTypesJsonConversion.fromJsonString(e as String)) - .toList(), + currentTripsIds: + (json['currentTripsIds'] as List?) + ?.map((dynamic e) => e as String) + .toList(), + waypoints: + (json['waypoints'] as List?) + ?.map( + (dynamic e) => ODRDWaypoint.fromJson(e as Map), + ) + .toList(), + supportedTripTypes: + (json['supportedTripTypes'] as List?) + ?.map( + (dynamic e) => + ODRDTripTypesJsonConversion.fromJsonString(e as String), + ) + .toList(), backToBackEnabled: json['backToBackEnabled'] as bool?, maximumCapacity: json['maximumCapacity'] as int?, - lastLocation: json['lastLocation'] == null - ? null - : LatLngJsonConversion.fromJson((json['lastLocation'] - as Map)['point'] as Map), + lastLocation: + json['lastLocation'] == null + ? null + : LatLngJsonConversion.fromJson( + (json['lastLocation'] as Map)['point'] + as Map, + ), ); } @override Map toJson() { - final Map json = { - 'vehicleId': vehicleId, - }; + final Map json = {'vehicleId': vehicleId}; if (vehicleState != null) { json['vehicleState'] = vehicleState!.toJsonString(); } if (supportedTripTypes != null) { - json['supportedTripTypes'] = supportedTripTypes! - .map((ODRDTripType e) => e.toJsonString()) - .toList(); + json['supportedTripTypes'] = + supportedTripTypes! + .map((ODRDTripType e) => e.toJsonString()) + .toList(); } if (backToBackEnabled != null) { json['backToBackEnabled'] = backToBackEnabled; @@ -173,15 +183,12 @@ class ODRDVehicle extends Vehicle { /// Helper class to convert LatLng to/from JSON. extension LatLngJsonConversion on LatLng { - /// Converts a LatLng instance to a Map for JSON serialization. + /// Converts a LatLng instance to a Map`` for JSON serialization. Map toJson() { - return { - 'latitude': latitude, - 'longitude': longitude, - }; + return {'latitude': latitude, 'longitude': longitude}; } - /// Constructs a [LatLng] instance from a Map. + /// Constructs a [LatLng] instance from a Map``. static LatLng fromJson(Map json) { return LatLng( latitude: json['latitude'] as double, @@ -199,7 +206,7 @@ enum ODRDWaypointType { dropOff, /// Intermediate destination waypoint type. - intermediateDestination + intermediateDestination, } /// Helper class to convert WaypointType to/from JSON. @@ -358,21 +365,23 @@ class ODRDWaypoint { this.tripId, }); - /// Constructs a [ODRDWaypoint] instance from a Map. + /// Constructs a [ODRDWaypoint] instance from a Map``. factory ODRDWaypoint.fromJson(Map json) { final Map location = json['location'] as Map; return ODRDWaypoint( location: LatLngJsonConversion.fromJson( - location['point'] as Map), + location['point'] as Map, + ), heading: location['heading'] as int? ?? 0, waypointType: ODRDWaypointTypeJsonConversion.fromJsonString( - json['waypointType'] as String), + json['waypointType'] as String, + ), tripId: json['tripId'] as String?, ); } - /// Converts a ODRDWaypoint instance to a Map for + /// Converts a ODRDWaypoint instance to a Map`` for /// JSON serialization. Map toJson() { return { @@ -402,13 +411,12 @@ class ODRDWaypoint { /// On-demand Rides and Deliveries Solution (ODRD). class ODRDTripUpdate { /// Constructs an [ODRDTripUpdate] instance with the given details. - ODRDTripUpdate({ - required this.tripStatus, - this.intermediateDestinationIndex, - }) : assert( - intermediateDestinationIndex == null || - tripStatus == ODRDTripStatus.enrouteToIntermediateDestination, - 'intermediateDestinationIndex can be used only with enrouteToIntermediateDestination status.'); + ODRDTripUpdate({required this.tripStatus, this.intermediateDestinationIndex}) + : assert( + intermediateDestinationIndex == null || + tripStatus == ODRDTripStatus.enrouteToIntermediateDestination, + 'intermediateDestinationIndex can be used only with enrouteToIntermediateDestination status.', + ); /// The next status of the trip. final ODRDTripStatus tripStatus; @@ -467,11 +475,8 @@ class ODRDCreateTrip { }; if (intermediateDestinations != null) { - json['intermediateDestinations'] = intermediateDestinations! - .map( - (LatLng l) => l.toJson(), - ) - .toList(); + json['intermediateDestinations'] = + intermediateDestinations!.map((LatLng l) => l.toJson()).toList(); } return json; @@ -498,10 +503,14 @@ class ODRDTrip { name: json['name'] as String, vehicleId: json['vehicleId'] as String, tripStatus: ODRDTripStatusJsonConversion.fromJsonString( - json['tripStatus'] as String), - waypoints: (json['waypoints'] as List) - .map((dynamic e) => ODRDWaypoint.fromJson(e as Map)) - .toList(), + json['tripStatus'] as String, + ), + waypoints: + (json['waypoints'] as List) + .map( + (dynamic e) => ODRDWaypoint.fromJson(e as Map), + ) + .toList(), ); } diff --git a/example/lib/api/shared_types.dart b/example/lib/api/shared_types.dart index ca2135f..926e666 100644 --- a/example/lib/api/shared_types.dart +++ b/example/lib/api/shared_types.dart @@ -22,10 +22,11 @@ class TokenResponse { /// [creationTimestampMs] - The Unix timestamp at which the token was created (in milliseconds). /// [expirationTimestampMs] - The Unix timestamp at which time the token will expire (in milliseconds). /// [token] - The token in base-64 encoded format. - const TokenResponse( - {required this.creationTimestampMs, - required this.expirationTimestampMs, - required this.token}); + const TokenResponse({ + required this.creationTimestampMs, + required this.expirationTimestampMs, + required this.token, + }); /// Factory constructor for LMFS API JSON response factory TokenResponse.fromLMFSJson(Map json) { @@ -61,6 +62,6 @@ abstract class Vehicle { /// The ID of the vehicle. String get vehicleId; - /// Converts a Vehicle instance to a Map for JSON serialization. + /// Converts a Vehicle instance to a Map`` for JSON serialization. Map toJson(); } diff --git a/example/lib/main.dart b/example/lib/main.dart index dbf8b27..80a08cd 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -106,15 +106,19 @@ class _DriverDemoState extends State with WidgetsBindingObserver { } ScaffoldMessenger.of(context).showSnackBar( SnackBar( - content: Text('$backendName backend is not running\n' - 'Read the README.md file for instructions on ' - 'how to start the backend services.')), + content: Text( + '$backendName backend is not running\n' + 'Read the README.md file for instructions on ' + 'how to start the backend services.', + ), + ), ); return; } - await Navigator.of(context) - .push(MaterialPageRoute(builder: (_) => page)); + await Navigator.of( + context, + ).push(MaterialPageRoute(builder: (_) => page)); } bool _isBackendRunning(ExamplePage page) { @@ -128,8 +132,9 @@ class _DriverDemoState extends State with WidgetsBindingObserver { } void _startBackendStatusPolling() { - _backendStatusPollingTimer = - Timer.periodic(const Duration(seconds: 5), (Timer timer) { + _backendStatusPollingTimer = Timer.periodic(const Duration(seconds: 5), ( + Timer timer, + ) { _checkBackendServicesStatus(); }); } @@ -166,44 +171,46 @@ class _DriverDemoState extends State with WidgetsBindingObserver { @override Widget build(BuildContext context) { - String buildPermissionsStatus() => (Platform.isIOS - ? 'Location ${_locationPermitted ? 'granted' : 'denied'} • Notifications ${_notificationsPermitted ? 'granted' : 'denied'}' - : 'Location ${_locationPermitted ? 'granted' : 'denied'} '); + String buildPermissionsStatus() => + (Platform.isIOS + ? 'Location ${_locationPermitted ? 'granted' : 'denied'} • Notifications ${_notificationsPermitted ? 'granted' : 'denied'}' + : 'Location ${_locationPermitted ? 'granted' : 'denied'} '); return Scaffold( appBar: AppBar(title: const Text('Google Maps Driver examples')), body: SafeArea( - top: false, - minimum: const EdgeInsets.all(8.0), - child: ListView.builder( - itemCount: _allPages.length + 1, - itemBuilder: (_, int index) { - if (index == 0) { - return Card( - child: Container( - padding: const EdgeInsets.all(8.0), - alignment: Alignment.center, - child: Text( - '${buildPermissionsStatus()}\n' - 'Driver SDK version: $_driverSDKVersion\n' - 'Navigation SDK version: $_navSDKVersion', - textAlign: TextAlign.center, - ), + top: false, + minimum: const EdgeInsets.all(8.0), + child: ListView.builder( + itemCount: _allPages.length + 1, + itemBuilder: (_, int index) { + if (index == 0) { + return Card( + child: Container( + padding: const EdgeInsets.all(8.0), + alignment: Alignment.center, + child: Text( + '${buildPermissionsStatus()}\n' + 'Driver SDK version: $_driverSDKVersion\n' + 'Navigation SDK version: $_navSDKVersion', + textAlign: TextAlign.center, ), - ); - } - final ExamplePage page = _allPages[index - 1]; - return ListTile( - leading: page.leading, - title: Text(page.title), - trailing: Icon( - _isBackendRunning(page) ? Icons.check_circle : Icons.error, - color: _isBackendRunning(page) ? Colors.green : Colors.red, ), - onTap: () => _pushPage(context, page), ); - }, - )), + } + final ExamplePage page = _allPages[index - 1]; + return ListTile( + leading: page.leading, + title: Text(page.title), + trailing: Icon( + _isBackendRunning(page) ? Icons.check_circle : Icons.error, + color: _isBackendRunning(page) ? Colors.green : Colors.red, + ), + onTap: () => _pushPage(context, page), + ); + }, + ), + ), ); } } @@ -211,12 +218,17 @@ class _DriverDemoState extends State with WidgetsBindingObserver { void main() { final ElevatedButtonThemeData exampleButtonDefaultTheme = ElevatedButtonThemeData( - style: ElevatedButton.styleFrom(minimumSize: const Size(160, 36))); - runApp(MaterialApp( - home: const DriverDemo(), - theme: ThemeData.light() - .copyWith(elevatedButtonTheme: exampleButtonDefaultTheme), - darkTheme: ThemeData.dark() - .copyWith(elevatedButtonTheme: exampleButtonDefaultTheme), - )); + style: ElevatedButton.styleFrom(minimumSize: const Size(160, 36)), + ); + runApp( + MaterialApp( + home: const DriverDemo(), + theme: ThemeData.light().copyWith( + elevatedButtonTheme: exampleButtonDefaultTheme, + ), + darkTheme: ThemeData.dark().copyWith( + elevatedButtonTheme: exampleButtonDefaultTheme, + ), + ), + ); } diff --git a/example/lib/pages/lmfs_driver.dart b/example/lib/pages/lmfs_driver.dart index e7ee2bf..98ca319 100644 --- a/example/lib/pages/lmfs_driver.dart +++ b/example/lib/pages/lmfs_driver.dart @@ -31,9 +31,10 @@ import '../widgets/widgets.dart'; class LMFSDriverPage extends ExamplePage { /// Creates a Google Maps Driver LMFS demo page. const LMFSDriverPage({super.key}) - : super( - leading: const Icon(Icons.directions), - title: 'Delivery Driver (LMFS)'); + : super( + leading: const Icon(Icons.directions), + title: 'Delivery Driver (LMFS)', + ); @override ExamplePageState createState() => _DriverPageState(); @@ -132,8 +133,9 @@ class _DriverPageState extends ExamplePageState target: const LatLng(latitude: 37.41914, longitude: -122.08845), ), NavigationWaypoint.withLatLngTarget( - title: 'CWF7+748, 1700 Amphitheatre Pkwy, Mountain View, CA 94043', - target: const LatLng(latitude: 37.4231613, longitude: -122.087159)) + title: 'CWF7+748, 1700 Amphitheatre Pkwy, Mountain View, CA 94043', + target: const LatLng(latitude: 37.4231613, longitude: -122.087159), + ), ], ); @@ -163,51 +165,68 @@ class _DriverPageState extends ExamplePageState } await DeliveryDriver.initialize( - providerId: _manifest.vehicle.providerId, - vehicleId: _manifest.vehicle.vehicleId, - onGetToken: (AuthTokenContext context) async { - if (_tokenResponse == null || - DateTime.now().millisecondsSinceEpoch > - _tokenResponse!.expirationTimestampMs) { - _tokenResponse = await getLMFSApi().getToken( - LMFSTokenType.deliveryDriver, _manifest.vehicle.vehicleId); - } - if (_tokenResponse == null || _tokenResponse!.token.isEmpty) { - throw Exception('Token retrieval from the backend failed.'); - } - - return _tokenResponse!.token; - }, - onStatusUpdate: Platform.isAndroid - ? (DriverStatusLevel level, DriverStatusCode code, - String message, DriverException? exception) { + providerId: _manifest.vehicle.providerId, + vehicleId: _manifest.vehicle.vehicleId, + onGetToken: (AuthTokenContext context) async { + if (_tokenResponse == null || + DateTime.now().millisecondsSinceEpoch > + _tokenResponse!.expirationTimestampMs) { + _tokenResponse = await getLMFSApi().getToken( + LMFSTokenType.deliveryDriver, + _manifest.vehicle.vehicleId, + ); + } + if (_tokenResponse == null || _tokenResponse!.token.isEmpty) { + throw Exception('Token retrieval from the backend failed.'); + } + + return _tokenResponse!.token; + }, + onStatusUpdate: + Platform.isAndroid + ? ( + DriverStatusLevel level, + DriverStatusCode code, + String message, + DriverException? exception, + ) { debugPrint( - // ignore: unnecessary_brace_in_string_interps - 'Driver status changed: $level - $code - $message, e: ${exception?.code} ${exception?.message}'); + // ignore: unnecessary_brace_in_string_interps + 'Driver status changed: $level - $code - $message, e: ${exception?.code} ${exception?.message}', + ); } - : null); + : null, + ); if (Platform.isIOS) { - DeliveryDriver.vehicleReporter.setListener(VehicleReporterListener( - onDidSucceed: (VehicleUpdate vehicleUpdate) { - debugPrint( - 'Vehicle update succeeded - location (${vehicleUpdate.location?.latitude.toStringAsFixed(3) ?? '-'}, ${vehicleUpdate.location?.longitude.toStringAsFixed(3) ?? '-'})'); - }, - onDidFail: - (VehicleUpdate vehicleUpdate, DriverException exception) { - debugPrint( - 'Vehicle updated failed - location (${vehicleUpdate.location?.latitude.toStringAsFixed(3) ?? '-'}, ${vehicleUpdate.location?.longitude.toStringAsFixed(3) ?? '-'})'); - debugPrint(' Error ${exception.message}'); - }, - )); + DeliveryDriver.vehicleReporter.setListener( + VehicleReporterListener( + onDidSucceed: (VehicleUpdate vehicleUpdate) { + debugPrint( + 'Vehicle update succeeded - location (${vehicleUpdate.location?.latitude.toStringAsFixed(3) ?? '-'}, ${vehicleUpdate.location?.longitude.toStringAsFixed(3) ?? '-'})', + ); + }, + onDidFail: ( + VehicleUpdate vehicleUpdate, + DriverException exception, + ) { + debugPrint( + 'Vehicle updated failed - location (${vehicleUpdate.location?.latitude.toStringAsFixed(3) ?? '-'}, ${vehicleUpdate.location?.longitude.toStringAsFixed(3) ?? '-'})', + ); + debugPrint(' Error ${exception.message}'); + }, + ), + ); } _locationReportingInterval = await DeliveryDriver.vehicleReporter.getLocationReportingInterval(); - await DeliveryDriver.vehicleReporter - .setLocationTrackingEnabled(_locationTrackingEnabled); - await DeliveryDriver.vehicleReporter - .setLocationReportingInterval(_locationReportingInterval!); + await DeliveryDriver.vehicleReporter.setLocationTrackingEnabled( + _locationTrackingEnabled, + ); + await DeliveryDriver.vehicleReporter.setLocationReportingInterval( + _locationReportingInterval!, + ); _driverInitialized = true; if (_stopUpdateMethod == _StopUpdateMethod.driverApi) { @@ -223,12 +242,14 @@ class _DriverPageState extends ExamplePageState switch (e.code) { case SessionInitializationError.locationPermissionMissing: _showMessage( - 'No user location is available. Did you allow location permission?'); + 'No user location is available. Did you allow location permission?', + ); case SessionInitializationError.termsNotAccepted: _showMessage('Accept the terms and conditions dialog first.'); case SessionInitializationError.notAuthorized: _showMessage( - 'Your API key is empty, invalid or not authorized to use Navigation.'); + 'Your API key is empty, invalid or not authorized to use Navigation.', + ); } } } @@ -264,8 +285,9 @@ class _DriverPageState extends ExamplePageState void _setupListeners() { _clearListeners(); - _onArrivalSubscription = - GoogleMapsNavigator.setOnArrivalListener(_onArrivalEvent); + _onArrivalSubscription = GoogleMapsNavigator.setOnArrivalListener( + _onArrivalEvent, + ); } void _clearListeners() { @@ -273,9 +295,7 @@ class _DriverPageState extends ExamplePageState _onArrivalSubscription = null; } - void _onArrivalEvent( - OnArrivalEvent event, - ) { + void _onArrivalEvent(OnArrivalEvent event) { if (!mounted) { return; } @@ -286,8 +306,10 @@ class _DriverPageState extends ExamplePageState debugPrint('Arrived to waypoint'); } - Future _resetSimulatedLocation(LatLng? location, - {bool stopSimulation = true}) async { + Future _resetSimulatedLocation( + LatLng? location, { + bool stopSimulation = true, + }) async { if (location != null) { if (stopSimulation) { await GoogleMapsNavigator.simulator.removeUserLocation(); @@ -307,8 +329,9 @@ class _DriverPageState extends ExamplePageState target: waypoint.target, ), ], - displayOptions: - NavigationDisplayOptions(showDestinationMarkers: false), + displayOptions: NavigationDisplayOptions( + showDestinationMarkers: false, + ), ); final NavigationRouteStatus status = @@ -316,8 +339,9 @@ class _DriverPageState extends ExamplePageState if (status == NavigationRouteStatus.statusOk) { await GoogleMapsNavigator.startGuidance(); - await _navigationViewController - .followMyLocation(CameraPerspective.tilted); + await _navigationViewController.followMyLocation( + CameraPerspective.tilted, + ); if (_simulationEnabled) { await _startSimulation(); } @@ -348,8 +372,10 @@ class _DriverPageState extends ExamplePageState } } else { await _loadingWrapper(() async { - _manifest = - await updateLMFSStopState(_manifest, VehicleStopState.enroute); + _manifest = await updateLMFSStopState( + _manifest, + VehicleStopState.enroute, + ); }); _updateVehicleStopsFromManifest(); } @@ -367,8 +393,10 @@ class _DriverPageState extends ExamplePageState } } else { await _loadingWrapper(() async { - _manifest = - await updateLMFSStopState(_manifest, VehicleStopState.arrived); + _manifest = await updateLMFSStopState( + _manifest, + VehicleStopState.arrived, + ); }); _updateVehicleStopsFromManifest(); } @@ -419,9 +447,9 @@ class _DriverPageState extends ExamplePageState Future _startSimulation() async { await GoogleMapsNavigator.simulator - .simulateLocationsAlongExistingRouteWithOptions(SimulationOptions( - speedMultiplier: 5, - )); + .simulateLocationsAlongExistingRouteWithOptions( + SimulationOptions(speedMultiplier: 5), + ); } Future _pauseSimulation() async { @@ -430,13 +458,15 @@ class _DriverPageState extends ExamplePageState Future _setSupplementalLocation() async { final Location location = Location( - latitude: _supplementalLocation.latitude, - longitude: _supplementalLocation.longitude, - accuracy: 1, - time: DateTime.now().millisecondsSinceEpoch); + latitude: _supplementalLocation.latitude, + longitude: _supplementalLocation.longitude, + accuracy: 1, + time: DateTime.now().millisecondsSinceEpoch, + ); await DeliveryDriver.setSupplementalLocation(location); showOverlaySnackBar( - 'DeliveryDriver supplemental location set successfully'); + 'DeliveryDriver supplemental location set successfully', + ); } Future _showDeliveryVehicle() async { @@ -473,116 +503,151 @@ Stops: ${vehicle.stops.length}'''); @override Widget build(BuildContext context) => buildPage( - context, - Stack(children: [ - Column(children: [ - Expanded(child: GoogleMapsNavigationView( - onViewCreated: (GoogleNavigationViewController controller) { - _navigationViewController = controller; - })), - Padding( + context, + Stack( + children: [ + Column( + children: [ + Expanded( + child: GoogleMapsNavigationView( + onViewCreated: (GoogleNavigationViewController controller) { + _navigationViewController = controller; + }, + ), + ), + Padding( padding: const EdgeInsets.all(8), - child: Column(children: [ - if (_driverInitialized) - Card( - child: Padding( - padding: const EdgeInsets.all(8), - child: Text( - _nextStop != null - ? 'Stop state: ${_vehicleStopStateToString(_nextStop!.vehicleStopState)}\nStops remaining: ${_vehicleStops.length}' - : 'No planned vehicle stops', + child: Column( + children: [ + if (_driverInitialized) + Card( + child: Padding( + padding: const EdgeInsets.all(8), + child: Text( + _nextStop != null + ? 'Stop state: ${_vehicleStopStateToString(_nextStop!.vehicleStopState)}\nStops remaining: ${_vehicleStops.length}' + : 'No planned vehicle stops', + ), ), ), - ), - if (_isLoading) - const Padding( - padding: EdgeInsets.all(6), - child: CircularProgressIndicator(), - ) - else - Wrap(spacing: 10, children: [ - if (!_driverInitialized) - ElevatedButton( - onPressed: _backendInitialized ? _initDriver : null, - child: const Text('Initialize driver'), - ), - if (!_driverInitialized && _backendInitialized) - ElevatedButton( - onPressed: () => Clipboard.setData( - ClipboardData(text: _manifest.vehicle.vehicleId)), - child: const Text('Copy vehicle ID')), - if (_driverInitialized && - _nextStop?.vehicleStopState == VehicleStopState.newStop) - ElevatedButton( - onPressed: () async { - await _enrouteToNextStop(); - await _startNavigation(); - }, - child: const Text('Navigate to next stop'), - ), - if (_nextStop == null && _driverInitialized) - ElevatedButton( - onPressed: () => Navigator.pop(context), - child: const Text('Exit')), - if (_driverInitialized && - _nextStop?.vehicleStopState == VehicleStopState.enroute) - ElevatedButton( - onPressed: () async { - await _stopNavigation(); - await _pauseSimulation(); - await _arrivedAtStop(); - }, - child: const Text('Arrived at stop'), - ), - if (_driverInitialized && - _nextStop?.vehicleStopState == VehicleStopState.arrived) - ElevatedButton( - onPressed: _completedStop, - child: const Text('Completed stop'), - ), - ]), - getOverlayOptionsButton(context, + if (_isLoading) + const Padding( + padding: EdgeInsets.all(6), + child: CircularProgressIndicator(), + ) + else + Wrap( + spacing: 10, + children: [ + if (!_driverInitialized) + ElevatedButton( + onPressed: _backendInitialized ? _initDriver : null, + child: const Text('Initialize driver'), + ), + if (!_driverInitialized && _backendInitialized) + ElevatedButton( + onPressed: + () => Clipboard.setData( + ClipboardData( + text: _manifest.vehicle.vehicleId, + ), + ), + child: const Text('Copy vehicle ID'), + ), + if (_driverInitialized && + _nextStop?.vehicleStopState == + VehicleStopState.newStop) + ElevatedButton( + onPressed: () async { + await _enrouteToNextStop(); + await _startNavigation(); + }, + child: const Text('Navigate to next stop'), + ), + if (_nextStop == null && _driverInitialized) + ElevatedButton( + onPressed: () => Navigator.pop(context), + child: const Text('Exit'), + ), + if (_driverInitialized && + _nextStop?.vehicleStopState == + VehicleStopState.enroute) + ElevatedButton( + onPressed: () async { + await _stopNavigation(); + await _pauseSimulation(); + await _arrivedAtStop(); + }, + child: const Text('Arrived at stop'), + ), + if (_driverInitialized && + _nextStop?.vehicleStopState == + VehicleStopState.arrived) + ElevatedButton( + onPressed: _completedStop, + child: const Text('Completed stop'), + ), + ], + ), + getOverlayOptionsButton( + context, onPressed: - _backendInitialized ? () => toggleOverlay() : null), - ])) - ]), - ])); + _backendInitialized ? () => toggleOverlay() : null, + ), + ], + ), + ), + ], + ), + ], + ), + ); @override Widget buildOverlayContent(BuildContext context) { - return Column(children: [ - Card( + return Column( + children: [ + Card( child: ExpansionTile( - title: const Text('Driver initialization'), - children: [ - Wrap( + title: const Text('Driver initialization'), + children: [ + Wrap( alignment: WrapAlignment.center, spacing: 10, children: [ ElevatedButton( onPressed: _driverInitialized ? _disposeDriver : _initDriver, - child: Text(_driverInitialized - ? 'Dispose driver' - : 'Initialize driver'), + child: Text( + _driverInitialized + ? 'Dispose driver' + : 'Initialize driver', + ), ), ElevatedButton( - onPressed: () => Clipboard.setData( - ClipboardData(text: _manifest.vehicle.vehicleId)), - child: const Text('Copy vehicle ID')), + onPressed: + () => Clipboard.setData( + ClipboardData(text: _manifest.vehicle.vehicleId), + ), + child: const Text('Copy vehicle ID'), + ), ElevatedButton( - onPressed: _driverInitialized - ? _navigationRunning - ? _stopNavigation - : _startNavigation - : null, - child: Text(_navigationRunning + onPressed: + _driverInitialized + ? _navigationRunning + ? _stopNavigation + : _startNavigation + : null, + child: Text( + _navigationRunning ? 'Stop navigation' - : 'Start navigation')), + : 'Start navigation', + ), + ), ElevatedButton( - onPressed: - _driverInitialized ? _showDeliveryVehicle : null, - child: const Text('Show delivery vehicle')), + onPressed: _driverInitialized ? _showDeliveryVehicle : null, + child: const Text('Show delivery vehicle'), + ), SwitchListTile( title: const Text('Simulation'), value: _simulationEnabled, @@ -601,112 +666,129 @@ Stops: ${vehicle.stops.length}'''); }); }, ), - ]) - ])), - IgnorePointer( + ], + ), + ], + ), + ), + IgnorePointer( ignoring: !_driverInitialized, child: Card( - child: ExpansionTile( - title: const Text('Vehicle stop handling'), - children: [ + child: ExpansionTile( + title: const Text('Vehicle stop handling'), + children: [ Wrap( - alignment: WrapAlignment.center, - spacing: 10, - children: [ - ExampleDropdownButton<_StopUpdateMethod>( - title: 'Stop update method', - value: _stopUpdateMethod, - items: _StopUpdateMethod.values, - onChanged: (_StopUpdateMethod? newValue) { + alignment: WrapAlignment.center, + spacing: 10, + children: [ + ExampleDropdownButton<_StopUpdateMethod>( + title: 'Stop update method', + value: _stopUpdateMethod, + items: _StopUpdateMethod.values, + onChanged: (_StopUpdateMethod? newValue) { + setState(() { + _stopUpdateMethod = newValue!; + }); + }, + ), + ElevatedButton( + onPressed: _nextStop != null ? _enrouteToNextStop : null, + child: const Text('Enroute to stop'), + ), + ElevatedButton( + onPressed: _nextStop != null ? _arrivedAtStop : null, + child: const Text('Arrived at stop'), + ), + ElevatedButton( + onPressed: + _driverInitialized && _nextStop != null + ? _completedStop + : null, + child: const Text('Completed stop'), + ), + if (_stopUpdateMethod == _StopUpdateMethod.driverApi) + SwitchListTile( + title: const Text('Force local stop state on update'), + value: _forceLocalStopStateOnDriverApiUpdates, + onChanged: (bool value) async { setState(() { - _stopUpdateMethod = newValue!; + _forceLocalStopStateOnDriverApiUpdates = value; }); }, ), + if (_stopUpdateMethod == _StopUpdateMethod.driverApi) ElevatedButton( - onPressed: - _nextStop != null ? _enrouteToNextStop : null, - child: const Text('Enroute to stop')), - ElevatedButton( - onPressed: _nextStop != null ? _arrivedAtStop : null, - child: const Text('Arrived at stop')), - ElevatedButton( - onPressed: _driverInitialized && _nextStop != null - ? _completedStop - : null, - child: const Text('Completed stop')), - if (_stopUpdateMethod == _StopUpdateMethod.driverApi) - SwitchListTile( - title: const Text('Force local stop state on update'), - value: _forceLocalStopStateOnDriverApiUpdates, - onChanged: (bool value) async { - setState(() { - _forceLocalStopStateOnDriverApiUpdates = value; - }); - }, - ), - if (_stopUpdateMethod == _StopUpdateMethod.driverApi) - ElevatedButton( - onPressed: () async { - await _updateVehicleStopsFromVehicleReporter(); - }, - child: - const Text('Update stops from vehicle reporter'), - ), - ]) - ]))), - Card( - child: ExpansionTile( - title: const Text('Vehicle location reporting'), - children: [ - SwitchListTile( - title: const Text('Location tracking'), - value: _locationTrackingEnabled, - onChanged: (bool value) async { - if (await DeliveryDriver.isInitialized()) { - await DeliveryDriver.vehicleReporter - .setLocationTrackingEnabled(value); - } - setState(() { - _locationTrackingEnabled = value; - }); - }, + onPressed: () async { + await _updateVehicleStopsFromVehicleReporter(); + }, + child: const Text('Update stops from vehicle reporter'), + ), + ], + ), + ], ), - ExampleSlider( + ), + ), + Card( + child: ExpansionTile( + title: const Text('Vehicle location reporting'), + children: [ + SwitchListTile( + title: const Text('Location tracking'), + value: _locationTrackingEnabled, + onChanged: (bool value) async { + if (await DeliveryDriver.isInitialized()) { + await DeliveryDriver.vehicleReporter + .setLocationTrackingEnabled(value); + } + setState(() { + _locationTrackingEnabled = value; + }); + }, + ), + ExampleSlider( unit: 's', title: 'Reporting interval', min: 5, max: 60, value: _locationReportingInterval?.inSeconds.toDouble() ?? 5, fractionDigits: 0, - onChanged: _locationTrackingEnabled - ? (double newValue) async { - _locationReportingInterval = - Duration(seconds: newValue.toInt()); - if (_driverInitialized) { - await DeliveryDriver.vehicleReporter - .setLocationReportingInterval( - _locationReportingInterval!); - setState(() { - _locationReportingInterval = - _locationReportingInterval; - }); + onChanged: + _locationTrackingEnabled + ? (double newValue) async { + _locationReportingInterval = Duration( + seconds: newValue.toInt(), + ); + if (_driverInitialized) { + await DeliveryDriver.vehicleReporter + .setLocationReportingInterval( + _locationReportingInterval!, + ); + setState(() { + _locationReportingInterval = + _locationReportingInterval; + }); + } } - } - : null) - ])), - Card( + : null, + ), + ], + ), + ), + Card( child: ExpansionTile( - title: const Text('Supplemental location'), - children: [ - Wrap( + title: const Text('Supplemental location'), + children: [ + Wrap( alignment: WrapAlignment.center, spacing: 10, children: [ ExampleLatLngEditor( title: 'Coordinates', - initialLatLng: - const LatLng(latitude: 65.0, longitude: 25.5), + initialLatLng: const LatLng( + latitude: 65.0, + longitude: 25.5, + ), onChanged: (LatLng newTarget) { _supplementalLocation = newTarget; }, @@ -716,22 +798,29 @@ Stops: ${vehicle.stops.length}'''); _driverInitialized ? _setSupplementalLocation : null, child: const Text('Set supplemental location'), ), - ]) - ])), - ]); + ], + ), + ], + ), + ), + ], + ); } // Current version of the driver API does not update the stop state properly, // this is a workaround to force the stop state to be updated locally. void _forceUpdateLocalStopState( - VehicleStopState state, List stops) { + VehicleStopState state, + List stops, + ) { if (_forceLocalStopStateOnDriverApiUpdates && _stopUpdateMethod == _StopUpdateMethod.driverApi && stops.isNotEmpty) { stops[0] = VehicleStop( - vehicleStopState: state, - waypoint: stops[0].waypoint, - taskInfoList: stops[0].taskInfoList); + vehicleStopState: state, + waypoint: stops[0].waypoint, + taskInfoList: stops[0].taskInfoList, + ); } } @@ -753,7 +842,4 @@ Stops: ${vehicle.stops.length}'''); } } -enum _StopUpdateMethod { - backend, - driverApi, -} +enum _StopUpdateMethod { backend, driverApi } diff --git a/example/lib/pages/odrd_driver.dart b/example/lib/pages/odrd_driver.dart index 42eefd5..7bc0a7e 100644 --- a/example/lib/pages/odrd_driver.dart +++ b/example/lib/pages/odrd_driver.dart @@ -29,9 +29,10 @@ import '../widgets/widgets.dart'; class ODRDDriverPage extends ExamplePage { /// Creates a Google Maps Driver ODRD demo page. const ODRDDriverPage({super.key}) - : super( - leading: const Icon(Icons.directions), - title: 'Ridesharing Driver (ODRD)'); + : super( + leading: const Icon(Icons.directions), + title: 'Ridesharing Driver (ODRD)', + ); @override ExamplePageState createState() => _DriverPageState(); @@ -46,43 +47,47 @@ class _ExampleTrip { final List<_ExampleTrip> _exampleTrips = <_ExampleTrip>[ _ExampleTrip( - NavigationWaypoint.withLatLngTarget( - title: 'Kuusiluoto, Oulu', - target: const LatLng(latitude: 65.0105737, longitude: 25.4564055), - ), - NavigationWaypoint.withLatLngTarget( - title: 'Höyhtyä, Oulu', - target: const LatLng(latitude: 64.9955575, longitude: 25.4865491), - )), + NavigationWaypoint.withLatLngTarget( + title: 'Kuusiluoto, Oulu', + target: const LatLng(latitude: 65.0105737, longitude: 25.4564055), + ), + NavigationWaypoint.withLatLngTarget( + title: 'Höyhtyä, Oulu', + target: const LatLng(latitude: 64.9955575, longitude: 25.4865491), + ), + ), _ExampleTrip( - NavigationWaypoint.withLatLngTarget( - title: 'Valtatie, Oulu', - target: const LatLng(latitude: 65.027869, longitude: 25.457963), - ), - NavigationWaypoint.withLatLngTarget( - title: 'Hollihaka, Oulu', - target: const LatLng(latitude: 65.007450, longitude: 25.449969), - )), + NavigationWaypoint.withLatLngTarget( + title: 'Valtatie, Oulu', + target: const LatLng(latitude: 65.027869, longitude: 25.457963), + ), + NavigationWaypoint.withLatLngTarget( + title: 'Hollihaka, Oulu', + target: const LatLng(latitude: 65.007450, longitude: 25.449969), + ), + ), _ExampleTrip( - NavigationWaypoint.withLatLngTarget( - title: 'Tuira, Oulu', - target: const LatLng(latitude: 65.0161051, longitude: 25.4983671), - ), - NavigationWaypoint.withLatLngTarget( - title: 'Nokela, Oulu', - target: const LatLng(latitude: 64.9904488, longitude: 25.4719577), - )) + NavigationWaypoint.withLatLngTarget( + title: 'Tuira, Oulu', + target: const LatLng(latitude: 65.0161051, longitude: 25.4983671), + ), + NavigationWaypoint.withLatLngTarget( + title: 'Nokela, Oulu', + target: const LatLng(latitude: 64.9904488, longitude: 25.4719577), + ), + ), ]; /// Driver demo page state. class _DriverPageState extends ExamplePageState with WidgetsBindingObserver { - static const LatLng _startLocation = - LatLng(latitude: 65.002822, longitude: 25.463639); + static const LatLng _startLocation = LatLng( + latitude: 65.002822, + longitude: 25.463639, + ); final Completer - _navigationControllerCompleter = - Completer(); + _navigationControllerCompleter = Completer(); bool _backendInitialized = false; bool _driverInitialized = false; @@ -191,7 +196,8 @@ class _DriverPageState extends ExamplePageState ); debugPrint( - 'ODRD backend initialized.\nVehicle ID: ${_vehicle!.vehicleId}\nVehicle state: ${_vehicle!.vehicleState?.name}'); + 'ODRD backend initialized.\nVehicle ID: ${_vehicle!.vehicleId}\nVehicle state: ${_vehicle!.vehicleState?.name}', + ); setState(() { _backendInitialized = true; _vehicleUpdated = true; @@ -226,14 +232,18 @@ class _DriverPageState extends ExamplePageState debugPrint('ODRD backend Trip ID: ${_trip!.tripId}'); if (_vehicle?.waypoints != null) { - _waypoints = _vehicle!.waypoints! - .asMap() - .entries - .map((MapEntry waypointEntry) => - NavigationWaypoint.withLatLngTarget( - target: waypointEntry.value.location, - title: 'Waypoint ${waypointEntry.key + 1}')) - .toList(); + _waypoints = + _vehicle!.waypoints! + .asMap() + .entries + .map( + (MapEntry waypointEntry) => + NavigationWaypoint.withLatLngTarget( + target: waypointEntry.value.location, + title: 'Waypoint ${waypointEntry.key + 1}', + ), + ) + .toList(); } await _initNavigation(); _pollVehicleUpdates(); @@ -253,52 +263,66 @@ class _DriverPageState extends ExamplePageState // Initialize Ridesharing Driver SDK. await RidesharingDriver.initialize( - providerId: getProjectId(), - vehicleId: _vehicle!.vehicleId, - onGetToken: (AuthTokenContext context) async { - if (_tokenResponse == null || - DateTime.now().millisecondsSinceEpoch > - _tokenResponse!.expirationTimestampMs) { - _tokenResponse = await getODRDApi().getToken( - ODRDTokenType.driver, - _vehicle!.vehicleId, - ); - } - if (_tokenResponse == null || _tokenResponse!.token.isEmpty) { - throw Exception('Token retrieval from the backend failed.'); - } - - return Future.value(_tokenResponse!.token); - }, - onStatusUpdate: Platform.isAndroid - ? (DriverStatusLevel level, DriverStatusCode code, - String message, DriverException? exception) { + providerId: getProjectId(), + vehicleId: _vehicle!.vehicleId, + onGetToken: (AuthTokenContext context) async { + if (_tokenResponse == null || + DateTime.now().millisecondsSinceEpoch > + _tokenResponse!.expirationTimestampMs) { + _tokenResponse = await getODRDApi().getToken( + ODRDTokenType.driver, + _vehicle!.vehicleId, + ); + } + if (_tokenResponse == null || _tokenResponse!.token.isEmpty) { + throw Exception('Token retrieval from the backend failed.'); + } + + return Future.value(_tokenResponse!.token); + }, + onStatusUpdate: + Platform.isAndroid + ? ( + DriverStatusLevel level, + DriverStatusCode code, + String message, + DriverException? exception, + ) { debugPrint( - 'Driver status changed: $level - $code - $message, e: ${exception?.code} ${exception?.message}'); + 'Driver status changed: $level - $code - $message, e: ${exception?.code} ${exception?.message}', + ); } - : null); + : null, + ); if (Platform.isIOS) { - RidesharingDriver.vehicleReporter.setListener(VehicleReporterListener( - onDidSucceed: (VehicleUpdate vehicleUpdate) { - debugPrint( - 'Vehicle update succeeded - location (${vehicleUpdate.location?.latitude.toStringAsFixed(3) ?? '-'}, ${vehicleUpdate.location?.longitude.toStringAsFixed(3) ?? '-'}) and state: ${vehicleUpdate.vehicleState == VehicleState.online ? 'online' : 'offline'}'); - }, - onDidFail: - (VehicleUpdate vehicleUpdate, DriverException exception) { - debugPrint( - 'Vehicle updated failed - location (${vehicleUpdate.location?.latitude.toStringAsFixed(3) ?? '-'}, ${vehicleUpdate.location?.longitude.toStringAsFixed(3) ?? '-'}) state: ${vehicleUpdate.vehicleState == VehicleState.online ? 'online' : 'offline'}'); - debugPrint(' Error ${exception.message}'); - }, - )); + RidesharingDriver.vehicleReporter.setListener( + VehicleReporterListener( + onDidSucceed: (VehicleUpdate vehicleUpdate) { + debugPrint( + 'Vehicle update succeeded - location (${vehicleUpdate.location?.latitude.toStringAsFixed(3) ?? '-'}, ${vehicleUpdate.location?.longitude.toStringAsFixed(3) ?? '-'}) and state: ${vehicleUpdate.vehicleState == VehicleState.online ? 'online' : 'offline'}', + ); + }, + onDidFail: ( + VehicleUpdate vehicleUpdate, + DriverException exception, + ) { + debugPrint( + 'Vehicle updated failed - location (${vehicleUpdate.location?.latitude.toStringAsFixed(3) ?? '-'}, ${vehicleUpdate.location?.longitude.toStringAsFixed(3) ?? '-'}) state: ${vehicleUpdate.vehicleState == VehicleState.online ? 'online' : 'offline'}', + ); + debugPrint(' Error ${exception.message}'); + }, + ), + ); } // Fetch the current locationReportintInterval - await RidesharingDriver.vehicleReporter - .setLocationReportingInterval(const Duration(seconds: 5)); - _locationReportingIntervalMillis = await RidesharingDriver - .vehicleReporter - .getLocationReportingInterval(); + await RidesharingDriver.vehicleReporter.setLocationReportingInterval( + const Duration(seconds: 5), + ); + _locationReportingIntervalMillis = + await RidesharingDriver.vehicleReporter + .getLocationReportingInterval(); if (!_locationTrackingEnabled) { await _setLocationTrackingEnabled(true); } @@ -313,12 +337,14 @@ class _DriverPageState extends ExamplePageState switch (e.code) { case SessionInitializationError.locationPermissionMissing: _showMessage( - 'No user location is available. Did you allow location permission?'); + 'No user location is available. Did you allow location permission?', + ); case SessionInitializationError.termsNotAccepted: _showMessage('Accept the terms and conditions dialog first.'); case SessionInitializationError.notAuthorized: _showMessage( - 'Your API key is empty, invalid or not authorized to use Navigation.'); + 'Your API key is empty, invalid or not authorized to use Navigation.', + ); } } } @@ -330,8 +356,9 @@ class _DriverPageState extends ExamplePageState void _pollTripUpdates() { assert(_trip != null && _trip!.tripId.isNotEmpty, 'tripId is required'); _stopPollingTripUpdates(); - _tripUpdateTimer = - Timer.periodic(const Duration(seconds: 5), (Timer timer) async { + _tripUpdateTimer = Timer.periodic(const Duration(seconds: 5), ( + Timer timer, + ) async { try { if (_trip == null) { _stopPollingTripUpdates(); @@ -339,7 +366,8 @@ class _DriverPageState extends ExamplePageState } _trip = await getODRDApi().getTrip(_selectedTripId ?? _trip!.tripId); debugPrint( - ' - Trip (${_trip!.tripId}) status: ${_trip!.tripStatus.name}'); + ' - Trip (${_trip!.tripId}) status: ${_trip!.tripStatus.name}', + ); bool tripMatched = false; if (_trip!.vehicleId.isNotEmpty && !_tripMatched) { debugPrint(' - Trip has matched vehicle: ${_trip!.vehicleId}'); @@ -367,33 +395,38 @@ class _DriverPageState extends ExamplePageState assert(_vehicle != null, 'vehicle is required'); _stopPollingVehicleUpdates(); _vehicleUpdateTimer = Timer.periodic( - _locationReportingIntervalMillis ?? const Duration(seconds: 5), - (Timer timer) async { - try { - final ODRDVehicle vehicle = - await getODRDApi().getVehicle(_vehicle!.vehicleId); - debugPrint( - ' - Vehicle (${vehicle.vehicleId}) state: ${vehicle.vehicleState?.name}, vehicle trips: ${vehicle.currentTripsIds}, vehicle waypoints: ${vehicle.waypoints}, last location ${vehicle.lastLocation?.latitude},${vehicle.lastLocation?.longitude}'); + _locationReportingIntervalMillis ?? const Duration(seconds: 5), + (Timer timer) async { + try { + final ODRDVehicle vehicle = await getODRDApi().getVehicle( + _vehicle!.vehicleId, + ); + debugPrint( + ' - Vehicle (${vehicle.vehicleId}) state: ${vehicle.vehicleState?.name}, vehicle trips: ${vehicle.currentTripsIds}, vehicle waypoints: ${vehicle.waypoints}, last location ${vehicle.lastLocation?.latitude},${vehicle.lastLocation?.longitude}', + ); + + if (_simulationRunning && vehicle.lastLocation != null) { + _lastKnownDriverLocation = vehicle.lastLocation; + } - if (_simulationRunning && vehicle.lastLocation != null) { - _lastKnownDriverLocation = vehicle.lastLocation; + _vehicleState = + vehicle.vehicleState == ODRDVehicleState.online + ? VehicleState.online + : VehicleState.offline; + + setState(() { + _vehicleUpdated = true; + _vehicle = vehicle; + }); + + await _updateFleetEngineLocationMarker( + show: _showFleetEngineLocationOnMap, + ); + } catch (e) { + debugPrint(' - Error fetching vehicle: $e'); } - - _vehicleState = vehicle.vehicleState == ODRDVehicleState.online - ? VehicleState.online - : VehicleState.offline; - - setState(() { - _vehicleUpdated = true; - _vehicle = vehicle; - }); - - await _updateFleetEngineLocationMarker( - show: _showFleetEngineLocationOnMap); - } catch (e) { - debugPrint(' - Error fetching vehicle: $e'); - } - }); + }, + ); } void _stopPollingVehicleUpdates() { @@ -405,7 +438,8 @@ class _DriverPageState extends ExamplePageState final List allVehicles = await getODRDApi().getVehicles(); allVehicles.map((ODRDVehicle vehicle) { debugPrint( - 'Vehicle: ${vehicle.vehicleId}, Vehicle state: ${vehicle.vehicleState?.name}, Vehicle trips: ${vehicle.currentTripsIds}'); + 'Vehicle: ${vehicle.vehicleId}, Vehicle state: ${vehicle.vehicleState?.name}, Vehicle trips: ${vehicle.currentTripsIds}', + ); }).toList(); } @@ -416,9 +450,7 @@ class _DriverPageState extends ExamplePageState try { _trip = await updateODRDTrip( tripId: _trip!.tripId, - update: ODRDTripUpdate( - tripStatus: status, - ), + update: ODRDTripUpdate(tripStatus: status), ); if (status.name.contains('enroute')) { @@ -538,8 +570,10 @@ class _DriverPageState extends ExamplePageState } } - Future _resetSimulatedLocation(LatLng? location, - {bool stopSimulation = true}) async { + Future _resetSimulatedLocation( + LatLng? location, { + bool stopSimulation = true, + }) async { if (location != null) { if (stopSimulation) { await GoogleMapsNavigator.simulator.removeUserLocation(); @@ -555,15 +589,15 @@ class _DriverPageState extends ExamplePageState if (_waypoints.length > _waypointIndex) { // Reset simulated user location. If navigation is running, this will use the // last location from the fleet engine. - await GoogleMapsNavigator.simulator - .setUserLocation(_lastKnownDriverLocation ?? _startLocation); + await GoogleMapsNavigator.simulator.setUserLocation( + _lastKnownDriverLocation ?? _startLocation, + ); await GoogleMapsNavigator.simulator .simulateLocationsAlongNewRouteWithRoutingAndSimulationOptions( - [_waypoints[_waypointIndex]], - RoutingOptions(), - SimulationOptions( - speedMultiplier: simulationSpeedMultiplier, - )); + [_waypoints[_waypointIndex]], + RoutingOptions(), + SimulationOptions(speedMultiplier: simulationSpeedMultiplier), + ); setState(() { _waypointIndex = _waypointIndex + 1; _simulationRunning = true; @@ -573,8 +607,9 @@ class _DriverPageState extends ExamplePageState void _setupListeners() { _clearListeners(); - _onArrivalSubscription = - GoogleMapsNavigator.setOnArrivalListener(_onArrivalEvent); + _onArrivalSubscription = GoogleMapsNavigator.setOnArrivalListener( + _onArrivalEvent, + ); } void _clearListeners() { @@ -582,9 +617,7 @@ class _DriverPageState extends ExamplePageState _onArrivalSubscription = null; } - void _onArrivalEvent( - OnArrivalEvent event, - ) { + void _onArrivalEvent(OnArrivalEvent event) { if (!mounted) { return; } @@ -624,45 +657,49 @@ class _DriverPageState extends ExamplePageState @override Widget build(BuildContext context) { - final String tripState = _trip?.vehicleId != null - ? 'Trip state: ${_getTripStatusText(_trip?.tripStatus)}' - : 'No trip'; - final String vehicleState = _trip?.vehicleId != null - ? 'Assigned vehicle ID: ${_trip?.vehicleId}' - : 'No assigned vehicle'; + final String tripState = + _trip?.vehicleId != null + ? 'Trip state: ${_getTripStatusText(_trip?.tripStatus)}' + : 'No trip'; + final String vehicleState = + _trip?.vehicleId != null + ? 'Assigned vehicle ID: ${_trip?.vehicleId}' + : 'No assigned vehicle'; return buildPage( - context, - Stack(children: [ - Column(children: [ - Expanded( + context, + Stack( + children: [ + Column( + children: [ + Expanded( child: GoogleMapsNavigationView( - onViewCreated: (GoogleNavigationViewController controller) { - _navigationControllerCompleter.complete(controller); - }, - initialCameraPosition: const CameraPosition( - target: _startLocation, - zoom: 14, + onViewCreated: (GoogleNavigationViewController controller) { + _navigationControllerCompleter.complete(controller); + }, + initialCameraPosition: const CameraPosition( + target: _startLocation, + zoom: 14, + ), + ), ), - )), - Padding( + Padding( padding: const EdgeInsets.all(8), - child: Column(children: [ - if (_driverInitialized) - Card( - child: Padding( - padding: const EdgeInsets.all(8), - child: Text( - '$tripState\n$vehicleState', + child: Column( + children: [ + if (_driverInitialized) + Card( + child: Padding( + padding: const EdgeInsets.all(8), + child: Text('$tripState\n$vehicleState'), ), ), - ), - if (_isLoading) - const Padding( - padding: EdgeInsets.all(6), - child: CircularProgressIndicator(), - ) - else - Wrap( + if (_isLoading) + const Padding( + padding: EdgeInsets.all(6), + child: CircularProgressIndicator(), + ) + else + Wrap( alignment: WrapAlignment.center, spacing: 10, children: [ @@ -673,16 +710,16 @@ class _DriverPageState extends ExamplePageState ), if (_driverInitialized && !_locationTrackingEnabled) ElevatedButton( - onPressed: () => - _setLocationTrackingEnabled(true), + onPressed: + () => _setLocationTrackingEnabled(true), child: const Text('Enable location tracking'), ), if (_driverInitialized && _locationTrackingEnabled && _vehicleState == VehicleState.offline) ElevatedButton( - onPressed: () => - _setVehicleState(VehicleState.online), + onPressed: + () => _setVehicleState(VehicleState.online), child: const Text('Set vehicle online'), ), if (_driverInitialized && @@ -690,8 +727,9 @@ class _DriverPageState extends ExamplePageState _vehicleUpdated) ElevatedButton( onPressed: _createExampleTrip, - child: - const Text('Create new trip (as consumer)'), + child: const Text( + 'Create new trip (as consumer)', + ), ), if (_canSelectNewTrip) for (final MapEntry entry @@ -703,14 +741,22 @@ class _DriverPageState extends ExamplePageState if (_hasTrips && _hasSelectedTrip && _trip?.tripId == _selectedTripId) - _buildRouteActionButtons() - ]), - getOverlayOptionsButton(context, + _buildRouteActionButtons(), + ], + ), + getOverlayOptionsButton( + context, onPressed: - _backendInitialized ? () => toggleOverlay() : null), - ])) - ]), - ])); + _backendInitialized ? () => toggleOverlay() : null, + ), + ], + ), + ), + ], + ), + ], + ), + ); } bool get _hasVehicle => _vehicle != null; @@ -724,57 +770,62 @@ class _DriverPageState extends ExamplePageState @override Widget buildOverlayContent(BuildContext context) { - return Column(children: [ - Wrap( - alignment: WrapAlignment.center, - spacing: 10, - children: [ - SwitchListTile( - title: const Text('Location tracking'), - value: _locationTrackingEnabled, - onChanged: (bool value) async { - if (await RidesharingDriver.isInitialized()) { - await RidesharingDriver.vehicleReporter - .setLocationTrackingEnabled(value); - } - setState(() { - _locationTrackingEnabled = value; - }); - }, - ), - SwitchListTile( - title: const Text('Vehicle online'), - value: _vehicleState == VehicleState.online, - onChanged: _locationTrackingEnabled - ? (bool value) async { - final VehicleState newState = - value ? VehicleState.online : VehicleState.offline; - await _setVehicleState(newState); - setState(() { - _vehicleState = newState; - }); - } - : null, - ), - SwitchListTile( - title: const Text('Show fleet engine location marker'), - value: _showFleetEngineLocationOnMap, - onChanged: (bool value) async { - await _updateFleetEngineLocationMarker(show: value); - }, - ), - ElevatedButton( - onPressed: _driverInitialized ? _disposeDriver : _initializeDriver, - child: Text( - _driverInitialized ? 'Dispose driver' : 'Initialize driver'), - ), - ElevatedButton( - onPressed: _fetchVehicles, - child: const Text('Debug print all vehicles'), - ), - ], - ) - ]); + return Column( + children: [ + Wrap( + alignment: WrapAlignment.center, + spacing: 10, + children: [ + SwitchListTile( + title: const Text('Location tracking'), + value: _locationTrackingEnabled, + onChanged: (bool value) async { + if (await RidesharingDriver.isInitialized()) { + await RidesharingDriver.vehicleReporter + .setLocationTrackingEnabled(value); + } + setState(() { + _locationTrackingEnabled = value; + }); + }, + ), + SwitchListTile( + title: const Text('Vehicle online'), + value: _vehicleState == VehicleState.online, + onChanged: + _locationTrackingEnabled + ? (bool value) async { + final VehicleState newState = + value ? VehicleState.online : VehicleState.offline; + await _setVehicleState(newState); + setState(() { + _vehicleState = newState; + }); + } + : null, + ), + SwitchListTile( + title: const Text('Show fleet engine location marker'), + value: _showFleetEngineLocationOnMap, + onChanged: (bool value) async { + await _updateFleetEngineLocationMarker(show: value); + }, + ), + ElevatedButton( + onPressed: + _driverInitialized ? _disposeDriver : _initializeDriver, + child: Text( + _driverInitialized ? 'Dispose driver' : 'Initialize driver', + ), + ), + ElevatedButton( + onPressed: _fetchVehicles, + child: const Text('Debug print all vehicles'), + ), + ], + ), + ], + ); } Wrap _buildRouteActionButtons() { @@ -836,24 +887,29 @@ class _DriverPageState extends ExamplePageState await _navigationControllerCompleter.future; if (show) { final MarkerOptions options = MarkerOptions( - position: _lastKnownDriverLocation ?? _startLocation, - infoWindow: const InfoWindow(title: 'Fleet engine location')); + position: _lastKnownDriverLocation ?? _startLocation, + infoWindow: const InfoWindow(title: 'Fleet engine location'), + ); if (_fleetEngineLocationMarker != null) { - final Marker updatedMarker = - _fleetEngineLocationMarker!.copyWith(options: options); + final Marker updatedMarker = _fleetEngineLocationMarker!.copyWith( + options: options, + ); _fleetEngineLocationMarker = - (await viewController.updateMarkers([updatedMarker])) - .firstOrNull; + (await viewController.updateMarkers([ + updatedMarker, + ])).firstOrNull; } else { _fleetEngineLocationMarker = - (await viewController.addMarkers([options])) - .firstOrNull; + (await viewController.addMarkers([ + options, + ])).firstOrNull; } } else { if (_fleetEngineLocationMarker != null) { - await viewController - .removeMarkers([_fleetEngineLocationMarker!]); + await viewController.removeMarkers([ + _fleetEngineLocationMarker!, + ]); setState(() { _fleetEngineLocationMarker = null; }); diff --git a/example/lib/utils/overlay_options.dart b/example/lib/utils/overlay_options.dart index 0edcf9b..2e1ca76 100644 --- a/example/lib/utils/overlay_options.dart +++ b/example/lib/utils/overlay_options.dart @@ -21,24 +21,25 @@ Widget getOptionsButton( BuildContext context, { required void Function()? onPressed, ButtonStyle? style, -}) => - ElevatedButton.icon( - style: style ?? ElevatedButton.styleFrom(minimumSize: const Size(80, 36)), - icon: const Icon(Icons.settings), - onPressed: onPressed, - label: const Text('Options'), - ); +}) => ElevatedButton.icon( + style: style ?? ElevatedButton.styleFrom(minimumSize: const Size(80, 36)), + icon: const Icon(Icons.settings), + onPressed: onPressed, + label: const Text('Options'), +); /// Builds options button Widget with positioned alignment for the example app. -Widget getOverlayOptionsButton(BuildContext context, - {required void Function()? onPressed, ButtonStyle? style}) => - SafeArea( - child: Align( - alignment: - Platform.isAndroid ? Alignment.bottomCenter : Alignment.bottomRight, - child: Padding( - padding: const EdgeInsets.all(10), - child: getOptionsButton(context, onPressed: onPressed, style: style), - ), - ), - ); +Widget getOverlayOptionsButton( + BuildContext context, { + required void Function()? onPressed, + ButtonStyle? style, +}) => SafeArea( + child: Align( + alignment: + Platform.isAndroid ? Alignment.bottomCenter : Alignment.bottomRight, + child: Padding( + padding: const EdgeInsets.all(10), + child: getOptionsButton(context, onPressed: onPressed, style: style), + ), + ), +); diff --git a/example/lib/widgets/dropdown_button.dart b/example/lib/widgets/dropdown_button.dart index 63d0ac1..aceaec4 100644 --- a/example/lib/widgets/dropdown_button.dart +++ b/example/lib/widgets/dropdown_button.dart @@ -36,12 +36,10 @@ class ExampleDropdownButton extends StatelessWidget { title: Text(title), trailing: DropdownButton( value: value, - items: items.map>((T value) { - return DropdownMenuItem( - value: value, - child: Text(value.name), - ); - }).toList(), + items: + items.map>((T value) { + return DropdownMenuItem(value: value, child: Text(value.name)); + }).toList(), onChanged: onChanged, ), ); diff --git a/example/lib/widgets/latlng_editor.dart b/example/lib/widgets/latlng_editor.dart index eff7823..eba27e6 100644 --- a/example/lib/widgets/latlng_editor.dart +++ b/example/lib/widgets/latlng_editor.dart @@ -82,40 +82,42 @@ class ExampleLatLngTextEditor extends StatelessWidget { @override Widget build(BuildContext context) { - return Column(children: [ - Padding( - padding: const EdgeInsetsDirectional.only(start: 16.0, end: 24.0), - child: TextFormField( - initialValue: initialLatLng.latitude.toString(), - decoration: const InputDecoration(labelText: 'Latitude'), - keyboardType: TextInputType.number, - onChanged: (String value) { - onChanged( - LatLng( - latitude: double.parse(value), - longitude: initialLatLng.longitude, - ), - ); - }, + return Column( + children: [ + Padding( + padding: const EdgeInsetsDirectional.only(start: 16.0, end: 24.0), + child: TextFormField( + initialValue: initialLatLng.latitude.toString(), + decoration: const InputDecoration(labelText: 'Latitude'), + keyboardType: TextInputType.number, + onChanged: (String value) { + onChanged( + LatLng( + latitude: double.parse(value), + longitude: initialLatLng.longitude, + ), + ); + }, + ), ), - ), - Padding( - padding: const EdgeInsetsDirectional.only(start: 16.0, end: 24.0), - child: TextFormField( - initialValue: initialLatLng.longitude.toString(), - decoration: const InputDecoration(labelText: 'Longitude'), - keyboardType: TextInputType.number, - onChanged: (String value) { - onChanged( - LatLng( - latitude: initialLatLng.latitude, - longitude: double.parse(value), - ), - ); - }, + Padding( + padding: const EdgeInsetsDirectional.only(start: 16.0, end: 24.0), + child: TextFormField( + initialValue: initialLatLng.longitude.toString(), + decoration: const InputDecoration(labelText: 'Longitude'), + keyboardType: TextInputType.number, + onChanged: (String value) { + onChanged( + LatLng( + latitude: initialLatLng.latitude, + longitude: double.parse(value), + ), + ); + }, + ), ), - ), - ]); + ], + ); } } @@ -155,9 +157,7 @@ class ExampleLatLngSlideEditorState extends State { setState(() { latitude = newValue; }); - widget.onChanged( - LatLng(latitude: newValue, longitude: longitude), - ); + widget.onChanged(LatLng(latitude: newValue, longitude: longitude)); }, title: 'Latitude', min: -90, @@ -169,9 +169,7 @@ class ExampleLatLngSlideEditorState extends State { setState(() { longitude = newValue; }); - widget.onChanged( - LatLng(latitude: latitude, longitude: newValue), - ); + widget.onChanged(LatLng(latitude: latitude, longitude: newValue)); }, title: 'Longitude', min: -180, diff --git a/example/lib/widgets/page.dart b/example/lib/widgets/page.dart index 0725e72..9664e60 100644 --- a/example/lib/widgets/page.dart +++ b/example/lib/widgets/page.dart @@ -52,10 +52,7 @@ abstract class ExamplePageState extends State _overlayOffsetAnimation = Tween( begin: const Offset(0.0, 1.0), end: Offset.zero, - ).animate(CurvedAnimation( - parent: _controller, - curve: Curves.easeInOut, - )); + ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeInOut)); } /// Toggles overlay visibility. @@ -98,12 +95,7 @@ abstract class ExamplePageState extends State Widget buildPage(BuildContext context, Widget child) { return Stack( children: [ - Scaffold( - appBar: AppBar( - title: Text(widget.title), - ), - body: child, - ), + Scaffold(appBar: AppBar(title: Text(widget.title)), body: child), if (_isOverlayVisible) _buildOverlay(), ], ); @@ -114,11 +106,17 @@ abstract class ExamplePageState extends State children: [ // Overlay background, which is used to close overlay when tapped. GestureDetector( - onTap: hideOverlay, - child: AnimatedBuilder( - animation: _controller, - builder: (BuildContext context, Widget? child) => Container( - color: Colors.black.withOpacity(_controller.value * 0.5)))), + onTap: hideOverlay, + child: AnimatedBuilder( + animation: _controller, + builder: + (BuildContext context, Widget? child) => Container( + color: Colors.black.withValues( + alpha: _controller.value * 0.5, + ), + ), + ), + ), // Overlay content SlideTransition( position: _overlayOffsetAnimation, @@ -133,8 +131,9 @@ abstract class ExamplePageState extends State color: Theme.of(context).cardColor, elevation: 4, borderRadius: const BorderRadius.only( - topLeft: Radius.circular(16), - topRight: Radius.circular(16)), + topLeft: Radius.circular(16), + topRight: Radius.circular(16), + ), child: Column( mainAxisSize: MainAxisSize.min, children: [ @@ -152,11 +151,15 @@ abstract class ExamplePageState extends State // Container for overlay content Container( constraints: BoxConstraints( - maxHeight: MediaQuery.of(context).size.height * 0.6), + maxHeight: MediaQuery.of(context).size.height * 0.6, + ), child: SafeArea( top: false, minimum: const EdgeInsets.only( - left: 8, right: 8, bottom: 16), + left: 8, + right: 8, + bottom: 16, + ), // Make content scrollable child: Scrollbar( thumbVisibility: true, @@ -172,41 +175,46 @@ abstract class ExamplePageState extends State ), ), ), - ) + ), ], ); } /// Helper method to show message overlay. - void showOverlaySnackBar(String message, - {Alignment alignment = Alignment.bottomCenter}) { + void showOverlaySnackBar( + String message, { + Alignment alignment = Alignment.bottomCenter, + }) { final OverlayState overlay = Overlay.of(context); final OverlayEntry overlayEntry = OverlayEntry( - builder: (BuildContext context) => Align( - alignment: alignment, - child: SizedBox( - width: double.infinity, - child: Material( - elevation: 10.0, - child: Container( - padding: const EdgeInsets.all(16), - color: Theme.of(context).snackBarTheme.backgroundColor, - child: SafeArea( - child: Text( - message, - style: Theme.of(context).snackBarTheme.contentTextStyle, - )), + builder: + (BuildContext context) => Align( + alignment: alignment, + child: SizedBox( + width: double.infinity, + child: Material( + elevation: 10.0, + child: Container( + padding: const EdgeInsets.all(16), + color: Theme.of(context).snackBarTheme.backgroundColor, + child: SafeArea( + child: Text( + message, + style: Theme.of(context).snackBarTheme.contentTextStyle, + ), + ), + ), + ), ), ), - ), - ), ); overlay.insert(overlayEntry); // Automatically remove the snack bar after some duration - Future.delayed(const Duration(seconds: 3)) - .then((_) => overlayEntry.remove()); + Future.delayed( + const Duration(seconds: 3), + ).then((_) => overlayEntry.remove()); } @override diff --git a/example/lib/widgets/slider_editor.dart b/example/lib/widgets/slider_editor.dart index 146e647..c897b14 100644 --- a/example/lib/widgets/slider_editor.dart +++ b/example/lib/widgets/slider_editor.dart @@ -43,16 +43,18 @@ class ExampleSlider extends StatelessWidget { children: [ ListTile( title: Text(title), - trailing: - Text(value.toStringAsFixed(fractionDigits ?? 1) + (unit ?? '')), + trailing: Text( + value.toStringAsFixed(fractionDigits ?? 1) + (unit ?? ''), + ), ), Slider( value: value, - onChanged: onChanged == null - ? null - : (double newValue) { - onChanged!(newValue); - }, + onChanged: + onChanged == null + ? null + : (double newValue) { + onChanged!(newValue); + }, min: min, max: max, ), diff --git a/example/pubspec.yaml b/example/pubspec.yaml index 564868c..8e28aad 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -17,25 +17,27 @@ description: Demonstrates how to use the google_driver_flutter plugin. publish_to: "none" environment: - sdk: ^3.4.0 + sdk: ^3.7.0 dependencies: - cupertino_icons: ^1.0.2 + cupertino_icons: ^1.0.8 flutter: sdk: flutter google_driver_flutter: path: ../ + google_navigation_flutter: ^0.6.2 http: ^1.1.2 - permission_handler: ^11.1.0 + permission_handler: ^11.3.1 dev_dependencies: - flutter_lints: ^3.0.1 + flutter_lints: ^5.0.0 flutter_test: sdk: flutter integration_test: sdk: flutter - patrol: ^3.7.2 + patrol: 3.16.0 pub_semver: ^2.1.4 + test_api: any flutter: uses-material-design: true diff --git a/example/tools/backend/LMFS/Dockerfile b/example/tools/backend/LMFS/Dockerfile index 8e42215..cb0790a 100644 --- a/example/tools/backend/LMFS/Dockerfile +++ b/example/tools/backend/LMFS/Dockerfile @@ -13,11 +13,11 @@ # limitations under the License. # Use an appropriate Java base image -FROM openjdk:11 +FROM openjdk:17-jdk-slim # Install git RUN apt-get update && \ - apt-get install -y git && \ + apt-get install -y git python3 && \ rm -rf /var/lib/apt/lists/* # Accept build arguments for the git hash @@ -35,14 +35,9 @@ RUN git init && \ # Move to the backend directory WORKDIR /lmfs-backend/backend -# Append the force gRPC versions to the build.gradle file -RUN echo '\nconfigurations.all {\n\ - resolutionStrategy {\n\ - force '\''io.grpc:grpc-stub:1.55.1'\''\n\ - force '\''io.grpc:grpc-protobuf:1.55.1'\''\n\ - force '\''io.grpc:grpc-netty:1.55.1'\''\n\ - }\n\ -}' >> build.gradle +# Fix grpc dependency issues +RUN sed -i 's/io\.grpc:grpc-netty:\([0-9.]\+\)/io.grpc:grpc-netty-shaded:\1/' build.gradle +RUN sed -i '/io\.grpc:grpc-netty-shaded/ a\ \ implementation '\''io.grpc:grpc-core:1.66.0'\''' build.gradle # Precompile the backend and download the Google Cloud SDK RUN ./gradlew compileJava war downloadCloudSdk @@ -73,5 +68,7 @@ RUN sed -i "s/\*\*\*\*\*UPDATE_WITH_PROJECT_ID\*\*\*\*\*/${PROJECT_ID}/g" src/ma # Expose the port the backend runs on EXPOSE 8080 +RUN ./gradlew dependencies > dependencies.txt && echo "--- Gradle Dependency Tree ---" && cat dependencies.txt && echo "--- End of Dependency Tree ---" + # Command to start the backend with App Engine CMD ["./gradlew", "appengineRun"] diff --git a/example/tools/backend/ODRD/Dockerfile b/example/tools/backend/ODRD/Dockerfile index 56f70bc..416f0de 100644 --- a/example/tools/backend/ODRD/Dockerfile +++ b/example/tools/backend/ODRD/Dockerfile @@ -13,11 +13,11 @@ # limitations under the License. # Use an appropriate Java base image -FROM openjdk:11 +FROM openjdk:17-jdk-slim # Install git RUN apt-get update && \ - apt-get install -y git && \ + apt-get install -y git python3 && \ rm -rf /var/lib/apt/lists/* # Create a directory for the backend diff --git a/example/tools/backend/docker-compose.yml b/example/tools/backend/docker-compose.yml index 03a4295..b4b0f70 100644 --- a/example/tools/backend/docker-compose.yml +++ b/example/tools/backend/docker-compose.yml @@ -26,7 +26,7 @@ services: FLEET_READER_SERVICE_ACCOUNT_EMAIL: ${FLEET_READER_SERVICE_ACCOUNT_EMAIL} JS_API_KEY: ${JS_API_KEY} HOST: http://localhost:8091 - GIT_HASH: dff5045208bb687337ca2e27e2060ff0b2c7826e + GIT_HASH: 70246d5b9af68eba49d091dc4bbf4557683072ef command: ["./gradlew", "appengineRun", "--stacktrace"] ports: - "8091:8080" @@ -42,7 +42,7 @@ services: SERVER_SERVICE_ACCOUNT_EMAIL: ${SERVER_SERVICE_ACCOUNT_EMAIL} DRIVER_SERVICE_ACCOUNT_EMAIL: ${DRIVER_SERVICE_ACCOUNT_EMAIL} CONSUMER_SERVICE_ACCOUNT_EMAIL: ${CONSUMER_SERVICE_ACCOUNT_EMAIL} - GIT_HASH: 9ae34af34a0abc51e1139ce2a4fc7e0d30f368b2 + GIT_HASH: 4e60f77a46b0affd7b8e3f7355f1c60faf8699b1 command: ["./gradlew", "appengineRun", "--stacktrace"] ports: - "8092:8080" diff --git a/ios/Classes/AccessTokenProvider.swift b/ios/Classes/AccessTokenProvider.swift index 7bd9764..1722146 100644 --- a/ios/Classes/AccessTokenProvider.swift +++ b/ios/Classes/AccessTokenProvider.swift @@ -30,10 +30,14 @@ class AccessTokenProvider: NSObject, GMTDAuthorization, ObservableObject { _authTokenEventApi = AuthTokenEventApi(binaryMessenger: messenger) } - func fetchToken(with authorizationContext: GMTDAuthorizationContext?, - completion: @escaping GMTDAuthTokenFetchCompletionHandler) { - _authTokenEventApi.getToken(taskId: authorizationContext?.taskID ?? nil, - vehicleId: authorizationContext?.vehicleID ?? nil) { result in + func fetchToken( + with authorizationContext: GMTDAuthorizationContext?, + completion: @escaping GMTDAuthTokenFetchCompletionHandler + ) { + _authTokenEventApi.getToken( + taskId: authorizationContext?.taskID ?? nil, + vehicleId: authorizationContext?.vehicleID ?? nil + ) { result in switch result { case let .success(data): completion(data, nil) @@ -41,8 +45,10 @@ class AccessTokenProvider: NSObject, GMTDAuthorization, ObservableObject { let nsError = NSError( domain: "com.google.mapsplatform.transportation.driver.vehiclereporter.ErrorDomain", code: 0, - userInfo: [NSLocalizedDescriptionKey: error - .message ?? "Token retrieval from the backend failed."] + userInfo: [ + NSLocalizedDescriptionKey: error + .message ?? "Token retrieval from the backend failed." + ] ) completion(nil, nsError) } diff --git a/ios/Classes/Convert.swift b/ios/Classes/Convert.swift index d2b3987..01616ee 100644 --- a/ios/Classes/Convert.swift +++ b/ios/Classes/Convert.swift @@ -36,7 +36,8 @@ enum Convert { // This conversion functions has been duplicated from // google_navigation_flutter. Keep in sync. static func convertNavigationWayPointToDto(_ gmsNavigationWaypoint: GMSNavigationWaypoint?) - -> NavigationWaypointDto? { + -> NavigationWaypointDto? + { guard let gmsNavigationWaypoint else { return nil } return NavigationWaypointDto( title: gmsNavigationWaypoint.title, @@ -53,7 +54,8 @@ enum Convert { // This conversion functions has been duplicated from // google_navigation_flutter. Keep in sync. static func convertNavigationWayPointFromDto(_ waypoint: NavigationWaypointDto?) - -> GMSNavigationWaypoint? { + -> GMSNavigationWaypoint? + { guard let waypoint else { return nil } if let latitude = waypoint.target?.latitude, let longitude = waypoint.target?.longitude { if let preferSameSideOfRoad = waypoint.preferSameSideOfRoad { @@ -90,7 +92,8 @@ enum Convert { // This conversion functions has been duplicated from // google_navigation_flutter. Keep in sync. static func convertWaypoints(_ waypoints: [NavigationWaypointDto?]) - -> [GMSNavigationWaypoint] { + -> [GMSNavigationWaypoint] + { waypoints .map { waypoint -> GMSNavigationWaypoint? in guard let waypoint else { return nil } @@ -99,19 +102,20 @@ enum Convert { .compactMap { $0 } } - // Converts Pigeon [TaskInfoDto] to Google Driver [GMTSTaskInfo]. - static func convertTaskInfoFromDto(task: TaskInfoDto) -> GMTSTaskInfo { - GMTSTaskInfo(taskID: task.taskId, taskDuration: TimeInterval(task.durationSeconds)) + // Converts Pigeon [TaskInfoDto] to Google Driver [GMTDTaskInfo]. + static func convertTaskInfoFromDto(task: TaskInfoDto) -> GMTDTaskInfo { + GMTDTaskInfo(taskID: task.taskId, taskDuration: TimeInterval(task.durationSeconds)) } - // Converts Google Driver [GMTSTaskInfo] to Pigeon [TaskInfoDto]. - static func convertTaskInfoToDto(task: GMTSTaskInfo) -> TaskInfoDto { + // Converts Google Driver [GMTDTaskInfo] to Pigeon [TaskInfoDto]. + static func convertTaskInfoToDto(task: GMTDTaskInfo) -> TaskInfoDto { TaskInfoDto(taskId: task.taskID, durationSeconds: Int64(task.taskDuration)) } // Converts pigeon [VehicleStopStateDto] to Google Drive [Int]. static func convertVehicleStopStateFromDto(vehicleStopState: VehicleStopStateDto) - -> GMTDVehicleStopState { + -> GMTDVehicleStopState + { switch vehicleStopState { case VehicleStopStateDto.stateUnspecified: return .unspecified @@ -126,7 +130,8 @@ enum Convert { // Converts Google Drive [Int] to pigeon [VehicleStopStateDto]. static func convertVehicleStopStateToDto(googleVehicleStopState: GMTDVehicleStopState) - -> VehicleStopStateDto { + -> VehicleStopStateDto + { switch googleVehicleStopState { case .unspecified: return VehicleStopStateDto.stateUnspecified @@ -154,19 +159,21 @@ enum Convert { // Converts Google Driver [GMTDVehicleStop] to Pigeon [VehicleStopDto]. static func convertVehicleStopFromDto(stop: VehicleStopDto) -> GMTDVehicleStop { - GMTDVehicleStop(taskInfoArray: stop.taskInfoList.map { taskInfo -> GMTSTaskInfo? in - guard let taskInfo else { return nil } + GMTDVehicleStop( + taskInfoArray: stop.taskInfoList.map { taskInfo -> GMTDTaskInfo? in + guard let taskInfo else { return nil } - return convertTaskInfoFromDto(task: taskInfo) - }.compactMap { $0 }, plannedWaypoint: convertNavigationWayPointFromDto(stop.waypoint), - state: convertVehicleStopStateFromDto( - vehicleStopState: stop.vehicleStopState - )) + return convertTaskInfoFromDto(task: taskInfo) + }.compactMap { $0 }, plannedWaypoint: convertNavigationWayPointFromDto(stop.waypoint), + state: convertVehicleStopStateFromDto( + vehicleStopState: stop.vehicleStopState + )) } // Converts Pigeon [VehicleStateDto] to Google Driver [GMTDVehicleState]. static func convertVehicleStateFromDto(state: VehicleStateDto) - -> GMTDVehicleState { + -> GMTDVehicleState + { switch state { case .offline: return GMTDVehicleState.offline @@ -177,7 +184,8 @@ enum Convert { // Converts Google Driver [GMTDVehicleState] to Pigeon [VehicleStateDto]. static func convertVehicleStateToDto(state: GMTDVehicleState) - -> VehicleStateDto { + -> VehicleStateDto + { switch state { case .offline: return VehicleStateDto.offline @@ -189,16 +197,19 @@ enum Convert { } } - static func convertVehicleUpdateToDto(vehicleUpdate: GMTDVehicleUpdate, - ridesharing: Bool) -> VehicleUpdateDto { + static func convertVehicleUpdateToDto( + vehicleUpdate: GMTDVehicleUpdate, + ridesharing: Bool + ) -> VehicleUpdateDto { VehicleUpdateDto( - vehicleState: ridesharing ? - convertVehicleStateToDto(state: vehicleUpdate.vehicleState) + vehicleState: ridesharing + ? convertVehicleStateToDto(state: vehicleUpdate.vehicleState) : nil, location: vehicleUpdate .location != nil ? convertLatLngToDto(point: vehicleUpdate.location!.coordinate) : nil, destinationWaypoint: convertNavigationWayPointToDto(vehicleUpdate.destinationWaypoint), - route: (vehicleUpdate.route ?? []).map { convertLatLngToDto(point: $0.coordinate) + route: (vehicleUpdate.route ?? []).map { + convertLatLngToDto(point: $0.coordinate) }, remainingTimeInSeconds: vehicleUpdate.remainingTimeInSeconds?.doubleValue, remainingDistanceInMeters: vehicleUpdate.remainingDistanceInMeters?.doubleValue @@ -228,7 +239,8 @@ enum Convert { } static func convertDeliveryVehicleToDto(deliveryVehicle: GMTDDeliveryVehicle) - -> DeliveryVehicleDto { + -> DeliveryVehicleDto + { DeliveryVehicleDto( providerId: deliveryVehicle.providerID, id: deliveryVehicle.vehicleID, diff --git a/ios/Classes/GoogleMapsBaseDriver.swift b/ios/Classes/GoogleMapsBaseDriver.swift index 693df6c..116fb97 100644 --- a/ios/Classes/GoogleMapsBaseDriver.swift +++ b/ios/Classes/GoogleMapsBaseDriver.swift @@ -13,8 +13,8 @@ // limitations under the License. import Flutter -import google_navigation_flutter import GoogleRidesharingDriver +import google_navigation_flutter class GoogleMapsBaseDriver { var _accessTokenProvider: AccessTokenProvider @@ -29,8 +29,10 @@ class GoogleMapsBaseDriver { fatalError("Method must be overridden") } - func initialize(providerId: String, vehicleId: String, - abnormalTerminationReportingEnabled: Bool) throws { + func initialize( + providerId: String, vehicleId: String, + abnormalTerminationReportingEnabled: Bool + ) throws { fatalError("Method must be overridden") } diff --git a/ios/Classes/GoogleMapsCommonApiHandler.swift b/ios/Classes/GoogleMapsCommonApiHandler.swift index db51f96..f56d46f 100644 --- a/ios/Classes/GoogleMapsCommonApiHandler.swift +++ b/ios/Classes/GoogleMapsCommonApiHandler.swift @@ -32,8 +32,10 @@ class GoogleMapsCommonApiHandler: CommonDriverApi { private let _deliveryDriverApi: GoogleMapsDeliveryDriver private let _ridesharingDriverApi: GoogleMapsRidesharingDriver - init(messenger: FlutterBinaryMessenger, deliveryDriverApi: GoogleMapsDeliveryDriver, - ridesharingDriverApi: GoogleMapsRidesharingDriver) { + init( + messenger: FlutterBinaryMessenger, deliveryDriverApi: GoogleMapsDeliveryDriver, + ridesharingDriverApi: GoogleMapsRidesharingDriver + ) { _deliveryDriverApi = deliveryDriverApi _ridesharingDriverApi = ridesharingDriverApi CommonDriverApiSetup.setUp(binaryMessenger: messenger, api: self) @@ -48,8 +50,10 @@ class GoogleMapsCommonApiHandler: CommonDriverApi { } } - func initialize(type: DriverApiTypeDto, providerId: String, vehicleId: String, - abnormalTerminationReportingEnabled: Bool) throws { + func initialize( + type: DriverApiTypeDto, providerId: String, vehicleId: String, + abnormalTerminationReportingEnabled: Bool + ) throws { if try _deliveryDriverApi.isInitialized() { throw GoogleMapsDriverError.apiAlreadyInitialized } diff --git a/ios/Classes/GoogleMapsDeliveryDriver.swift b/ios/Classes/GoogleMapsDeliveryDriver.swift index 717c797..dbd873d 100644 --- a/ios/Classes/GoogleMapsDeliveryDriver.swift +++ b/ios/Classes/GoogleMapsDeliveryDriver.swift @@ -14,8 +14,8 @@ import Flutter import Foundation -import google_navigation_flutter import GoogleRidesharingDriver +import google_navigation_flutter // Keep in sync with GoogleMapsNavigationSessionManager.kt enum GoogleMapsDeliveryDriverError: Error { @@ -25,6 +25,8 @@ enum GoogleMapsDeliveryDriverError: Error { case noRoadSnappedLocationProvider } +extension FlutterError: Error {} + func convertError(_ error: Error) -> FlutterError { let fullError = error as NSError @@ -56,8 +58,10 @@ class GoogleMapsDeliveryDriver: GoogleMapsBaseDriver, DeliveryDriverApi { } } - override func initialize(providerId: String, vehicleId: String, - abnormalTerminationReportingEnabled: Bool) throws { + override func initialize( + providerId: String, vehicleId: String, + abnormalTerminationReportingEnabled: Bool + ) throws { let navigator = try ExposedGoogleMapsNavigator.getNavigator() GMSNavigationServices.createNavigationSession() @@ -73,8 +77,10 @@ class GoogleMapsDeliveryDriver: GoogleMapsBaseDriver, DeliveryDriverApi { // Should not fail since the ExposedGoogleMapsNavigator.getNavigator() few // lines above should have thrown sessionNotInitialized already. - if let _roadSnappedLocationProvider = try ExposedGoogleMapsNavigator - .getRoadSnappedLocationProvider() { + if let _roadSnappedLocationProvider = + try ExposedGoogleMapsNavigator + .getRoadSnappedLocationProvider() + { if let vehicleReporter = _deliveryDriverAPI?.vehicleReporter { _roadSnappedLocationProvider.add(vehicleReporter) } else { @@ -110,11 +116,12 @@ class GoogleMapsDeliveryDriver: GoogleMapsBaseDriver, DeliveryDriverApi { if _deliveryDriverAPI != nil { _deliveryDriverAPI?.vehicleReporter.reportEnrouteToNextStop(completion: { stops, error in if error == nil { - completion(.success( - (stops ?? []).map { stop -> VehicleStopDto in - Convert.convertVehicleStopToDto(stop: stop) - } - )) + completion( + .success( + (stops ?? []).map { stop -> VehicleStopDto in + Convert.convertVehicleStopToDto(stop: stop) + } + )) } else { completion(.failure(convertError(error!))) } @@ -128,11 +135,12 @@ class GoogleMapsDeliveryDriver: GoogleMapsBaseDriver, DeliveryDriverApi { if _deliveryDriverAPI != nil { _deliveryDriverAPI?.vehicleReporter.reportArrivedAtStop(completion: { stops, error in if error == nil { - completion(.success( - (stops ?? []).map { stop -> VehicleStopDto in - Convert.convertVehicleStopToDto(stop: stop) - } - )) + completion( + .success( + (stops ?? []).map { stop -> VehicleStopDto in + Convert.convertVehicleStopToDto(stop: stop) + } + )) } else { completion(.failure(convertError(error!))) } @@ -146,11 +154,12 @@ class GoogleMapsDeliveryDriver: GoogleMapsBaseDriver, DeliveryDriverApi { if _deliveryDriverAPI != nil { _deliveryDriverAPI?.vehicleReporter.reportCompletedStop(completion: { stops, error in if error == nil { - completion(.success( - (stops ?? []).map { stop -> VehicleStopDto in - Convert.convertVehicleStopToDto(stop: stop) - } - )) + completion( + .success( + (stops ?? []).map { stop -> VehicleStopDto in + Convert.convertVehicleStopToDto(stop: stop) + } + )) } else { completion(.failure(convertError(error!))) } @@ -164,11 +173,12 @@ class GoogleMapsDeliveryDriver: GoogleMapsBaseDriver, DeliveryDriverApi { if _deliveryDriverAPI != nil { _deliveryDriverAPI?.vehicleReporter.getRemainingVehicleStops(completion: { stops, error in if error == nil { - completion(.success( - (stops ?? []).map { stop -> VehicleStopDto in - Convert.convertVehicleStopToDto(stop: stop) - } - )) + completion( + .success( + (stops ?? []).map { stop -> VehicleStopDto in + Convert.convertVehicleStopToDto(stop: stop) + } + )) } else { completion(.failure(convertError(error!))) } @@ -178,31 +188,35 @@ class GoogleMapsDeliveryDriver: GoogleMapsBaseDriver, DeliveryDriverApi { } } - func setVehicleStops(stops: [VehicleStopDto], - completion: @escaping (Result<[VehicleStopDto], Error>) -> Void) { + func setVehicleStops( + stops: [VehicleStopDto], + completion: @escaping (Result<[VehicleStopDto], Error>) -> Void + ) { if _deliveryDriverAPI != nil { let vehicleStops: [GMTDVehicleStop] = stops.map { stop -> GMTDVehicleStop in Convert.convertVehicleStopFromDto(stop: stop) } - _deliveryDriverAPI?.vehicleReporter.setVehicleStops(vehicleStops, - completion: { stops, error in - if error == nil { - completion(.success( - (stops ?? []) - .map { stop -> VehicleStopDto in - Convert - .convertVehicleStopToDto( - stop: stop - ) - } - )) - } else { - completion( - .failure(convertError(error!)) - ) - } - }) + _deliveryDriverAPI?.vehicleReporter.setVehicleStops( + vehicleStops, + completion: { stops, error in + if error == nil { + completion( + .success( + (stops ?? []) + .map { stop -> VehicleStopDto in + Convert + .convertVehicleStopToDto( + stop: stop + ) + } + )) + } else { + completion( + .failure(convertError(error!)) + ) + } + }) } else { completion(.failure(GoogleMapsDeliveryDriverError.driverNotInitialized)) @@ -214,8 +228,10 @@ class GoogleMapsDeliveryDriver: GoogleMapsBaseDriver, DeliveryDriverApi { _deliveryDriverAPI!.deliveryVehicleManager! .getVehicleWithCompletion { deliveryVehicle, error in if error == nil { - completion(.success(Convert - .convertDeliveryVehicleToDto(deliveryVehicle: deliveryVehicle!))) + completion( + .success( + Convert + .convertDeliveryVehicleToDto(deliveryVehicle: deliveryVehicle!))) } else { completion(.failure(convertError(error!))) } diff --git a/ios/Classes/GoogleMapsRidesharingDriver.swift b/ios/Classes/GoogleMapsRidesharingDriver.swift index c1d2dfb..6e46e94 100644 --- a/ios/Classes/GoogleMapsRidesharingDriver.swift +++ b/ios/Classes/GoogleMapsRidesharingDriver.swift @@ -14,8 +14,8 @@ import Flutter import Foundation -import google_navigation_flutter import GoogleRidesharingDriver +import google_navigation_flutter // Keep in sync with GoogleMapsNavigationSessionManager.kt enum GoogleMapsRidesharingDriverError: Error { @@ -43,8 +43,10 @@ class GoogleMapsRidesharingDriver: GoogleMapsBaseDriver, RidesharingDriverApi { } } - override func initialize(providerId: String, vehicleId: String, - abnormalTerminationReportingEnabled: Bool) throws { + override func initialize( + providerId: String, vehicleId: String, + abnormalTerminationReportingEnabled: Bool + ) throws { let navigator = try ExposedGoogleMapsNavigator.getNavigator() GMSNavigationServices.createNavigationSession() @@ -59,8 +61,10 @@ class GoogleMapsRidesharingDriver: GoogleMapsBaseDriver, RidesharingDriverApi { // Should not fail since the ExposedGoogleMapsNavigator.getNavigator() few // lines above should have thrown sessionNotInitialized already. - if let _roadSnappedLocationProvider = try ExposedGoogleMapsNavigator - .getRoadSnappedLocationProvider() { + if let _roadSnappedLocationProvider = + try ExposedGoogleMapsNavigator + .getRoadSnappedLocationProvider() + { if let vehicleReporter = _ridesharingDriverAPI?.vehicleReporter { _roadSnappedLocationProvider.add(vehicleReporter) } else { diff --git a/ios/Classes/VehicleReporterListener.swift b/ios/Classes/VehicleReporterListener.swift index 83cc20a..09e2855 100644 --- a/ios/Classes/VehicleReporterListener.swift +++ b/ios/Classes/VehicleReporterListener.swift @@ -25,21 +25,28 @@ class VehicleReporterListener: NSObject, GMTDVehicleReporterListener { _ridesharing = ridesharing } - func vehicleReporter(_ vehicleReporter: GMTDVehicleReporter, - didSucceed vehicleUpdate: GMTDVehicleUpdate) { + func vehicleReporter( + _ vehicleReporter: GMTDVehicleReporter, + didSucceed vehicleUpdate: GMTDVehicleUpdate + ) { if _listenerApi != nil { _listenerApi? - .onDidSucceed(vehicleUpdate: Convert - .convertVehicleUpdateToDto( - vehicleUpdate: vehicleUpdate, - ridesharing: _ridesharing - )) { error in } + .onDidSucceed( + vehicleUpdate: + Convert + .convertVehicleUpdateToDto( + vehicleUpdate: vehicleUpdate, + ridesharing: _ridesharing + ) + ) { error in } } } - func vehicleReporter(_ vehicleReporter: GMTDVehicleReporter, - didFail vehicleUpdate: GMTDVehicleUpdate, - withError error: Error) { + func vehicleReporter( + _ vehicleReporter: GMTDVehicleReporter, + didFail vehicleUpdate: GMTDVehicleUpdate, + withError error: Error + ) { if _listenerApi != nil { // Top-level error always has error code 1 and message "Vehicle update failed.", // pass child error that describes the actual issue instead if available. diff --git a/ios/Classes/messages.g.swift b/ios/Classes/messages.g.swift index 2033857..f2157ff 100644 --- a/ios/Classes/messages.g.swift +++ b/ios/Classes/messages.g.swift @@ -12,10 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. // -// Autogenerated from Pigeon (v15.0.0), do not edit directly. +// Autogenerated from Pigeon (v25.3.2), do not edit directly. // See also: https://pub.dev/packages/pigeon import Foundation + #if os(iOS) import Flutter #elseif os(macOS) @@ -24,11 +25,36 @@ import Foundation #error("Unsupported platform.") #endif +/// Error class for passing custom error details to Dart side. +final class PigeonError: Error { + let code: String + let message: String? + let details: Sendable? + + init(code: String, message: String?, details: Sendable?) { + self.code = code + self.message = message + self.details = details + } + + var localizedDescription: String { + return + "PigeonError(code: \(code), message: \(message ?? ""), details: \(details ?? "")" + } +} + private func wrapResult(_ result: Any?) -> [Any?] { - [result] + return [result] } private func wrapError(_ error: Any) -> [Any?] { + if let pigeonError = error as? PigeonError { + return [ + pigeonError.code, + pigeonError.message, + pigeonError.details, + ] + } if let flutterError = error as? FlutterError { return [ flutterError.code, @@ -43,16 +69,14 @@ private func wrapError(_ error: Any) -> [Any?] { ] } -private func createConnectionError(withChannelName channelName: String) -> FlutterError { - FlutterError( - code: "channel-error", - message: "Unable to establish connection on channel: '\(channelName)'.", - details: "" - ) +private func createConnectionError(withChannelName channelName: String) -> PigeonError { + return PigeonError( + code: "channel-error", message: "Unable to establish connection on channel: '\(channelName)'.", + details: "") } private func isNullish(_ value: Any?) -> Bool { - value is NSNull || value == nil + return value is NSNull || value == nil } private func nilOrValue(_ value: Any?) -> T? { @@ -60,6 +84,68 @@ private func nilOrValue(_ value: Any?) -> T? { return value as! T? } +func deepEqualsmessages(_ lhs: Any?, _ rhs: Any?) -> Bool { + let cleanLhs = nilOrValue(lhs) as Any? + let cleanRhs = nilOrValue(rhs) as Any? + switch (cleanLhs, cleanRhs) { + case (nil, nil): + return true + + case (nil, _), (_, nil): + return false + + case is (Void, Void): + return true + + case let (cleanLhsHashable, cleanRhsHashable) as (AnyHashable, AnyHashable): + return cleanLhsHashable == cleanRhsHashable + + case let (cleanLhsArray, cleanRhsArray) as ([Any?], [Any?]): + guard cleanLhsArray.count == cleanRhsArray.count else { return false } + for (index, element) in cleanLhsArray.enumerated() { + if !deepEqualsmessages(element, cleanRhsArray[index]) { + return false + } + } + return true + + case let (cleanLhsDictionary, cleanRhsDictionary) as ([AnyHashable: Any?], [AnyHashable: Any?]): + guard cleanLhsDictionary.count == cleanRhsDictionary.count else { return false } + for (key, cleanLhsValue) in cleanLhsDictionary { + guard cleanRhsDictionary.index(forKey: key) != nil else { return false } + if !deepEqualsmessages(cleanLhsValue, cleanRhsDictionary[key]!) { + return false + } + } + return true + + default: + // Any other type shouldn't be able to be used with pigeon. File an issue if you find this to be untrue. + return false + } +} + +func deepHashmessages(value: Any?, hasher: inout Hasher) { + if let valueList = value as? [AnyHashable] { + for item in valueList { deepHashmessages(value: item, hasher: &hasher) } + return + } + + if let valueDict = value as? [AnyHashable: AnyHashable] { + for key in valueDict.keys { + hasher.combine(key) + deepHashmessages(value: valueDict[key]!, hasher: &hasher) + } + return + } + + if let hashableValue = value as? AnyHashable { + hasher.combine(hashableValue.hashValue) + } + + return hasher.combine(String(describing: value)) +} + /// Indicates the API type for a driver. enum DriverApiTypeDto: Int { /// Indicates the API is for a delivery driver. @@ -101,41 +187,45 @@ enum DriverStatusCodeDto: Int { } /// Generated class from Pigeon that represents data sent in messages. -struct TaskInfoDto { +struct TaskInfoDto: Hashable { var taskId: String var durationSeconds: Int64 - static func fromList(_ list: [Any?]) -> TaskInfoDto? { - let taskId = list[0] as! String - let durationSeconds = list[1] is Int64 ? list[1] as! Int64 : Int64(list[1] as! Int32) + // swift-format-ignore: AlwaysUseLowerCamelCase + static func fromList(_ pigeonVar_list: [Any?]) -> TaskInfoDto? { + let taskId = pigeonVar_list[0] as! String + let durationSeconds = pigeonVar_list[1] as! Int64 return TaskInfoDto( taskId: taskId, durationSeconds: durationSeconds ) } - func toList() -> [Any?] { - [ + return [ taskId, durationSeconds, ] } + static func == (lhs: TaskInfoDto, rhs: TaskInfoDto) -> Bool { + return deepEqualsmessages(lhs.toList(), rhs.toList()) + } + func hash(into hasher: inout Hasher) { + deepHashmessages(value: toList(), hasher: &hasher) + } } /// Generated class from Pigeon that represents data sent in messages. -struct VehicleStopDto { +struct VehicleStopDto: Hashable { var vehicleStopState: VehicleStopStateDto - var waypoint: NavigationWaypointDto? + var waypoint: NavigationWaypointDto? = nil var taskInfoList: [TaskInfoDto?] - static func fromList(_ list: [Any?]) -> VehicleStopDto? { - let vehicleStopState = VehicleStopStateDto(rawValue: list[0] as! Int)! - var waypoint: NavigationWaypointDto? - if let waypointList: [Any?] = nilOrValue(list[1]) { - waypoint = NavigationWaypointDto.fromList(waypointList) - } - let taskInfoList = list[2] as! [TaskInfoDto?] + // swift-format-ignore: AlwaysUseLowerCamelCase + static func fromList(_ pigeonVar_list: [Any?]) -> VehicleStopDto? { + let vehicleStopState = pigeonVar_list[0] as! VehicleStopStateDto + let waypoint: NavigationWaypointDto? = nilOrValue(pigeonVar_list[1]) + let taskInfoList = pigeonVar_list[2] as! [TaskInfoDto?] return VehicleStopDto( vehicleStopState: vehicleStopState, @@ -143,57 +233,65 @@ struct VehicleStopDto { taskInfoList: taskInfoList ) } - func toList() -> [Any?] { - [ - vehicleStopState.rawValue, - waypoint?.toList(), + return [ + vehicleStopState, + waypoint, taskInfoList, ] } + static func == (lhs: VehicleStopDto, rhs: VehicleStopDto) -> Bool { + return deepEqualsmessages(lhs.toList(), rhs.toList()) + } + func hash(into hasher: inout Hasher) { + deepHashmessages(value: toList(), hasher: &hasher) + } } /// Generated class from Pigeon that represents data sent in messages. -struct LatLngDto { +struct LatLngDto: Hashable { var latitude: Double var longitude: Double - static func fromList(_ list: [Any?]) -> LatLngDto? { - let latitude = list[0] as! Double - let longitude = list[1] as! Double + // swift-format-ignore: AlwaysUseLowerCamelCase + static func fromList(_ pigeonVar_list: [Any?]) -> LatLngDto? { + let latitude = pigeonVar_list[0] as! Double + let longitude = pigeonVar_list[1] as! Double return LatLngDto( latitude: latitude, longitude: longitude ) } - func toList() -> [Any?] { - [ + return [ latitude, longitude, ] } + static func == (lhs: LatLngDto, rhs: LatLngDto) -> Bool { + return deepEqualsmessages(lhs.toList(), rhs.toList()) + } + func hash(into hasher: inout Hasher) { + deepHashmessages(value: toList(), hasher: &hasher) + } } /// Generated class from Pigeon that represents data sent in messages. -struct NavigationWaypointDto { +struct NavigationWaypointDto: Hashable { var title: String - var target: LatLngDto? - var placeID: String? - var preferSameSideOfRoad: Bool? - var preferredSegmentHeading: Int64? - - static func fromList(_ list: [Any?]) -> NavigationWaypointDto? { - let title = list[0] as! String - var target: LatLngDto? - if let targetList: [Any?] = nilOrValue(list[1]) { - target = LatLngDto.fromList(targetList) - } - let placeID: String? = nilOrValue(list[2]) - let preferSameSideOfRoad: Bool? = nilOrValue(list[3]) - let preferredSegmentHeading: Int64? = isNullish(list[4]) ? nil : - (list[4] is Int64? ? list[4] as! Int64? : Int64(list[4] as! Int32)) + var target: LatLngDto? = nil + var placeID: String? = nil + var preferSameSideOfRoad: Bool? = nil + var preferredSegmentHeading: Int64? = nil + + // swift-format-ignore: AlwaysUseLowerCamelCase + static func fromList(_ pigeonVar_list: [Any?]) -> NavigationWaypointDto? { + let title = pigeonVar_list[0] as! String + let target: LatLngDto? = nilOrValue(pigeonVar_list[1]) + let placeID: String? = nilOrValue(pigeonVar_list[2]) + let preferSameSideOfRoad: Bool? = nilOrValue(pigeonVar_list[3]) + let preferredSegmentHeading: Int64? = nilOrValue(pigeonVar_list[4]) return NavigationWaypointDto( title: title, @@ -203,44 +301,48 @@ struct NavigationWaypointDto { preferredSegmentHeading: preferredSegmentHeading ) } - func toList() -> [Any?] { - [ + return [ title, - target?.toList(), + target, placeID, preferSameSideOfRoad, preferredSegmentHeading, ] } + static func == (lhs: NavigationWaypointDto, rhs: NavigationWaypointDto) -> Bool { + return deepEqualsmessages(lhs.toList(), rhs.toList()) + } + func hash(into hasher: inout Hasher) { + deepHashmessages(value: toList(), hasher: &hasher) + } } /// Generated class from Pigeon that represents data sent in messages. -struct LocationDto { - var accuracy: Double? - var altitude: Double? - var elapsedRealtimeNanos: Int64? - var bearing: Double? - var isMock: Bool? - var latitude: Double? - var longitude: Double? - var provider: String? - var speed: Double? - var time: Int64? - - static func fromList(_ list: [Any?]) -> LocationDto? { - let accuracy: Double? = nilOrValue(list[0]) - let altitude: Double? = nilOrValue(list[1]) - let elapsedRealtimeNanos: Int64? = isNullish(list[2]) ? nil : - (list[2] is Int64? ? list[2] as! Int64? : Int64(list[2] as! Int32)) - let bearing: Double? = nilOrValue(list[3]) - let isMock: Bool? = nilOrValue(list[4]) - let latitude: Double? = nilOrValue(list[5]) - let longitude: Double? = nilOrValue(list[6]) - let provider: String? = nilOrValue(list[7]) - let speed: Double? = nilOrValue(list[8]) - let time: Int64? = isNullish(list[9]) ? nil : - (list[9] is Int64? ? list[9] as! Int64? : Int64(list[9] as! Int32)) +struct LocationDto: Hashable { + var accuracy: Double? = nil + var altitude: Double? = nil + var elapsedRealtimeNanos: Int64? = nil + var bearing: Double? = nil + var isMock: Bool? = nil + var latitude: Double? = nil + var longitude: Double? = nil + var provider: String? = nil + var speed: Double? = nil + var time: Int64? = nil + + // swift-format-ignore: AlwaysUseLowerCamelCase + static func fromList(_ pigeonVar_list: [Any?]) -> LocationDto? { + let accuracy: Double? = nilOrValue(pigeonVar_list[0]) + let altitude: Double? = nilOrValue(pigeonVar_list[1]) + let elapsedRealtimeNanos: Int64? = nilOrValue(pigeonVar_list[2]) + let bearing: Double? = nilOrValue(pigeonVar_list[3]) + let isMock: Bool? = nilOrValue(pigeonVar_list[4]) + let latitude: Double? = nilOrValue(pigeonVar_list[5]) + let longitude: Double? = nilOrValue(pigeonVar_list[6]) + let provider: String? = nilOrValue(pigeonVar_list[7]) + let speed: Double? = nilOrValue(pigeonVar_list[8]) + let time: Int64? = nilOrValue(pigeonVar_list[9]) return LocationDto( accuracy: accuracy, @@ -255,9 +357,8 @@ struct LocationDto { time: time ) } - func toList() -> [Any?] { - [ + return [ accuracy, altitude, elapsedRealtimeNanos, @@ -270,20 +371,27 @@ struct LocationDto { time, ] } + static func == (lhs: LocationDto, rhs: LocationDto) -> Bool { + return deepEqualsmessages(lhs.toList(), rhs.toList()) + } + func hash(into hasher: inout Hasher) { + deepHashmessages(value: toList(), hasher: &hasher) + } } /// Generated class from Pigeon that represents data sent in messages. -struct DeliveryVehicleDto { +struct DeliveryVehicleDto: Hashable { var providerId: String var id: String var name: String var stops: [VehicleStopDto?] - static func fromList(_ list: [Any?]) -> DeliveryVehicleDto? { - let providerId = list[0] as! String - let id = list[1] as! String - let name = list[2] as! String - let stops = list[3] as! [VehicleStopDto?] + // swift-format-ignore: AlwaysUseLowerCamelCase + static func fromList(_ pigeonVar_list: [Any?]) -> DeliveryVehicleDto? { + let providerId = pigeonVar_list[0] as! String + let id = pigeonVar_list[1] as! String + let name = pigeonVar_list[2] as! String + let stops = pigeonVar_list[3] as! [VehicleStopDto?] return DeliveryVehicleDto( providerId: providerId, @@ -292,43 +400,39 @@ struct DeliveryVehicleDto { stops: stops ) } - func toList() -> [Any?] { - [ + return [ providerId, id, name, stops, ] } + static func == (lhs: DeliveryVehicleDto, rhs: DeliveryVehicleDto) -> Bool { + return deepEqualsmessages(lhs.toList(), rhs.toList()) + } + func hash(into hasher: inout Hasher) { + deepHashmessages(value: toList(), hasher: &hasher) + } } /// Generated class from Pigeon that represents data sent in messages. -struct VehicleUpdateDto { - var vehicleState: VehicleStateDto? - var location: LatLngDto? - var destinationWaypoint: NavigationWaypointDto? - var route: [LatLngDto?]? - var remainingTimeInSeconds: Double? - var remainingDistanceInMeters: Double? - - static func fromList(_ list: [Any?]) -> VehicleUpdateDto? { - var vehicleState: VehicleStateDto? - let vehicleStateEnumVal: Int? = nilOrValue(list[0]) - if let vehicleStateRawValue = vehicleStateEnumVal { - vehicleState = VehicleStateDto(rawValue: vehicleStateRawValue)! - } - var location: LatLngDto? - if let locationList: [Any?] = nilOrValue(list[1]) { - location = LatLngDto.fromList(locationList) - } - var destinationWaypoint: NavigationWaypointDto? - if let destinationWaypointList: [Any?] = nilOrValue(list[2]) { - destinationWaypoint = NavigationWaypointDto.fromList(destinationWaypointList) - } - let route: [LatLngDto?]? = nilOrValue(list[3]) - let remainingTimeInSeconds: Double? = nilOrValue(list[4]) - let remainingDistanceInMeters: Double? = nilOrValue(list[5]) +struct VehicleUpdateDto: Hashable { + var vehicleState: VehicleStateDto? = nil + var location: LatLngDto? = nil + var destinationWaypoint: NavigationWaypointDto? = nil + var route: [LatLngDto?]? = nil + var remainingTimeInSeconds: Double? = nil + var remainingDistanceInMeters: Double? = nil + + // swift-format-ignore: AlwaysUseLowerCamelCase + static func fromList(_ pigeonVar_list: [Any?]) -> VehicleUpdateDto? { + let vehicleState: VehicleStateDto? = nilOrValue(pigeonVar_list[0]) + let location: LatLngDto? = nilOrValue(pigeonVar_list[1]) + let destinationWaypoint: NavigationWaypointDto? = nilOrValue(pigeonVar_list[2]) + let route: [LatLngDto?]? = nilOrValue(pigeonVar_list[3]) + let remainingTimeInSeconds: Double? = nilOrValue(pigeonVar_list[4]) + let remainingDistanceInMeters: Double? = nilOrValue(pigeonVar_list[5]) return VehicleUpdateDto( vehicleState: vehicleState, @@ -339,34 +443,114 @@ struct VehicleUpdateDto { remainingDistanceInMeters: remainingDistanceInMeters ) } - func toList() -> [Any?] { - [ - vehicleState?.rawValue, - location?.toList(), - destinationWaypoint?.toList(), + return [ + vehicleState, + location, + destinationWaypoint, route, remainingTimeInSeconds, remainingDistanceInMeters, ] } + static func == (lhs: VehicleUpdateDto, rhs: VehicleUpdateDto) -> Bool { + return deepEqualsmessages(lhs.toList(), rhs.toList()) + } + func hash(into hasher: inout Hasher) { + deepHashmessages(value: toList(), hasher: &hasher) + } } -private class CommonDriverApiCodecReader: FlutterStandardReader { +private class MessagesPigeonCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { - case 128: - return LocationDto.fromList(readValue() as! [Any?]) + case 129: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return DriverApiTypeDto(rawValue: enumResultAsInt) + } + return nil + case 130: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return VehicleStopStateDto(rawValue: enumResultAsInt) + } + return nil + case 131: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return VehicleStateDto(rawValue: enumResultAsInt) + } + return nil + case 132: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return DriverStatusLevelDto(rawValue: enumResultAsInt) + } + return nil + case 133: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return DriverStatusCodeDto(rawValue: enumResultAsInt) + } + return nil + case 134: + return TaskInfoDto.fromList(self.readValue() as! [Any?]) + case 135: + return VehicleStopDto.fromList(self.readValue() as! [Any?]) + case 136: + return LatLngDto.fromList(self.readValue() as! [Any?]) + case 137: + return NavigationWaypointDto.fromList(self.readValue() as! [Any?]) + case 138: + return LocationDto.fromList(self.readValue() as! [Any?]) + case 139: + return DeliveryVehicleDto.fromList(self.readValue() as! [Any?]) + case 140: + return VehicleUpdateDto.fromList(self.readValue() as! [Any?]) default: return super.readValue(ofType: type) } } } -private class CommonDriverApiCodecWriter: FlutterStandardWriter { +private class MessagesPigeonCodecWriter: FlutterStandardWriter { override func writeValue(_ value: Any) { - if let value = value as? LocationDto { - super.writeByte(128) + if let value = value as? DriverApiTypeDto { + super.writeByte(129) + super.writeValue(value.rawValue) + } else if let value = value as? VehicleStopStateDto { + super.writeByte(130) + super.writeValue(value.rawValue) + } else if let value = value as? VehicleStateDto { + super.writeByte(131) + super.writeValue(value.rawValue) + } else if let value = value as? DriverStatusLevelDto { + super.writeByte(132) + super.writeValue(value.rawValue) + } else if let value = value as? DriverStatusCodeDto { + super.writeByte(133) + super.writeValue(value.rawValue) + } else if let value = value as? TaskInfoDto { + super.writeByte(134) + super.writeValue(value.toList()) + } else if let value = value as? VehicleStopDto { + super.writeByte(135) + super.writeValue(value.toList()) + } else if let value = value as? LatLngDto { + super.writeByte(136) + super.writeValue(value.toList()) + } else if let value = value as? NavigationWaypointDto { + super.writeByte(137) + super.writeValue(value.toList()) + } else if let value = value as? LocationDto { + super.writeByte(138) + super.writeValue(value.toList()) + } else if let value = value as? DeliveryVehicleDto { + super.writeByte(139) + super.writeValue(value.toList()) + } else if let value = value as? VehicleUpdateDto { + super.writeByte(140) super.writeValue(value.toList()) } else { super.writeValue(value) @@ -374,24 +558,25 @@ private class CommonDriverApiCodecWriter: FlutterStandardWriter { } } -private class CommonDriverApiCodecReaderWriter: FlutterStandardReaderWriter { +private class MessagesPigeonCodecReaderWriter: FlutterStandardReaderWriter { override func reader(with data: Data) -> FlutterStandardReader { - CommonDriverApiCodecReader(data: data) + return MessagesPigeonCodecReader(data: data) } override func writer(with data: NSMutableData) -> FlutterStandardWriter { - CommonDriverApiCodecWriter(data: data) + return MessagesPigeonCodecWriter(data: data) } } -class CommonDriverApiCodec: FlutterStandardMessageCodec { - static let shared = CommonDriverApiCodec(readerWriter: CommonDriverApiCodecReaderWriter()) +class MessagesPigeonCodec: FlutterStandardMessageCodec, @unchecked Sendable { + static let shared = MessagesPigeonCodec(readerWriter: MessagesPigeonCodecReaderWriter()) } /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol CommonDriverApi { - func initialize(type: DriverApiTypeDto, providerId: String, vehicleId: String, - abnormalTerminationReportingEnabled: Bool) throws + func initialize( + type: DriverApiTypeDto, providerId: String, vehicleId: String, + abnormalTerminationReportingEnabled: Bool) throws func isInitialized(type: DriverApiTypeDto) throws -> Bool func getProviderId(type: DriverApiTypeDto) throws -> String func getVehicleId(type: DriverApiTypeDto) throws -> String @@ -405,30 +590,28 @@ protocol CommonDriverApi { } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. -enum CommonDriverApiSetup { - /// The codec used by CommonDriverApi. - static var codec: FlutterStandardMessageCodec { CommonDriverApiCodec.shared } +class CommonDriverApiSetup { + static var codec: FlutterStandardMessageCodec { MessagesPigeonCodec.shared } /// Sets up an instance of `CommonDriverApi` to handle messages through the `binaryMessenger`. - static func setUp(binaryMessenger: FlutterBinaryMessenger, api: CommonDriverApi?) { + static func setUp( + binaryMessenger: FlutterBinaryMessenger, api: CommonDriverApi?, + messageChannelSuffix: String = "" + ) { + let channelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : "" let initializeChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize", - binaryMessenger: binaryMessenger, - codec: codec - ) - if let api { + name: "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { initializeChannel.setMessageHandler { message, reply in let args = message as! [Any?] - let typeArg = DriverApiTypeDto(rawValue: args[0] as! Int)! + let typeArg = args[0] as! DriverApiTypeDto let providerIdArg = args[1] as! String let vehicleIdArg = args[2] as! String let abnormalTerminationReportingEnabledArg = args[3] as! Bool do { try api.initialize( - type: typeArg, - providerId: providerIdArg, - vehicleId: vehicleIdArg, - abnormalTerminationReportingEnabled: abnormalTerminationReportingEnabledArg - ) + type: typeArg, providerId: providerIdArg, vehicleId: vehicleIdArg, + abnormalTerminationReportingEnabled: abnormalTerminationReportingEnabledArg) reply(wrapResult(nil)) } catch { reply(wrapError(error)) @@ -438,14 +621,13 @@ enum CommonDriverApiSetup { initializeChannel.setMessageHandler(nil) } let isInitializedChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isInitialized", - binaryMessenger: binaryMessenger, - codec: codec - ) - if let api { + name: + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isInitialized\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { isInitializedChannel.setMessageHandler { message, reply in let args = message as! [Any?] - let typeArg = DriverApiTypeDto(rawValue: args[0] as! Int)! + let typeArg = args[0] as! DriverApiTypeDto do { let result = try api.isInitialized(type: typeArg) reply(wrapResult(result)) @@ -457,14 +639,13 @@ enum CommonDriverApiSetup { isInitializedChannel.setMessageHandler(nil) } let getProviderIdChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getProviderId", - binaryMessenger: binaryMessenger, - codec: codec - ) - if let api { + name: + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getProviderId\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { getProviderIdChannel.setMessageHandler { message, reply in let args = message as! [Any?] - let typeArg = DriverApiTypeDto(rawValue: args[0] as! Int)! + let typeArg = args[0] as! DriverApiTypeDto do { let result = try api.getProviderId(type: typeArg) reply(wrapResult(result)) @@ -476,14 +657,12 @@ enum CommonDriverApiSetup { getProviderIdChannel.setMessageHandler(nil) } let getVehicleIdChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getVehicleId", - binaryMessenger: binaryMessenger, - codec: codec - ) - if let api { + name: "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getVehicleId\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { getVehicleIdChannel.setMessageHandler { message, reply in let args = message as! [Any?] - let typeArg = DriverApiTypeDto(rawValue: args[0] as! Int)! + let typeArg = args[0] as! DriverApiTypeDto do { let result = try api.getVehicleId(type: typeArg) reply(wrapResult(result)) @@ -495,14 +674,13 @@ enum CommonDriverApiSetup { getVehicleIdChannel.setMessageHandler(nil) } let isLocationTrackingEnabledChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isLocationTrackingEnabled", - binaryMessenger: binaryMessenger, - codec: codec - ) - if let api { + name: + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isLocationTrackingEnabled\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { isLocationTrackingEnabledChannel.setMessageHandler { message, reply in let args = message as! [Any?] - let typeArg = DriverApiTypeDto(rawValue: args[0] as! Int)! + let typeArg = args[0] as! DriverApiTypeDto do { let result = try api.isLocationTrackingEnabled(type: typeArg) reply(wrapResult(result)) @@ -514,14 +692,13 @@ enum CommonDriverApiSetup { isLocationTrackingEnabledChannel.setMessageHandler(nil) } let setLocationTrackingEnabledChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationTrackingEnabled", - binaryMessenger: binaryMessenger, - codec: codec - ) - if let api { + name: + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationTrackingEnabled\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { setLocationTrackingEnabledChannel.setMessageHandler { message, reply in let args = message as! [Any?] - let typeArg = DriverApiTypeDto(rawValue: args[0] as! Int)! + let typeArg = args[0] as! DriverApiTypeDto let enabledArg = args[1] as! Bool do { try api.setLocationTrackingEnabled(type: typeArg, enabled: enabledArg) @@ -534,14 +711,13 @@ enum CommonDriverApiSetup { setLocationTrackingEnabledChannel.setMessageHandler(nil) } let getLocationReportingIntervalMillisChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getLocationReportingIntervalMillis", - binaryMessenger: binaryMessenger, - codec: codec - ) - if let api { + name: + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getLocationReportingIntervalMillis\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { getLocationReportingIntervalMillisChannel.setMessageHandler { message, reply in let args = message as! [Any?] - let typeArg = DriverApiTypeDto(rawValue: args[0] as! Int)! + let typeArg = args[0] as! DriverApiTypeDto do { let result = try api.getLocationReportingIntervalMillis(type: typeArg) reply(wrapResult(result)) @@ -553,15 +729,14 @@ enum CommonDriverApiSetup { getLocationReportingIntervalMillisChannel.setMessageHandler(nil) } let setLocationReportingIntervalMillisChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationReportingIntervalMillis", - binaryMessenger: binaryMessenger, - codec: codec - ) - if let api { + name: + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationReportingIntervalMillis\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { setLocationReportingIntervalMillisChannel.setMessageHandler { message, reply in let args = message as! [Any?] - let typeArg = DriverApiTypeDto(rawValue: args[0] as! Int)! - let millisecondsArg = args[1] is Int64 ? args[1] as! Int64 : Int64(args[1] as! Int32) + let typeArg = args[0] as! DriverApiTypeDto + let millisecondsArg = args[1] as! Int64 do { try api.setLocationReportingIntervalMillis(type: typeArg, milliseconds: millisecondsArg) reply(wrapResult(nil)) @@ -573,14 +748,12 @@ enum CommonDriverApiSetup { setLocationReportingIntervalMillisChannel.setMessageHandler(nil) } let disposeChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.dispose", - binaryMessenger: binaryMessenger, - codec: codec - ) - if let api { + name: "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.dispose\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { disposeChannel.setMessageHandler { message, reply in let args = message as! [Any?] - let typeArg = DriverApiTypeDto(rawValue: args[0] as! Int)! + let typeArg = args[0] as! DriverApiTypeDto do { try api.dispose(type: typeArg) reply(wrapResult(nil)) @@ -592,14 +765,13 @@ enum CommonDriverApiSetup { disposeChannel.setMessageHandler(nil) } let getDriverSdkVersionChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getDriverSdkVersion", - binaryMessenger: binaryMessenger, - codec: codec - ) - if let api { + name: + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getDriverSdkVersion\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { getDriverSdkVersionChannel.setMessageHandler { message, reply in let args = message as! [Any?] - let typeArg = DriverApiTypeDto(rawValue: args[0] as! Int)! + let typeArg = args[0] as! DriverApiTypeDto do { let result = try api.getDriverSdkVersion(type: typeArg) reply(wrapResult(result)) @@ -611,14 +783,13 @@ enum CommonDriverApiSetup { getDriverSdkVersionChannel.setMessageHandler(nil) } let setSupplementalLocationChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setSupplementalLocation", - binaryMessenger: binaryMessenger, - codec: codec - ) - if let api { + name: + "dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setSupplementalLocation\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { setSupplementalLocationChannel.setMessageHandler { message, reply in let args = message as! [Any?] - let typeArg = DriverApiTypeDto(rawValue: args[0] as! Int)! + let typeArg = args[0] as! DriverApiTypeDto let locationArg = args[1] as! LocationDto do { try api.setSupplementalLocation(type: typeArg, location: locationArg) @@ -632,92 +803,37 @@ enum CommonDriverApiSetup { } } } - -private class DeliveryDriverApiCodecReader: FlutterStandardReader { - override func readValue(ofType type: UInt8) -> Any? { - switch type { - case 128: - return DeliveryVehicleDto.fromList(readValue() as! [Any?]) - case 129: - return LatLngDto.fromList(readValue() as! [Any?]) - case 130: - return NavigationWaypointDto.fromList(readValue() as! [Any?]) - case 131: - return TaskInfoDto.fromList(readValue() as! [Any?]) - case 132: - return VehicleStopDto.fromList(readValue() as! [Any?]) - default: - return super.readValue(ofType: type) - } - } -} - -private class DeliveryDriverApiCodecWriter: FlutterStandardWriter { - override func writeValue(_ value: Any) { - if let value = value as? DeliveryVehicleDto { - super.writeByte(128) - super.writeValue(value.toList()) - } else if let value = value as? LatLngDto { - super.writeByte(129) - super.writeValue(value.toList()) - } else if let value = value as? NavigationWaypointDto { - super.writeByte(130) - super.writeValue(value.toList()) - } else if let value = value as? TaskInfoDto { - super.writeByte(131) - super.writeValue(value.toList()) - } else if let value = value as? VehicleStopDto { - super.writeByte(132) - super.writeValue(value.toList()) - } else { - super.writeValue(value) - } - } -} - -private class DeliveryDriverApiCodecReaderWriter: FlutterStandardReaderWriter { - override func reader(with data: Data) -> FlutterStandardReader { - DeliveryDriverApiCodecReader(data: data) - } - - override func writer(with data: NSMutableData) -> FlutterStandardWriter { - DeliveryDriverApiCodecWriter(data: data) - } -} - -class DeliveryDriverApiCodec: FlutterStandardMessageCodec { - static let shared = DeliveryDriverApiCodec(readerWriter: DeliveryDriverApiCodecReaderWriter()) -} - /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol DeliveryDriverApi { func arrivedAtStop(completion: @escaping (Result<[VehicleStopDto], Error>) -> Void) func completedStop(completion: @escaping (Result<[VehicleStopDto], Error>) -> Void) func enrouteToNextStop(completion: @escaping (Result<[VehicleStopDto], Error>) -> Void) func getRemainingVehicleStops(completion: @escaping (Result<[VehicleStopDto], Error>) -> Void) - func setVehicleStops(stops: [VehicleStopDto], - completion: @escaping (Result<[VehicleStopDto], Error>) -> Void) + func setVehicleStops( + stops: [VehicleStopDto], completion: @escaping (Result<[VehicleStopDto], Error>) -> Void) func getDeliveryVehicle(completion: @escaping (Result) -> Void) } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. -enum DeliveryDriverApiSetup { - /// The codec used by DeliveryDriverApi. - static var codec: FlutterStandardMessageCodec { DeliveryDriverApiCodec.shared } +class DeliveryDriverApiSetup { + static var codec: FlutterStandardMessageCodec { MessagesPigeonCodec.shared } /// Sets up an instance of `DeliveryDriverApi` to handle messages through the `binaryMessenger`. - static func setUp(binaryMessenger: FlutterBinaryMessenger, api: DeliveryDriverApi?) { + static func setUp( + binaryMessenger: FlutterBinaryMessenger, api: DeliveryDriverApi?, + messageChannelSuffix: String = "" + ) { + let channelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : "" let arrivedAtStopChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.arrivedAtStop", - binaryMessenger: binaryMessenger, - codec: codec - ) - if let api { + name: + "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.arrivedAtStop\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { arrivedAtStopChannel.setMessageHandler { _, reply in api.arrivedAtStop { result in switch result { - case let .success(res): + case .success(let res): reply(wrapResult(res)) - case let .failure(error): + case .failure(let error): reply(wrapError(error)) } } @@ -726,17 +842,16 @@ enum DeliveryDriverApiSetup { arrivedAtStopChannel.setMessageHandler(nil) } let completedStopChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.completedStop", - binaryMessenger: binaryMessenger, - codec: codec - ) - if let api { + name: + "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.completedStop\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { completedStopChannel.setMessageHandler { _, reply in api.completedStop { result in switch result { - case let .success(res): + case .success(let res): reply(wrapResult(res)) - case let .failure(error): + case .failure(let error): reply(wrapError(error)) } } @@ -745,17 +860,16 @@ enum DeliveryDriverApiSetup { completedStopChannel.setMessageHandler(nil) } let enrouteToNextStopChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.enrouteToNextStop", - binaryMessenger: binaryMessenger, - codec: codec - ) - if let api { + name: + "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.enrouteToNextStop\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { enrouteToNextStopChannel.setMessageHandler { _, reply in api.enrouteToNextStop { result in switch result { - case let .success(res): + case .success(let res): reply(wrapResult(res)) - case let .failure(error): + case .failure(let error): reply(wrapError(error)) } } @@ -764,17 +878,16 @@ enum DeliveryDriverApiSetup { enrouteToNextStopChannel.setMessageHandler(nil) } let getRemainingVehicleStopsChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.getRemainingVehicleStops", - binaryMessenger: binaryMessenger, - codec: codec - ) - if let api { + name: + "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.getRemainingVehicleStops\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { getRemainingVehicleStopsChannel.setMessageHandler { _, reply in api.getRemainingVehicleStops { result in switch result { - case let .success(res): + case .success(let res): reply(wrapResult(res)) - case let .failure(error): + case .failure(let error): reply(wrapError(error)) } } @@ -783,19 +896,18 @@ enum DeliveryDriverApiSetup { getRemainingVehicleStopsChannel.setMessageHandler(nil) } let setVehicleStopsChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.setVehicleStops", - binaryMessenger: binaryMessenger, - codec: codec - ) - if let api { + name: + "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.setVehicleStops\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { setVehicleStopsChannel.setMessageHandler { message, reply in let args = message as! [Any?] let stopsArg = args[0] as! [VehicleStopDto] api.setVehicleStops(stops: stopsArg) { result in switch result { - case let .success(res): + case .success(let res): reply(wrapResult(res)) - case let .failure(error): + case .failure(let error): reply(wrapError(error)) } } @@ -804,17 +916,16 @@ enum DeliveryDriverApiSetup { setVehicleStopsChannel.setMessageHandler(nil) } let getDeliveryVehicleChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.getDeliveryVehicle", - binaryMessenger: binaryMessenger, - codec: codec - ) - if let api { + name: + "dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.getDeliveryVehicle\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { getDeliveryVehicleChannel.setMessageHandler { _, reply in api.getDeliveryVehicle { result in switch result { - case let .success(res): + case .success(let res): reply(wrapResult(res)) - case let .failure(error): + case .failure(let error): reply(wrapError(error)) } } @@ -824,26 +935,28 @@ enum DeliveryDriverApiSetup { } } } - /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol RidesharingDriverApi { func setVehicleState(state: VehicleStateDto) throws } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. -enum RidesharingDriverApiSetup { - /// The codec used by RidesharingDriverApi. - /// Sets up an instance of `RidesharingDriverApi` to handle messages through the - /// `binaryMessenger`. - static func setUp(binaryMessenger: FlutterBinaryMessenger, api: RidesharingDriverApi?) { +class RidesharingDriverApiSetup { + static var codec: FlutterStandardMessageCodec { MessagesPigeonCodec.shared } + /// Sets up an instance of `RidesharingDriverApi` to handle messages through the `binaryMessenger`. + static func setUp( + binaryMessenger: FlutterBinaryMessenger, api: RidesharingDriverApi?, + messageChannelSuffix: String = "" + ) { + let channelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : "" let setVehicleStateChannel = FlutterBasicMessageChannel( - name: "dev.flutter.pigeon.google_driver_flutter.RidesharingDriverApi.setVehicleState", - binaryMessenger: binaryMessenger - ) - if let api { + name: + "dev.flutter.pigeon.google_driver_flutter.RidesharingDriverApi.setVehicleState\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { setVehicleStateChannel.setMessageHandler { message, reply in let args = message as! [Any?] - let stateArg = VehicleStateDto(rawValue: args[0] as! Int)! + let stateArg = args[0] as! VehicleStateDto do { try api.setVehicleState(state: stateArg) reply(wrapResult(nil)) @@ -856,23 +969,30 @@ enum RidesharingDriverApiSetup { } } } - /// Generated protocol from Pigeon that represents Flutter messages that can be called from Swift. protocol AuthTokenEventApiProtocol { - func getToken(taskId taskIdArg: String?, vehicleId vehicleIdArg: String?, - completion: @escaping (Result) -> Void) + func getToken( + taskId taskIdArg: String?, vehicleId vehicleIdArg: String?, + completion: @escaping (Result) -> Void) } - class AuthTokenEventApi: AuthTokenEventApiProtocol { private let binaryMessenger: FlutterBinaryMessenger - init(binaryMessenger: FlutterBinaryMessenger) { + private let messageChannelSuffix: String + init(binaryMessenger: FlutterBinaryMessenger, messageChannelSuffix: String = "") { self.binaryMessenger = binaryMessenger + self.messageChannelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : "" } - - func getToken(taskId taskIdArg: String?, vehicleId vehicleIdArg: String?, - completion: @escaping (Result) -> Void) { - let channelName = "dev.flutter.pigeon.google_driver_flutter.AuthTokenEventApi.getToken" - let channel = FlutterBasicMessageChannel(name: channelName, binaryMessenger: binaryMessenger) + var codec: MessagesPigeonCodec { + return MessagesPigeonCodec.shared + } + func getToken( + taskId taskIdArg: String?, vehicleId vehicleIdArg: String?, + completion: @escaping (Result) -> Void + ) { + let channelName: String = + "dev.flutter.pigeon.google_driver_flutter.AuthTokenEventApi.getToken\(messageChannelSuffix)" + let channel = FlutterBasicMessageChannel( + name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([taskIdArg, vehicleIdArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) @@ -882,13 +1002,13 @@ class AuthTokenEventApi: AuthTokenEventApiProtocol { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) - completion(.failure(FlutterError(code: code, message: message, details: details))) + completion(.failure(PigeonError(code: code, message: message, details: details))) } else if listResponse[0] == nil { - completion(.failure(FlutterError( - code: "null-error", - message: "Flutter api returned null value for non-null return value.", - details: "" - ))) + completion( + .failure( + PigeonError( + code: "null-error", + message: "Flutter api returned null value for non-null return value.", details: ""))) } else { let result = listResponse[0] as! String completion(.success(result)) @@ -896,87 +1016,33 @@ class AuthTokenEventApi: AuthTokenEventApiProtocol { } } } - -private class VehicleReporterListenerApiCodecReader: FlutterStandardReader { - override func readValue(ofType type: UInt8) -> Any? { - switch type { - case 128: - return LatLngDto.fromList(readValue() as! [Any?]) - case 129: - return LatLngDto.fromList(readValue() as! [Any?]) - case 130: - return NavigationWaypointDto.fromList(readValue() as! [Any?]) - case 131: - return VehicleUpdateDto.fromList(readValue() as! [Any?]) - default: - return super.readValue(ofType: type) - } - } -} - -private class VehicleReporterListenerApiCodecWriter: FlutterStandardWriter { - override func writeValue(_ value: Any) { - if let value = value as? LatLngDto { - super.writeByte(128) - super.writeValue(value.toList()) - } else if let value = value as? LatLngDto { - super.writeByte(129) - super.writeValue(value.toList()) - } else if let value = value as? NavigationWaypointDto { - super.writeByte(130) - super.writeValue(value.toList()) - } else if let value = value as? VehicleUpdateDto { - super.writeByte(131) - super.writeValue(value.toList()) - } else { - super.writeValue(value) - } - } -} - -private class VehicleReporterListenerApiCodecReaderWriter: FlutterStandardReaderWriter { - override func reader(with data: Data) -> FlutterStandardReader { - VehicleReporterListenerApiCodecReader(data: data) - } - - override func writer(with data: NSMutableData) -> FlutterStandardWriter { - VehicleReporterListenerApiCodecWriter(data: data) - } -} - -class VehicleReporterListenerApiCodec: FlutterStandardMessageCodec { - static let shared = - VehicleReporterListenerApiCodec(readerWriter: VehicleReporterListenerApiCodecReaderWriter()) -} - /// Generated protocol from Pigeon that represents Flutter messages that can be called from Swift. protocol VehicleReporterListenerApiProtocol { - func onDidSucceed(vehicleUpdate vehicleUpdateArg: VehicleUpdateDto, - completion: @escaping (Result) -> Void) - func onDidFail(vehicleUpdate vehicleUpdateArg: VehicleUpdateDto, errorCode errorCodeArg: String, - errorMessage errorMessageArg: String, - completion: @escaping (Result) -> Void) + func onDidSucceed( + vehicleUpdate vehicleUpdateArg: VehicleUpdateDto, + completion: @escaping (Result) -> Void) + func onDidFail( + vehicleUpdate vehicleUpdateArg: VehicleUpdateDto, errorCode errorCodeArg: String, + errorMessage errorMessageArg: String, completion: @escaping (Result) -> Void) } - class VehicleReporterListenerApi: VehicleReporterListenerApiProtocol { private let binaryMessenger: FlutterBinaryMessenger - init(binaryMessenger: FlutterBinaryMessenger) { + private let messageChannelSuffix: String + init(binaryMessenger: FlutterBinaryMessenger, messageChannelSuffix: String = "") { self.binaryMessenger = binaryMessenger + self.messageChannelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : "" } - - var codec: FlutterStandardMessageCodec { - VehicleReporterListenerApiCodec.shared + var codec: MessagesPigeonCodec { + return MessagesPigeonCodec.shared } - - func onDidSucceed(vehicleUpdate vehicleUpdateArg: VehicleUpdateDto, - completion: @escaping (Result) -> Void) { - let channelName = - "dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidSucceed" + func onDidSucceed( + vehicleUpdate vehicleUpdateArg: VehicleUpdateDto, + completion: @escaping (Result) -> Void + ) { + let channelName: String = + "dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidSucceed\(messageChannelSuffix)" let channel = FlutterBasicMessageChannel( - name: channelName, - binaryMessenger: binaryMessenger, - codec: codec - ) + name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([vehicleUpdateArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) @@ -986,23 +1052,20 @@ class VehicleReporterListenerApi: VehicleReporterListenerApiProtocol { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) - completion(.failure(FlutterError(code: code, message: message, details: details))) + completion(.failure(PigeonError(code: code, message: message, details: details))) } else { completion(.success(())) } } } - - func onDidFail(vehicleUpdate vehicleUpdateArg: VehicleUpdateDto, errorCode errorCodeArg: String, - errorMessage errorMessageArg: String, - completion: @escaping (Result) -> Void) { - let channelName = - "dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidFail" + func onDidFail( + vehicleUpdate vehicleUpdateArg: VehicleUpdateDto, errorCode errorCodeArg: String, + errorMessage errorMessageArg: String, completion: @escaping (Result) -> Void + ) { + let channelName: String = + "dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidFail\(messageChannelSuffix)" let channel = FlutterBasicMessageChannel( - name: channelName, - binaryMessenger: binaryMessenger, - codec: codec - ) + name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage([vehicleUpdateArg, errorCodeArg, errorMessageArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) @@ -1012,42 +1075,42 @@ class VehicleReporterListenerApi: VehicleReporterListenerApiProtocol { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) - completion(.failure(FlutterError(code: code, message: message, details: details))) + completion(.failure(PigeonError(code: code, message: message, details: details))) } else { completion(.success(())) } } } } - /// Generated protocol from Pigeon that represents Flutter messages that can be called from Swift. protocol DriverStatusListenerApiProtocol { - func onStatusUpdate(level levelArg: DriverStatusLevelDto, code codeArg: DriverStatusCodeDto, - message messageArg: String, errorCode errorCodeArg: String?, - errorMessage errorMessageArg: String?, - completion: @escaping (Result) -> Void) + func onStatusUpdate( + level levelArg: DriverStatusLevelDto, code codeArg: DriverStatusCodeDto, + message messageArg: String, errorCode errorCodeArg: String?, + errorMessage errorMessageArg: String?, completion: @escaping (Result) -> Void + ) } - class DriverStatusListenerApi: DriverStatusListenerApiProtocol { private let binaryMessenger: FlutterBinaryMessenger - init(binaryMessenger: FlutterBinaryMessenger) { + private let messageChannelSuffix: String + init(binaryMessenger: FlutterBinaryMessenger, messageChannelSuffix: String = "") { self.binaryMessenger = binaryMessenger + self.messageChannelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : "" } - - func onStatusUpdate(level levelArg: DriverStatusLevelDto, code codeArg: DriverStatusCodeDto, - message messageArg: String, errorCode errorCodeArg: String?, - errorMessage errorMessageArg: String?, - completion: @escaping (Result) -> Void) { - let channelName = - "dev.flutter.pigeon.google_driver_flutter.DriverStatusListenerApi.onStatusUpdate" - let channel = FlutterBasicMessageChannel(name: channelName, binaryMessenger: binaryMessenger) - channel.sendMessage([ - levelArg.rawValue, - codeArg.rawValue, - messageArg, - errorCodeArg, - errorMessageArg, - ] as [Any?]) { response in + var codec: MessagesPigeonCodec { + return MessagesPigeonCodec.shared + } + func onStatusUpdate( + level levelArg: DriverStatusLevelDto, code codeArg: DriverStatusCodeDto, + message messageArg: String, errorCode errorCodeArg: String?, + errorMessage errorMessageArg: String?, completion: @escaping (Result) -> Void + ) { + let channelName: String = + "dev.flutter.pigeon.google_driver_flutter.DriverStatusListenerApi.onStatusUpdate\(messageChannelSuffix)" + let channel = FlutterBasicMessageChannel( + name: channelName, binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage([levelArg, codeArg, messageArg, errorCodeArg, errorMessageArg] as [Any?]) { + response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return @@ -1056,7 +1119,7 @@ class DriverStatusListenerApi: DriverStatusListenerApiProtocol { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) - completion(.failure(FlutterError(code: code, message: message, details: details))) + completion(.failure(PigeonError(code: code, message: message, details: details))) } else { completion(.success(())) } diff --git a/ios/google_driver_flutter.podspec b/ios/google_driver_flutter.podspec index b995328..84969c8 100644 --- a/ios/google_driver_flutter.podspec +++ b/ios/google_driver_flutter.podspec @@ -15,9 +15,9 @@ A Google Maps Driver Flutter plugin. s.source = { :path => '.' } s.source_files = 'Classes/**/*' s.dependency 'Flutter' - s.dependency 'GoogleRidesharingDriver', '~> 3.2.0' + s.dependency 'GoogleRidesharingDriver', '~> 10.0.0' s.dependency 'google_navigation_flutter' - s.platform = :ios, '14.0' + s.platform = :ios, '16.0' s.static_framework = true # Flutter.framework does not contain a i386 slice. diff --git a/lib/google_driver_flutter.dart b/lib/google_driver_flutter.dart index 67b05dc..46b5522 100644 --- a/lib/google_driver_flutter.dart +++ b/lib/google_driver_flutter.dart @@ -23,6 +23,7 @@ /// This library provides support for two types of drivers: /// - [Delivery Driver](../topics/Delivery%20Driver-topic.html) (LMFS) /// - [RideSharing Driver](../topics/RideSharing%20Driver-topic.html) (ODRD) +// ignore: unnecessary_library_name library google_driver_flutter; export 'src/google_driver_flutter.dart'; diff --git a/lib/src/google_driver_flutter.dart b/lib/src/google_driver_flutter.dart index f49a540..7899b51 100644 --- a/lib/src/google_driver_flutter.dart +++ b/lib/src/google_driver_flutter.dart @@ -34,9 +34,7 @@ import 'method_channel/method_channel.dart'; /// /// {@category Delivery Driver} /// {@category Ridesharing Driver} -typedef OnGetToken = Future Function( - AuthTokenContext context, -); +typedef OnGetToken = Future Function(AuthTokenContext context); /// Called when there are status updates (Android-only). /// @@ -46,23 +44,26 @@ typedef OnGetToken = Future Function( /// /// {@category Delivery Driver} /// {@category Ridesharing Driver} -typedef OnStatusUpdate = void Function(DriverStatusLevel level, - DriverStatusCode code, String message, DriverException? exception); +typedef OnStatusUpdate = + void Function( + DriverStatusLevel level, + DriverStatusCode code, + String message, + DriverException? exception, + ); /// Called when the vehicle location or state update succeeded. /// /// {@category Delivery Driver} /// {@category Ridesharing Driver} -typedef OnVehicleUpdateDidSucceed = void Function( - VehicleUpdate vehicleUpdate, -); +typedef OnVehicleUpdateDidSucceed = void Function(VehicleUpdate vehicleUpdate); /// Called when the vehicle location or state update failed. /// /// {@category Delivery Driver} /// {@category Ridesharing Driver} -typedef OnVehicleUpdateDidFail = void Function( - VehicleUpdate vehicleUpdate, DriverException exception); +typedef OnVehicleUpdateDidFail = + void Function(VehicleUpdate vehicleUpdate, DriverException exception); /// Base vehicle reporter containing shared methods between delivery and /// ridesharing apis. @@ -101,10 +102,14 @@ class CommonVehicleReporter { /// By default, the interval is 10 seconds. The minimum allowed /// interval is 5 seconds and the maximum 60 seconds. Future setLocationReportingInterval(Duration duration) async { - assert(duration.inSeconds >= 5, - 'Minimum supported reporting interval is 5 seconds'); - assert(duration.inSeconds <= 60, - 'Maximum supported reporting interval is 60 seconds'); + assert( + duration.inSeconds >= 5, + 'Minimum supported reporting interval is 5 seconds', + ); + assert( + duration.inSeconds <= 60, + 'Maximum supported reporting interval is 60 seconds', + ); return _commonApi.setLocationReportingInterval(duration); } @@ -116,10 +121,13 @@ class CommonVehicleReporter { /// initialization callback instead. void setListener(VehicleReporterListener? vehicleReporterListener) { if (vehicleReporterListener != null) { - VehicleReporterListenerApi.setup(_VehicleReporterListenerApiImpl( - vehicleReporterListener: vehicleReporterListener)); + VehicleReporterListenerApi.setUp( + _VehicleReporterListenerApiImpl( + vehicleReporterListener: vehicleReporterListener, + ), + ); } else { - VehicleReporterListenerApi.setup(null); + VehicleReporterListenerApi.setUp(null); } } } @@ -144,7 +152,7 @@ class CommonVehicleReporter { /// {@category Delivery Driver} class DeliveryVehicleReporter extends CommonVehicleReporter { DeliveryVehicleReporter._(this._api, TypedCommonDriverApi _commonApi) - : super._(_commonApi); + : super._(_commonApi); final DeliveryDriverApi _api; @@ -202,7 +210,8 @@ class DeliveryVehicleReporter extends CommonVehicleReporter { Future> setVehicleStops(List stops) async { try { final List stopsDto = await _api.setVehicleStops( - stops.map((VehicleStop stop) => stop.toDto()).toList()); + stops.map((VehicleStop stop) => stop.toDto()).toList(), + ); return stopsDto.nonNulls .map((VehicleStopDto stop) => stop.toVehicleStop()) .toList(); @@ -241,7 +250,7 @@ class DeliveryVehicleReporter extends CommonVehicleReporter { /// {@category Ridesharing Driver} class RidesharingVehicleReporter extends CommonVehicleReporter { RidesharingVehicleReporter._(this._api, TypedCommonDriverApi _commonApi) - : super._(_commonApi); + : super._(_commonApi); final RidesharingDriverApi _api; @@ -264,8 +273,10 @@ class RidesharingVehicleReporter extends CommonVehicleReporter { /// {@category Ridesharing Driver} class VehicleReporterListener { /// Constructs an instance of [VehicleReporterListener]. - VehicleReporterListener( - {required this.onDidSucceed, required this.onDidFail}); + VehicleReporterListener({ + required this.onDidSucceed, + required this.onDidFail, + }); /// Called when the vehicle location or state update succeeded. final OnVehicleUpdateDidSucceed onDidSucceed; @@ -292,32 +303,41 @@ class TypedCommonDriverApi { /// Initialize Driver api instance for [apiType] with the given /// [providerId] and [vehicleId]. - Future initialize( - {required String providerId, - required String vehicleId, - required OnGetToken onGetToken, - OnStatusUpdate? onStatusUpdate, - bool abnormalTerminationReportingEnabled = false}) async { + Future initialize({ + required String providerId, + required String vehicleId, + required OnGetToken onGetToken, + OnStatusUpdate? onStatusUpdate, + bool abnormalTerminationReportingEnabled = false, + }) async { try { - await _commonApi.initialize(apiType.toDto(), providerId, vehicleId, - abnormalTerminationReportingEnabled); + await _commonApi.initialize( + apiType.toDto(), + providerId, + vehicleId, + abnormalTerminationReportingEnabled, + ); - AuthTokenEventApi.setup( - _AuthTokenEventApiImpl(onGetTokenEvent: onGetToken)); + AuthTokenEventApi.setUp( + _AuthTokenEventApiImpl(onGetTokenEvent: onGetToken), + ); if (onStatusUpdate != null) { - DriverStatusListenerApi.setup( - _DriverStatusListenerApiImpl(onStatusUpdateEvent: onStatusUpdate)); + DriverStatusListenerApi.setUp( + _DriverStatusListenerApiImpl(onStatusUpdateEvent: onStatusUpdate), + ); } else { - DriverStatusListenerApi.setup(null); + DriverStatusListenerApi.setUp(null); } } on PlatformException catch (e) { switch (e.code) { case 'sessionNotInitialized': throw const DriverInitializationException( - DriverInitializationError.navigationNotInitialized); + DriverInitializationError.navigationNotInitialized, + ); case 'apiAlreadyInitialized': throw const DriverInitializationException( - DriverInitializationError.apiAlreadyInitialized); + DriverInitializationError.apiAlreadyInitialized, + ); default: rethrow; } @@ -355,7 +375,9 @@ class TypedCommonDriverApi { Future setLocationTrackingEnabled(bool enabled) async { try { return await _commonApi.setLocationTrackingEnabled( - apiType.toDto(), enabled); + apiType.toDto(), + enabled, + ); } on PlatformException catch (e) { throw _convertException(e); } @@ -370,8 +392,10 @@ class TypedCommonDriverApi { Future getLocationReportingInterval() async { try { return Duration( - milliseconds: await _commonApi - .getLocationReportingIntervalMillis(apiType.toDto())); + milliseconds: await _commonApi.getLocationReportingIntervalMillis( + apiType.toDto(), + ), + ); } on PlatformException catch (e) { throw _convertException(e); } @@ -383,13 +407,19 @@ class TypedCommonDriverApi { /// By default, the interval is 10 seconds. The minimum allowed /// interval is 5 seconds and the maximum 60 seconds. Future setLocationReportingInterval(Duration duration) async { - assert(duration.inSeconds >= 5, - 'Minimum supported reporting interval is 5 seconds'); - assert(duration.inSeconds <= 60, - 'Maximum supported reporting interval is 60 seconds'); + assert( + duration.inSeconds >= 5, + 'Minimum supported reporting interval is 5 seconds', + ); + assert( + duration.inSeconds <= 60, + 'Maximum supported reporting interval is 60 seconds', + ); try { return await _commonApi.setLocationReportingIntervalMillis( - apiType.toDto(), duration.inMilliseconds); + apiType.toDto(), + duration.inMilliseconds, + ); } on PlatformException catch (e) { throw _convertException(e); } @@ -403,11 +433,14 @@ class TypedCommonDriverApi { Future setSupplementalLocation(Location location) async { try { return _commonApi.setSupplementalLocation( - apiType.toDto(), location.toDto()); + apiType.toDto(), + location.toDto(), + ); } on PlatformException catch (error) { if (error.code == 'notSupported') { throw UnsupportedError( - 'Setting supplemental location is not supported on iOS.'); + 'Setting supplemental location is not supported on iOS.', + ); } else { rethrow; } @@ -432,8 +465,10 @@ class DeliveryDriver { static final TypedCommonDriverApi _deliveryCommonDriverApi = TypedCommonDriverApi._(DriverApiType.delivery); static final DeliveryDriverApi _deliveryApi = DeliveryDriverApi(); - static final DeliveryVehicleReporter _reporter = - DeliveryVehicleReporter._(_deliveryApi, _deliveryCommonDriverApi); + static final DeliveryVehicleReporter _reporter = DeliveryVehicleReporter._( + _deliveryApi, + _deliveryCommonDriverApi, + ); /// Initialize DeliveryDriver instance with the given /// [providerId] and [vehicleId]. @@ -445,19 +480,20 @@ class DeliveryDriver { /// Optional parameter [abnormalTerminationReportingEnabled] can be used to /// disable reporting abnormal SDK terminations such as app crashes while the /// SDK is still running. By default, the reporting is enabled. - static Future initialize( - {required String providerId, - required String vehicleId, - required OnGetToken onGetToken, - OnStatusUpdate? onStatusUpdate, - bool abnormalTerminationReportingEnabled = false}) async { + static Future initialize({ + required String providerId, + required String vehicleId, + required OnGetToken onGetToken, + OnStatusUpdate? onStatusUpdate, + bool abnormalTerminationReportingEnabled = false, + }) async { return _deliveryCommonDriverApi.initialize( - providerId: providerId, - vehicleId: vehicleId, - onGetToken: onGetToken, - onStatusUpdate: onStatusUpdate, - abnormalTerminationReportingEnabled: - abnormalTerminationReportingEnabled); + providerId: providerId, + vehicleId: vehicleId, + onGetToken: onGetToken, + onStatusUpdate: onStatusUpdate, + abnormalTerminationReportingEnabled: abnormalTerminationReportingEnabled, + ); } /// Returns an instance of the [DeliveryVehicleReporter], @@ -528,7 +564,9 @@ class RidesharingDriver { static final RidesharingDriverApi _ridesharingApi = RidesharingDriverApi(); static final RidesharingVehicleReporter _reporter = RidesharingVehicleReporter._( - _ridesharingApi, _ridesharingCommonDriverApi); + _ridesharingApi, + _ridesharingCommonDriverApi, + ); /// Initialize RidesharingDriver instance with the given /// [providerId] and [vehicleId]. @@ -540,19 +578,20 @@ class RidesharingDriver { /// Optional parameter [abnormalTerminationReportingEnabled] can be used to /// disable reporting abnormal SDK terminations such as app crashes while the /// SDK is still running. By default, the reporting is enabled. - static Future initialize( - {required String providerId, - required String vehicleId, - required OnGetToken onGetToken, - OnStatusUpdate? onStatusUpdate, - bool abnormalTerminationReportingEnabled = false}) async { + static Future initialize({ + required String providerId, + required String vehicleId, + required OnGetToken onGetToken, + OnStatusUpdate? onStatusUpdate, + bool abnormalTerminationReportingEnabled = false, + }) async { return _ridesharingCommonDriverApi.initialize( - providerId: providerId, - vehicleId: vehicleId, - onGetToken: onGetToken, - onStatusUpdate: onStatusUpdate, - abnormalTerminationReportingEnabled: - abnormalTerminationReportingEnabled); + providerId: providerId, + vehicleId: vehicleId, + onGetToken: onGetToken, + onStatusUpdate: onStatusUpdate, + abnormalTerminationReportingEnabled: abnormalTerminationReportingEnabled, + ); } /// Returns an instance of the [RidesharingVehicleReporter], @@ -707,17 +746,16 @@ class AuthTokenContext { /// Event API implementation to receive token requests from Driver SDK. class _AuthTokenEventApiImpl implements AuthTokenEventApi { /// Basic constructor - const _AuthTokenEventApiImpl({ - this.onGetTokenEvent, - }); + const _AuthTokenEventApiImpl({this.onGetTokenEvent}); /// Callback for authentication token retrieval. final OnGetToken? onGetTokenEvent; @override Future getToken(String? taskId, String? vehicleId) async { - return onGetTokenEvent! - .call(AuthTokenContext._(taskId: taskId, vehicleId: vehicleId)); + return onGetTokenEvent!.call( + AuthTokenContext._(taskId: taskId, vehicleId: vehicleId), + ); } } @@ -739,32 +777,43 @@ class _VehicleReporterListenerApiImpl implements VehicleReporterListenerApi { @override void onDidFail( - VehicleUpdateDto vehicleUpdate, String? errorCode, String? errorMessage) { - vehicleReporterListener.onDidFail(vehicleUpdate.toVehicleUpdate(), - DriverException(code: errorCode ?? '', message: errorMessage!)); + VehicleUpdateDto vehicleUpdate, + String? errorCode, + String? errorMessage, + ) { + vehicleReporterListener.onDidFail( + vehicleUpdate.toVehicleUpdate(), + DriverException(code: errorCode ?? '', message: errorMessage!), + ); } } /// Event API implementation to receive driver status updates from Driver SDK (Android-only). class _DriverStatusListenerApiImpl implements DriverStatusListenerApi { /// Basic constructor - const _DriverStatusListenerApiImpl({ - this.onStatusUpdateEvent, - }); + const _DriverStatusListenerApiImpl({this.onStatusUpdateEvent}); /// Callback for authentication token retrieval. final OnStatusUpdate? onStatusUpdateEvent; @override - void onStatusUpdate(DriverStatusLevelDto level, DriverStatusCodeDto code, - String message, String? errorCode, String? errorMessage) { + void onStatusUpdate( + DriverStatusLevelDto level, + DriverStatusCodeDto code, + String message, + String? errorCode, + String? errorMessage, + ) { return onStatusUpdateEvent!.call( - level.toStatusLevel(), - code.toStatusCode(), - message, - errorCode != null - ? DriverException( - message: errorMessage ?? 'Unknown error.', code: errorCode) - : null); + level.toStatusLevel(), + code.toStatusCode(), + message, + errorCode != null + ? DriverException( + message: errorMessage ?? 'Unknown error.', + code: errorCode, + ) + : null, + ); } } diff --git a/lib/src/method_channel/convert/delivery_vehicle.dart b/lib/src/method_channel/convert/delivery_vehicle.dart index 1a63b67..a293824 100644 --- a/lib/src/method_channel/convert/delivery_vehicle.dart +++ b/lib/src/method_channel/convert/delivery_vehicle.dart @@ -21,12 +21,14 @@ extension ConvertDeliveryVehicleDto on DeliveryVehicleDto { /// Converts [DeliveryVehicleDto] to [DeliveryVehicle]. DeliveryVehicle toDeliveryVehicle() { return DeliveryVehicle( - providerId: providerId, - id: id, - name: name, - stops: stops - .whereType() - .map((VehicleStopDto e) => e.toVehicleStop()) - .toList()); + providerId: providerId, + id: id, + name: name, + stops: + stops + .whereType() + .map((VehicleStopDto e) => e.toVehicleStop()) + .toList(), + ); } } diff --git a/lib/src/method_channel/convert/location.dart b/lib/src/method_channel/convert/location.dart index 20aff65..9a8254b 100644 --- a/lib/src/method_channel/convert/location.dart +++ b/lib/src/method_channel/convert/location.dart @@ -22,16 +22,17 @@ extension ConvertLocation on Location { /// Converts [Location] to [LocationDto] LocationDto toDto() { return LocationDto( - accuracy: accuracy, - altitude: altitude, - elapsedRealtimeNanos: elapsedRealtimeNanos, - bearing: bearing, - isMock: isMock, - latitude: latitude, - longitude: longitude, - provider: provider, - speed: speed, - time: time); + accuracy: accuracy, + altitude: altitude, + elapsedRealtimeNanos: elapsedRealtimeNanos, + bearing: bearing, + isMock: isMock, + latitude: latitude, + longitude: longitude, + provider: provider, + speed: speed, + time: time, + ); } } @@ -41,15 +42,16 @@ extension ConvertLocationDto on LocationDto { /// Converts [LocationDto] to [Location] Location toLocation() { return Location( - accuracy: accuracy, - altitude: altitude, - elapsedRealtimeNanos: elapsedRealtimeNanos, - bearing: bearing, - isMock: isMock, - latitude: latitude, - longitude: longitude, - provider: provider, - speed: speed, - time: time); + accuracy: accuracy, + altitude: altitude, + elapsedRealtimeNanos: elapsedRealtimeNanos, + bearing: bearing, + isMock: isMock, + latitude: latitude, + longitude: longitude, + provider: provider, + speed: speed, + time: time, + ); } } diff --git a/lib/src/method_channel/convert/navigation_waypoint.dart b/lib/src/method_channel/convert/navigation_waypoint.dart index cc626e1..180a1f9 100644 --- a/lib/src/method_channel/convert/navigation_waypoint.dart +++ b/lib/src/method_channel/convert/navigation_waypoint.dart @@ -25,12 +25,12 @@ import '../method_channel.dart'; extension ConvertNavigationWaypointDto on NavigationWaypointDto { /// Converts [NavigationWaypointDto] to [NavigationWaypoint] NavigationWaypoint toNavigationWaypoint() => NavigationWaypoint( - title: title, - target: target?.toLatLng(), - placeID: placeID, - preferSameSideOfRoad: preferSameSideOfRoad, - preferredSegmentHeading: preferredSegmentHeading, - ); + title: title, + target: target?.toLatLng(), + placeID: placeID, + preferSameSideOfRoad: preferSameSideOfRoad, + preferredSegmentHeading: preferredSegmentHeading, + ); } /// [NavigationWaypoint] convert extension. @@ -38,10 +38,10 @@ extension ConvertNavigationWaypointDto on NavigationWaypointDto { extension ConvertNavigationWaypoint on NavigationWaypoint { /// Converts [NavigationWaypoint] to [NavigationWaypointDto] NavigationWaypointDto toDto() => NavigationWaypointDto( - title: title, - target: target?.toDto(), - placeID: placeID, - preferSameSideOfRoad: preferSameSideOfRoad, - preferredSegmentHeading: preferredSegmentHeading, - ); + title: title, + target: target?.toDto(), + placeID: placeID, + preferSameSideOfRoad: preferSameSideOfRoad, + preferredSegmentHeading: preferredSegmentHeading, + ); } diff --git a/lib/src/method_channel/convert/vehiclestop.dart b/lib/src/method_channel/convert/vehiclestop.dart index 070d941..af37f6c 100644 --- a/lib/src/method_channel/convert/vehiclestop.dart +++ b/lib/src/method_channel/convert/vehiclestop.dart @@ -75,10 +75,10 @@ extension ConvertVehicleStop on VehicleStop { /// Converts Google Driver [VehicleStop] to Pigeon [VehicleStopDto]. VehicleStopDto toDto() { return VehicleStopDto( - vehicleStopState: vehicleStopState.toDto(), - waypoint: waypoint?.toDto(), - taskInfoList: - taskInfoList.map((TaskInfo task) => task.toDto()).toList()); + vehicleStopState: vehicleStopState.toDto(), + waypoint: waypoint?.toDto(), + taskInfoList: taskInfoList.map((TaskInfo task) => task.toDto()).toList(), + ); } } @@ -88,10 +88,12 @@ extension ConvertVehicleStopDto on VehicleStopDto { /// Converts Pigeon [VehicleStopDto] to Google Driver [VehicleStop]. VehicleStop toVehicleStop() { return VehicleStop( - vehicleStopState: vehicleStopState.toVehicleStopState(), - waypoint: waypoint?.toNavigationWaypoint(), - taskInfoList: taskInfoList.nonNulls - .map((TaskInfoDto task) => task.toTaskInfo()) - .toList()); + vehicleStopState: vehicleStopState.toVehicleStopState(), + waypoint: waypoint?.toNavigationWaypoint(), + taskInfoList: + taskInfoList.nonNulls + .map((TaskInfoDto task) => task.toTaskInfo()) + .toList(), + ); } } diff --git a/lib/src/method_channel/convert/vehicleupdate.dart b/lib/src/method_channel/convert/vehicleupdate.dart index fd46e4e..2a5d9bf 100644 --- a/lib/src/method_channel/convert/vehicleupdate.dart +++ b/lib/src/method_channel/convert/vehicleupdate.dart @@ -21,13 +21,15 @@ extension ConvertVehicleUpdateDto on VehicleUpdateDto { /// Converts Pigeon [VehicleUpdateDto] to Google Driver [VehicleUpdate]. VehicleUpdate toVehicleUpdate() { return VehicleUpdate( - destinationWaypoint: destinationWaypoint?.toNavigationWaypoint(), - location: location?.toLatLng(), - remainingDistanceInMeters: remainingDistanceInMeters?.toInt(), - remainingTimeInSeconds: remainingTimeInSeconds != null - ? Duration(seconds: remainingTimeInSeconds!.toInt()) - : null, - route: route?.map((LatLngDto? e) => e?.toLatLng()).toList(), - vehicleState: vehicleState?.toVehicleState()); + destinationWaypoint: destinationWaypoint?.toNavigationWaypoint(), + location: location?.toLatLng(), + remainingDistanceInMeters: remainingDistanceInMeters?.toInt(), + remainingTimeInSeconds: + remainingTimeInSeconds != null + ? Duration(seconds: remainingTimeInSeconds!.toInt()) + : null, + route: route?.map((LatLngDto? e) => e?.toLatLng()).toList(), + vehicleState: vehicleState?.toVehicleState(), + ); } } diff --git a/lib/src/method_channel/messages.g.dart b/lib/src/method_channel/messages.g.dart index b87d78e..dd8e4fa 100644 --- a/lib/src/method_channel/messages.g.dart +++ b/lib/src/method_channel/messages.g.dart @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -// Autogenerated from Pigeon (v15.0.0), do not edit directly. +// Autogenerated from Pigeon (v25.3.2), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import, no_leading_underscores_for_local_identifiers @@ -29,8 +29,11 @@ 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 []; } @@ -40,6 +43,24 @@ List wrapResponse( return [error.code, error.message, error.details]; } +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]), + ); + } + if (a is Map && b is Map) { + return a.length == b.length && + a.entries.every( + (MapEntry entry) => + (b as Map).containsKey(entry.key) && + _deepEquals(entry.value, b[entry.key]), + ); + } + return a == b; +} + /// Indicates the API type for a driver. enum DriverApiTypeDto { /// Indicates the API is for a delivery driver. @@ -49,12 +70,7 @@ enum DriverApiTypeDto { ridesharing, } -enum VehicleStopStateDto { - stateUnspecified, - newStop, - enroute, - arrived, -} +enum VehicleStopStateDto { stateUnspecified, newStop, enroute, arrived } enum VehicleStateDto { /// Indicates the vehicle is not accepting new trips. @@ -64,12 +80,7 @@ enum VehicleStateDto { online, } -enum DriverStatusLevelDto { - debug, - info, - warning, - error, -} +enum DriverStatusLevelDto { debug, info, warning, error } enum DriverStatusCodeDto { defaultStatus, @@ -83,20 +94,18 @@ enum DriverStatusCodeDto { } class TaskInfoDto { - TaskInfoDto({ - required this.taskId, - required this.durationSeconds, - }); + TaskInfoDto({required this.taskId, required this.durationSeconds}); String taskId; int durationSeconds; + List _toList() { + return [taskId, durationSeconds]; + } + Object encode() { - return [ - taskId, - durationSeconds, - ]; + return _toList(); } static TaskInfoDto decode(Object result) { @@ -106,6 +115,22 @@ class TaskInfoDto { durationSeconds: result[1]! as int, ); } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + bool operator ==(Object other) { + if (other is! TaskInfoDto || other.runtimeType != runtimeType) { + return false; + } + if (identical(this, other)) { + return true; + } + return _deepEquals(encode(), other.encode()); + } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + int get hashCode => Object.hashAll(_toList()); } class VehicleStopDto { @@ -121,41 +146,53 @@ class VehicleStopDto { List taskInfoList; + List _toList() { + return [vehicleStopState, waypoint, taskInfoList]; + } + Object encode() { - return [ - vehicleStopState.index, - waypoint?.encode(), - taskInfoList, - ]; + return _toList(); } static VehicleStopDto decode(Object result) { result as List; return VehicleStopDto( - vehicleStopState: VehicleStopStateDto.values[result[0]! as int], - waypoint: result[1] != null - ? NavigationWaypointDto.decode(result[1]! as List) - : null, + vehicleStopState: result[0]! as VehicleStopStateDto, + waypoint: result[1] as NavigationWaypointDto?, taskInfoList: (result[2] as List?)!.cast(), ); } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + bool operator ==(Object other) { + if (other is! VehicleStopDto || other.runtimeType != runtimeType) { + return false; + } + if (identical(this, other)) { + return true; + } + return _deepEquals(encode(), other.encode()); + } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + int get hashCode => Object.hashAll(_toList()); } class LatLngDto { - LatLngDto({ - required this.latitude, - required this.longitude, - }); + LatLngDto({required this.latitude, required this.longitude}); double latitude; double longitude; + List _toList() { + return [latitude, longitude]; + } + Object encode() { - return [ - latitude, - longitude, - ]; + return _toList(); } static LatLngDto decode(Object result) { @@ -165,6 +202,22 @@ class LatLngDto { longitude: result[1]! as double, ); } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + bool operator ==(Object other) { + if (other is! LatLngDto || other.runtimeType != runtimeType) { + return false; + } + if (identical(this, other)) { + return true; + } + return _deepEquals(encode(), other.encode()); + } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + int get hashCode => Object.hashAll(_toList()); } class NavigationWaypointDto { @@ -186,28 +239,46 @@ class NavigationWaypointDto { int? preferredSegmentHeading; - Object encode() { + List _toList() { return [ title, - target?.encode(), + target, placeID, preferSameSideOfRoad, preferredSegmentHeading, ]; } + Object encode() { + return _toList(); + } + static NavigationWaypointDto decode(Object result) { result as List; return NavigationWaypointDto( title: result[0]! as String, - target: result[1] != null - ? LatLngDto.decode(result[1]! as List) - : null, + target: result[1] as LatLngDto?, placeID: result[2] as String?, preferSameSideOfRoad: result[3] as bool?, preferredSegmentHeading: result[4] as int?, ); } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + bool operator ==(Object other) { + if (other is! NavigationWaypointDto || other.runtimeType != runtimeType) { + return false; + } + if (identical(this, other)) { + return true; + } + return _deepEquals(encode(), other.encode()); + } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + int get hashCode => Object.hashAll(_toList()); } class LocationDto { @@ -244,7 +315,7 @@ class LocationDto { int? time; - Object encode() { + List _toList() { return [ accuracy, altitude, @@ -259,6 +330,10 @@ class LocationDto { ]; } + Object encode() { + return _toList(); + } + static LocationDto decode(Object result) { result as List; return LocationDto( @@ -274,6 +349,22 @@ class LocationDto { time: result[9] as int?, ); } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + bool operator ==(Object other) { + if (other is! LocationDto || other.runtimeType != runtimeType) { + return false; + } + if (identical(this, other)) { + return true; + } + return _deepEquals(encode(), other.encode()); + } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + int get hashCode => Object.hashAll(_toList()); } class DeliveryVehicleDto { @@ -292,13 +383,12 @@ class DeliveryVehicleDto { List stops; + List _toList() { + return [providerId, id, name, stops]; + } + Object encode() { - return [ - providerId, - id, - name, - stops, - ]; + return _toList(); } static DeliveryVehicleDto decode(Object result) { @@ -310,6 +400,22 @@ class DeliveryVehicleDto { stops: (result[3] as List?)!.cast(), ); } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + bool operator ==(Object other) { + if (other is! DeliveryVehicleDto || other.runtimeType != runtimeType) { + return false; + } + if (identical(this, other)) { + return true; + } + return _deepEquals(encode(), other.encode()); + } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + int get hashCode => Object.hashAll(_toList()); } class VehicleUpdateDto { @@ -334,41 +440,92 @@ class VehicleUpdateDto { double? remainingDistanceInMeters; - Object encode() { + List _toList() { return [ - vehicleState?.index, - location?.encode(), - destinationWaypoint?.encode(), + vehicleState, + location, + destinationWaypoint, route, remainingTimeInSeconds, remainingDistanceInMeters, ]; } + Object encode() { + return _toList(); + } + static VehicleUpdateDto decode(Object result) { result as List; return VehicleUpdateDto( - vehicleState: - result[0] != null ? VehicleStateDto.values[result[0]! as int] : null, - location: result[1] != null - ? LatLngDto.decode(result[1]! as List) - : null, - destinationWaypoint: result[2] != null - ? NavigationWaypointDto.decode(result[2]! as List) - : null, + vehicleState: result[0] as VehicleStateDto?, + location: result[1] as LatLngDto?, + destinationWaypoint: result[2] as NavigationWaypointDto?, route: (result[3] as List?)?.cast(), remainingTimeInSeconds: result[4] as double?, remainingDistanceInMeters: result[5] as double?, ); } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + bool operator ==(Object other) { + if (other is! VehicleUpdateDto || other.runtimeType != runtimeType) { + return false; + } + if (identical(this, other)) { + return true; + } + return _deepEquals(encode(), other.encode()); + } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + int get hashCode => Object.hashAll(_toList()); } -class _CommonDriverApiCodec extends StandardMessageCodec { - const _CommonDriverApiCodec(); +class _PigeonCodec extends StandardMessageCodec { + const _PigeonCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { - if (value is LocationDto) { - buffer.putUint8(128); + if (value is int) { + buffer.putUint8(4); + buffer.putInt64(value); + } else if (value is DriverApiTypeDto) { + buffer.putUint8(129); + writeValue(buffer, value.index); + } else if (value is VehicleStopStateDto) { + buffer.putUint8(130); + writeValue(buffer, value.index); + } else if (value is VehicleStateDto) { + buffer.putUint8(131); + writeValue(buffer, value.index); + } else if (value is DriverStatusLevelDto) { + buffer.putUint8(132); + writeValue(buffer, value.index); + } else if (value is DriverStatusCodeDto) { + buffer.putUint8(133); + writeValue(buffer, value.index); + } else if (value is TaskInfoDto) { + buffer.putUint8(134); + writeValue(buffer, value.encode()); + } else if (value is VehicleStopDto) { + buffer.putUint8(135); + writeValue(buffer, value.encode()); + } else if (value is LatLngDto) { + buffer.putUint8(136); + writeValue(buffer, value.encode()); + } else if (value is NavigationWaypointDto) { + buffer.putUint8(137); + writeValue(buffer, value.encode()); + } else if (value is LocationDto) { + buffer.putUint8(138); + writeValue(buffer, value.encode()); + } else if (value is DeliveryVehicleDto) { + buffer.putUint8(139); + writeValue(buffer, value.encode()); + } else if (value is VehicleUpdateDto) { + buffer.putUint8(140); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); @@ -378,8 +535,35 @@ class _CommonDriverApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 129: + final int? value = readValue(buffer) as int?; + return value == null ? null : DriverApiTypeDto.values[value]; + case 130: + final int? value = readValue(buffer) as int?; + return value == null ? null : VehicleStopStateDto.values[value]; + case 131: + final int? value = readValue(buffer) as int?; + return value == null ? null : VehicleStateDto.values[value]; + case 132: + final int? value = readValue(buffer) as int?; + return value == null ? null : DriverStatusLevelDto.values[value]; + case 133: + final int? value = readValue(buffer) as int?; + return value == null ? null : DriverStatusCodeDto.values[value]; + case 134: + return TaskInfoDto.decode(readValue(buffer)!); + case 135: + return VehicleStopDto.decode(readValue(buffer)!); + case 136: + return LatLngDto.decode(readValue(buffer)!); + case 137: + return NavigationWaypointDto.decode(readValue(buffer)!); + case 138: return LocationDto.decode(readValue(buffer)!); + case 139: + return DeliveryVehicleDto.decode(readValue(buffer)!); + case 140: + return VehicleUpdateDto.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } @@ -390,37 +574,49 @@ class CommonDriverApi { /// Constructor for [CommonDriverApi]. 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. - CommonDriverApi({BinaryMessenger? binaryMessenger}) - : __pigeon_binaryMessenger = binaryMessenger; - final BinaryMessenger? __pigeon_binaryMessenger; - - static const MessageCodec pigeonChannelCodec = - _CommonDriverApiCodec(); - - Future initialize(DriverApiTypeDto type, String providerId, - String vehicleId, bool abnormalTerminationReportingEnabled) async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize'; - final BasicMessageChannel __pigeon_channel = + CommonDriverApi({ + 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 initialize( + DriverApiTypeDto type, + String providerId, + String vehicleId, + bool abnormalTerminationReportingEnabled, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [ + type, + providerId, + vehicleId, + abnormalTerminationReportingEnabled, + ], ); - final List? __pigeon_replyList = await __pigeon_channel - .send([ - type.index, - providerId, - vehicleId, - abnormalTerminationReportingEnabled - ]) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { return; @@ -428,140 +624,157 @@ class CommonDriverApi { } Future isInitialized(DriverApiTypeDto type) async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isInitialized'; - final BasicMessageChannel __pigeon_channel = + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isInitialized$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [type], ); - final List? __pigeon_replyList = - await __pigeon_channel.send([type.index]) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (__pigeon_replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (__pigeon_replyList[0] as bool?)!; + return (pigeonVar_replyList[0] as bool?)!; } } Future getProviderId(DriverApiTypeDto type) async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getProviderId'; - final BasicMessageChannel __pigeon_channel = + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getProviderId$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [type], ); - final List? __pigeon_replyList = - await __pigeon_channel.send([type.index]) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (__pigeon_replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (__pigeon_replyList[0] as String?)!; + return (pigeonVar_replyList[0] as String?)!; } } Future getVehicleId(DriverApiTypeDto type) async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getVehicleId'; - final BasicMessageChannel __pigeon_channel = + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getVehicleId$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [type], ); - final List? __pigeon_replyList = - await __pigeon_channel.send([type.index]) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (__pigeon_replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (__pigeon_replyList[0] as String?)!; + return (pigeonVar_replyList[0] as String?)!; } } Future isLocationTrackingEnabled(DriverApiTypeDto type) async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isLocationTrackingEnabled'; - final BasicMessageChannel __pigeon_channel = + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isLocationTrackingEnabled$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [type], ); - final List? __pigeon_replyList = - await __pigeon_channel.send([type.index]) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (__pigeon_replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (__pigeon_replyList[0] as bool?)!; + return (pigeonVar_replyList[0] as bool?)!; } } Future setLocationTrackingEnabled( - DriverApiTypeDto type, bool enabled) async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationTrackingEnabled'; - final BasicMessageChannel __pigeon_channel = + DriverApiTypeDto type, + bool enabled, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationTrackingEnabled$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [type, enabled], ); - final List? __pigeon_replyList = await __pigeon_channel - .send([type.index, enabled]) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { return; @@ -569,53 +782,61 @@ class CommonDriverApi { } Future getLocationReportingIntervalMillis(DriverApiTypeDto type) async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getLocationReportingIntervalMillis'; - final BasicMessageChannel __pigeon_channel = + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getLocationReportingIntervalMillis$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [type], ); - final List? __pigeon_replyList = - await __pigeon_channel.send([type.index]) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (__pigeon_replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (__pigeon_replyList[0] as int?)!; + return (pigeonVar_replyList[0] as int?)!; } } Future setLocationReportingIntervalMillis( - DriverApiTypeDto type, int milliseconds) async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationReportingIntervalMillis'; - final BasicMessageChannel __pigeon_channel = + DriverApiTypeDto type, + int milliseconds, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationReportingIntervalMillis$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [type, milliseconds], ); - final List? __pigeon_replyList = await __pigeon_channel - .send([type.index, milliseconds]) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { return; @@ -623,23 +844,26 @@ class CommonDriverApi { } Future dispose(DriverApiTypeDto type) async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.dispose'; - final BasicMessageChannel __pigeon_channel = + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.dispose$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [type], ); - final List? __pigeon_replyList = - await __pigeon_channel.send([type.index]) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { return; @@ -647,53 +871,61 @@ class CommonDriverApi { } Future getDriverSdkVersion(DriverApiTypeDto type) async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getDriverSdkVersion'; - final BasicMessageChannel __pigeon_channel = + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getDriverSdkVersion$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [type], ); - final List? __pigeon_replyList = - await __pigeon_channel.send([type.index]) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (__pigeon_replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (__pigeon_replyList[0] as String?)!; + return (pigeonVar_replyList[0] as String?)!; } } Future setSupplementalLocation( - DriverApiTypeDto type, LocationDto location) async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setSupplementalLocation'; - final BasicMessageChannel __pigeon_channel = + DriverApiTypeDto type, + LocationDto location, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setSupplementalLocation$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [type, location], ); - final List? __pigeon_replyList = await __pigeon_channel - .send([type.index, location]) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { return; @@ -701,232 +933,203 @@ class CommonDriverApi { } } -class _DeliveryDriverApiCodec extends StandardMessageCodec { - const _DeliveryDriverApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is DeliveryVehicleDto) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else if (value is LatLngDto) { - buffer.putUint8(129); - writeValue(buffer, value.encode()); - } else if (value is NavigationWaypointDto) { - buffer.putUint8(130); - writeValue(buffer, value.encode()); - } else if (value is TaskInfoDto) { - buffer.putUint8(131); - writeValue(buffer, value.encode()); - } else if (value is VehicleStopDto) { - buffer.putUint8(132); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } - } - - @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return DeliveryVehicleDto.decode(readValue(buffer)!); - case 129: - return LatLngDto.decode(readValue(buffer)!); - case 130: - return NavigationWaypointDto.decode(readValue(buffer)!); - case 131: - return TaskInfoDto.decode(readValue(buffer)!); - case 132: - return VehicleStopDto.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } - } -} - class DeliveryDriverApi { /// Constructor for [DeliveryDriverApi]. 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. - DeliveryDriverApi({BinaryMessenger? binaryMessenger}) - : __pigeon_binaryMessenger = binaryMessenger; - final BinaryMessenger? __pigeon_binaryMessenger; - - static const MessageCodec pigeonChannelCodec = - _DeliveryDriverApiCodec(); - - Future> arrivedAtStop() async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.arrivedAtStop'; - final BasicMessageChannel __pigeon_channel = + DeliveryDriverApi({ + 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> arrivedAtStop() async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.arrivedAtStop$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, - ); - final List? __pigeon_replyList = - await __pigeon_channel.send(null) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (__pigeon_replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (__pigeon_replyList[0] as List?)!.cast(); + return (pigeonVar_replyList[0] as List?)!.cast(); } } - Future> completedStop() async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.completedStop'; - final BasicMessageChannel __pigeon_channel = + Future> completedStop() async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.completedStop$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, - ); - final List? __pigeon_replyList = - await __pigeon_channel.send(null) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (__pigeon_replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (__pigeon_replyList[0] as List?)!.cast(); + return (pigeonVar_replyList[0] as List?)!.cast(); } } - Future> enrouteToNextStop() async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.enrouteToNextStop'; - final BasicMessageChannel __pigeon_channel = + Future> enrouteToNextStop() async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.enrouteToNextStop$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, - ); - final List? __pigeon_replyList = - await __pigeon_channel.send(null) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (__pigeon_replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (__pigeon_replyList[0] as List?)!.cast(); + return (pigeonVar_replyList[0] as List?)!.cast(); } } - Future> getRemainingVehicleStops() async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.getRemainingVehicleStops'; - final BasicMessageChannel __pigeon_channel = + Future> getRemainingVehicleStops() async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.getRemainingVehicleStops$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, - ); - final List? __pigeon_replyList = - await __pigeon_channel.send(null) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (__pigeon_replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (__pigeon_replyList[0] as List?)!.cast(); + return (pigeonVar_replyList[0] as List?)!.cast(); } } - Future> setVehicleStops( - List stops) async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.setVehicleStops'; - final BasicMessageChannel __pigeon_channel = + Future> setVehicleStops( + List stops, + ) async { + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.setVehicleStops$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [stops], ); - final List? __pigeon_replyList = - await __pigeon_channel.send([stops]) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (__pigeon_replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (__pigeon_replyList[0] as List?)!.cast(); + return (pigeonVar_replyList[0] as List?)!.cast(); } } Future getDeliveryVehicle() async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.getDeliveryVehicle'; - final BasicMessageChannel __pigeon_channel = + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.getDeliveryVehicle$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, - ); - final List? __pigeon_replyList = - await __pigeon_channel.send(null) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (__pigeon_replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (__pigeon_replyList[0] as DeliveryVehicleDto?)!; + return (pigeonVar_replyList[0] as DeliveryVehicleDto?)!; } } } @@ -935,31 +1138,39 @@ class RidesharingDriverApi { /// Constructor for [RidesharingDriverApi]. 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. - RidesharingDriverApi({BinaryMessenger? binaryMessenger}) - : __pigeon_binaryMessenger = binaryMessenger; - final BinaryMessenger? __pigeon_binaryMessenger; + RidesharingDriverApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; + final BinaryMessenger? pigeonVar_binaryMessenger; - static const MessageCodec pigeonChannelCodec = - StandardMessageCodec(); + static const MessageCodec pigeonChannelCodec = _PigeonCodec(); + + final String pigeonVar_messageChannelSuffix; Future setVehicleState(VehicleStateDto state) async { - const String __pigeon_channelName = - 'dev.flutter.pigeon.google_driver_flutter.RidesharingDriverApi.setVehicleState'; - final BasicMessageChannel __pigeon_channel = + final String pigeonVar_channelName = + 'dev.flutter.pigeon.google_driver_flutter.RidesharingDriverApi.setVehicleState$pigeonVar_messageChannelSuffix'; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( - __pigeon_channelName, - pigeonChannelCodec, - binaryMessenger: __pigeon_binaryMessenger, + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [state], ); - final List? __pigeon_replyList = - await __pigeon_channel.send([state.index]) as List?; - if (__pigeon_replyList == null) { - throw _createConnectionError(__pigeon_channelName); - } else if (__pigeon_replyList.length > 1) { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: __pigeon_replyList[0]! as String, - message: __pigeon_replyList[1] as String?, - details: __pigeon_replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { return; @@ -968,25 +1179,32 @@ class RidesharingDriverApi { } abstract class AuthTokenEventApi { - static const MessageCodec pigeonChannelCodec = - StandardMessageCodec(); + static const MessageCodec pigeonChannelCodec = _PigeonCodec(); Future getToken(String? taskId, String? vehicleId); - static void setup(AuthTokenEventApi? api, - {BinaryMessenger? binaryMessenger}) { + static void setUp( + AuthTokenEventApi? api, { + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) { + messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.AuthTokenEventApi.getToken', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.AuthTokenEventApi.getToken$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { - __pigeon_channel.setMessageHandler(null); + pigeonVar_channel.setMessageHandler(null); } else { - __pigeon_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.AuthTokenEventApi.getToken was null.'); + pigeonVar_channel.setMessageHandler((Object? message) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.AuthTokenEventApi.getToken was null.', + ); final List args = (message as List?)!; final String? arg_taskId = (args[0] as String?); final String? arg_vehicleId = (args[1] as String?); @@ -997,7 +1215,8 @@ abstract class AuthTokenEventApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1005,72 +1224,46 @@ abstract class AuthTokenEventApi { } } -class _VehicleReporterListenerApiCodec extends StandardMessageCodec { - const _VehicleReporterListenerApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is LatLngDto) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else if (value is LatLngDto) { - buffer.putUint8(129); - writeValue(buffer, value.encode()); - } else if (value is NavigationWaypointDto) { - buffer.putUint8(130); - writeValue(buffer, value.encode()); - } else if (value is VehicleUpdateDto) { - buffer.putUint8(131); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } - } - - @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return LatLngDto.decode(readValue(buffer)!); - case 129: - return LatLngDto.decode(readValue(buffer)!); - case 130: - return NavigationWaypointDto.decode(readValue(buffer)!); - case 131: - return VehicleUpdateDto.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } - } -} - abstract class VehicleReporterListenerApi { - static const MessageCodec pigeonChannelCodec = - _VehicleReporterListenerApiCodec(); + static const MessageCodec pigeonChannelCodec = _PigeonCodec(); void onDidSucceed(VehicleUpdateDto vehicleUpdate); void onDidFail( - VehicleUpdateDto vehicleUpdate, String errorCode, String errorMessage); + VehicleUpdateDto vehicleUpdate, + String errorCode, + String errorMessage, + ); - static void setup(VehicleReporterListenerApi? api, - {BinaryMessenger? binaryMessenger}) { + static void setUp( + VehicleReporterListenerApi? api, { + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) { + messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidSucceed', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidSucceed$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { - __pigeon_channel.setMessageHandler(null); + pigeonVar_channel.setMessageHandler(null); } else { - __pigeon_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidSucceed was null.'); + pigeonVar_channel.setMessageHandler((Object? message) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidSucceed was null.', + ); final List args = (message as List?)!; final VehicleUpdateDto? arg_vehicleUpdate = (args[0] as VehicleUpdateDto?); - assert(arg_vehicleUpdate != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidSucceed was null, expected non-null VehicleUpdateDto.'); + assert( + arg_vehicleUpdate != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidSucceed was null, expected non-null VehicleUpdateDto.', + ); try { api.onDidSucceed(arg_vehicleUpdate!); return wrapResponse(empty: true); @@ -1078,43 +1271,57 @@ abstract class VehicleReporterListenerApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidFail', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidFail$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { - __pigeon_channel.setMessageHandler(null); + pigeonVar_channel.setMessageHandler(null); } else { - __pigeon_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidFail was null.'); + pigeonVar_channel.setMessageHandler((Object? message) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidFail was null.', + ); final List args = (message as List?)!; final VehicleUpdateDto? arg_vehicleUpdate = (args[0] as VehicleUpdateDto?); - assert(arg_vehicleUpdate != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidFail was null, expected non-null VehicleUpdateDto.'); + assert( + arg_vehicleUpdate != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidFail was null, expected non-null VehicleUpdateDto.', + ); final String? arg_errorCode = (args[1] as String?); - assert(arg_errorCode != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidFail was null, expected non-null String.'); + assert( + arg_errorCode != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidFail was null, expected non-null String.', + ); final String? arg_errorMessage = (args[2] as String?); - assert(arg_errorMessage != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidFail was null, expected non-null String.'); + assert( + arg_errorMessage != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.VehicleReporterListenerApi.onDidFail was null, expected non-null String.', + ); try { api.onDidFail( - arg_vehicleUpdate!, arg_errorCode!, arg_errorMessage!); + arg_vehicleUpdate!, + arg_errorCode!, + arg_errorMessage!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -1123,51 +1330,73 @@ abstract class VehicleReporterListenerApi { } abstract class DriverStatusListenerApi { - static const MessageCodec pigeonChannelCodec = - StandardMessageCodec(); - - void onStatusUpdate(DriverStatusLevelDto level, DriverStatusCodeDto code, - String message, String? errorCode, String? errorMessage); + static const MessageCodec pigeonChannelCodec = _PigeonCodec(); + + void onStatusUpdate( + DriverStatusLevelDto level, + DriverStatusCodeDto code, + String message, + String? errorCode, + String? errorMessage, + ); - static void setup(DriverStatusListenerApi? api, - {BinaryMessenger? binaryMessenger}) { + static void setUp( + DriverStatusListenerApi? api, { + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) { + messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.DriverStatusListenerApi.onStatusUpdate', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.DriverStatusListenerApi.onStatusUpdate$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { - __pigeon_channel.setMessageHandler(null); + pigeonVar_channel.setMessageHandler(null); } else { - __pigeon_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.DriverStatusListenerApi.onStatusUpdate was null.'); + pigeonVar_channel.setMessageHandler((Object? message) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.DriverStatusListenerApi.onStatusUpdate was null.', + ); final List args = (message as List?)!; - final DriverStatusLevelDto? arg_level = args[0] == null - ? null - : DriverStatusLevelDto.values[args[0]! as int]; - assert(arg_level != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.DriverStatusListenerApi.onStatusUpdate was null, expected non-null DriverStatusLevelDto.'); - final DriverStatusCodeDto? arg_code = args[1] == null - ? null - : DriverStatusCodeDto.values[args[1]! as int]; - assert(arg_code != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.DriverStatusListenerApi.onStatusUpdate was null, expected non-null DriverStatusCodeDto.'); + final DriverStatusLevelDto? arg_level = + (args[0] as DriverStatusLevelDto?); + assert( + arg_level != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.DriverStatusListenerApi.onStatusUpdate was null, expected non-null DriverStatusLevelDto.', + ); + final DriverStatusCodeDto? arg_code = + (args[1] as DriverStatusCodeDto?); + assert( + arg_code != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.DriverStatusListenerApi.onStatusUpdate was null, expected non-null DriverStatusCodeDto.', + ); final String? arg_message = (args[2] as String?); - assert(arg_message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.DriverStatusListenerApi.onStatusUpdate was null, expected non-null String.'); + assert( + arg_message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.DriverStatusListenerApi.onStatusUpdate was null, expected non-null String.', + ); final String? arg_errorCode = (args[3] as String?); final String? arg_errorMessage = (args[4] as String?); try { - api.onStatusUpdate(arg_level!, arg_code!, arg_message!, - arg_errorCode, arg_errorMessage); + api.onStatusUpdate( + arg_level!, + arg_code!, + arg_message!, + arg_errorCode, + arg_errorMessage, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } diff --git a/lib/src/types/delivery_vehicle.dart b/lib/src/types/delivery_vehicle.dart index bd64182..6869c9d 100644 --- a/lib/src/types/delivery_vehicle.dart +++ b/lib/src/types/delivery_vehicle.dart @@ -23,11 +23,12 @@ import '../../google_driver_flutter.dart'; @immutable class DeliveryVehicle { /// Constructs a [DeliveryVehicle] instance. - const DeliveryVehicle( - {required this.providerId, - required this.id, - required this.name, - required this.stops}); + const DeliveryVehicle({ + required this.providerId, + required this.id, + required this.name, + required this.stops, + }); /// Returns the unique identifier for this provider. final String providerId; diff --git a/lib/src/types/location.dart b/lib/src/types/location.dart index 4b4506f..d3873d4 100644 --- a/lib/src/types/location.dart +++ b/lib/src/types/location.dart @@ -21,17 +21,18 @@ import 'package:flutter/foundation.dart'; @immutable class Location { /// Constructs a [Location] instance. - const Location( - {this.accuracy, - this.altitude, - this.elapsedRealtimeNanos, - this.bearing, - this.isMock, - this.latitude, - this.longitude, - this.provider, - this.speed, - this.time}); + const Location({ + this.accuracy, + this.altitude, + this.elapsedRealtimeNanos, + this.bearing, + this.isMock, + this.latitude, + this.longitude, + this.provider, + this.speed, + this.time, + }); /// Horizontal accuracy in meters of this location. final double? accuracy; diff --git a/lib/src/types/statuslistener.dart b/lib/src/types/statuslistener.dart index a46cafd..70e45f7 100644 --- a/lib/src/types/statuslistener.dart +++ b/lib/src/types/statuslistener.dart @@ -29,7 +29,7 @@ enum DriverStatusLevel { warning, /// Error messages. - error + error, } /// The driver status code of the driver update. @@ -62,5 +62,5 @@ enum DriverStatusCode { permissionDenied, /// Traveled route error. - traveledRouteError + traveledRouteError, } diff --git a/lib/src/types/vehiclestop.dart b/lib/src/types/vehiclestop.dart index 42a3e70..9a9f649 100644 --- a/lib/src/types/vehiclestop.dart +++ b/lib/src/types/vehiclestop.dart @@ -19,10 +19,7 @@ import 'package:google_navigation_flutter/google_navigation_flutter.dart'; /// {@category Delivery Driver} class TaskInfo { /// Constructs a [TaskInfo] instance. - TaskInfo({ - required this.taskId, - required this.durationSeconds, - }); + TaskInfo({required this.taskId, required this.durationSeconds}); /// Returns the unique identifier of the task. final String taskId; diff --git a/melos.yaml b/melos.yaml index ca60ba7..a95b08a 100644 --- a/melos.yaml +++ b/melos.yaml @@ -64,10 +64,10 @@ scripts: format:ios: run: | - swiftformat --quiet . + swift-format -r -i --parallel . description: | - Formats the code of iOS package with swiftformat. - - Requires `swiftformat` (can be installed via Brew on macOS). + Formats the code of iOS package with swift-format. + - Requires `swift-format` (can be installed via Brew). format:android: run: | diff --git a/pigeons/messages.dart b/pigeons/messages.dart index 1d0a9bc..bba7d68 100644 --- a/pigeons/messages.dart +++ b/pigeons/messages.dart @@ -26,7 +26,6 @@ import 'package:pigeon/pigeon.dart'; copyrightHeader: 'pigeons/copyright.txt', ), ) - /// Indicates the API type for a driver. enum DriverApiTypeDto { /// Indicates the API is for a delivery driver. @@ -37,21 +36,13 @@ enum DriverApiTypeDto { } class TaskInfoDto { - TaskInfoDto({ - required this.taskId, - required this.durationSeconds, - }); + TaskInfoDto({required this.taskId, required this.durationSeconds}); final String taskId; final int durationSeconds; } -enum VehicleStopStateDto { - stateUnspecified, - newStop, - enroute, - arrived, -} +enum VehicleStopStateDto { stateUnspecified, newStop, enroute, arrived } class VehicleStopDto { VehicleStopDto({ @@ -66,10 +57,7 @@ class VehicleStopDto { } class LatLngDto { - const LatLngDto({ - required this.latitude, - required this.longitude, - }); + const LatLngDto({required this.latitude, required this.longitude}); final double latitude; final double longitude; @@ -100,17 +88,18 @@ enum VehicleStateDto { } class LocationDto { - LocationDto( - {this.accuracy, - this.altitude, - this.elapsedRealtimeNanos, - this.bearing, - this.isMock, - this.latitude, - this.longitude, - this.provider, - this.speed, - this.time}); + LocationDto({ + this.accuracy, + this.altitude, + this.elapsedRealtimeNanos, + this.bearing, + this.isMock, + this.latitude, + this.longitude, + this.provider, + this.speed, + this.time, + }); final double? accuracy; final double? altitude; final int? elapsedRealtimeNanos; @@ -124,11 +113,12 @@ class LocationDto { } class DeliveryVehicleDto { - DeliveryVehicleDto( - {required this.providerId, - required this.id, - required this.name, - required this.stops}); + DeliveryVehicleDto({ + required this.providerId, + required this.id, + required this.name, + required this.stops, + }); final String providerId; final String id; final String name; @@ -137,8 +127,12 @@ class DeliveryVehicleDto { @HostApi(dartHostTestHandler: 'TestCommonDriverApi') abstract class CommonDriverApi { - void initialize(DriverApiTypeDto type, String providerId, String vehicleId, - bool abnormalTerminationReportingEnabled); + void initialize( + DriverApiTypeDto type, + String providerId, + String vehicleId, + bool abnormalTerminationReportingEnabled, + ); bool isInitialized(DriverApiTypeDto type); String getProviderId(DriverApiTypeDto type); String getVehicleId(DriverApiTypeDto type); @@ -146,7 +140,9 @@ abstract class CommonDriverApi { void setLocationTrackingEnabled(DriverApiTypeDto type, bool enabled); int getLocationReportingIntervalMillis(DriverApiTypeDto type); void setLocationReportingIntervalMillis( - DriverApiTypeDto type, int milliseconds); + DriverApiTypeDto type, + int milliseconds, + ); void dispose(DriverApiTypeDto type); String getDriverSdkVersion(DriverApiTypeDto type); void setSupplementalLocation(DriverApiTypeDto type, LocationDto location); @@ -201,7 +197,10 @@ class VehicleUpdateDto { abstract class VehicleReporterListenerApi { void onDidSucceed(VehicleUpdateDto vehicleUpdate); void onDidFail( - VehicleUpdateDto vehicleUpdate, String errorCode, String errorMessage); + VehicleUpdateDto vehicleUpdate, + String errorCode, + String errorMessage, + ); } enum DriverStatusLevelDto { debug, info, warning, error } @@ -214,11 +213,16 @@ enum DriverStatusCodeDto { permissionDenied, serviceError, fileAccessError, - traveledRouteError + traveledRouteError, } @FlutterApi() abstract class DriverStatusListenerApi { - void onStatusUpdate(DriverStatusLevelDto level, DriverStatusCodeDto code, - String message, String? errorCode, String? errorMessage); + void onStatusUpdate( + DriverStatusLevelDto level, + DriverStatusCodeDto code, + String message, + String? errorCode, + String? errorMessage, + ); } diff --git a/pubspec.yaml b/pubspec.yaml index dd953a1..a1ad888 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -18,22 +18,22 @@ version: 0.3.0-beta publish_to: none environment: - sdk: ^3.4.0 - flutter: ">=3.22.1" + sdk: ^3.7.0 + flutter: ">=3.29.0" dependencies: flutter: sdk: flutter - google_navigation_flutter: ^0.3.0 + google_navigation_flutter: ^0.6.2 dev_dependencies: build_runner: ^2.4.6 - flutter_lints: ^3.0.1 + flutter_lints: ^5.0.0 flutter_test: sdk: flutter - melos: ^6.0.0 - mockito: 5.4.4 - pigeon: 15.0.0 + melos: ^6.3.2 + mockito: 5.4.6 + pigeon: 25.3.2 flutter: plugin: diff --git a/test/google_driver_flutter_test.dart b/test/google_driver_flutter_test.dart index 198c362..cfaf9c7 100644 --- a/test/google_driver_flutter_test.dart +++ b/test/google_driver_flutter_test.dart @@ -32,12 +32,12 @@ void main() { late MockTestCommonDriverApi mockedCommonDriverApi; setUp(() { mockedCommonDriverApi = MockTestCommonDriverApi(); - TestCommonDriverApi.setup(mockedCommonDriverApi); + TestCommonDriverApi.setUp(mockedCommonDriverApi); }); for (final DriverApiType driverApiType in [ DriverApiType.delivery, - DriverApiType.ridesharing + DriverApiType.ridesharing, ]) { group('Common API $driverApiType', () { const String providerIdIn = 'Foo'; @@ -53,12 +53,12 @@ void main() { publicCommonDriverApi = DeliveryDriver.commonDriverApi; mockedDeliveryDriverApi = MockTestDeliveryDriverApi(); vehicleReporter = DeliveryDriver.vehicleReporter; - TestDeliveryDriverApi.setup(mockedDeliveryDriverApi); + TestDeliveryDriverApi.setUp(mockedDeliveryDriverApi); } else if (driverApiType == DriverApiType.ridesharing) { publicCommonDriverApi = RidesharingDriver.commonDriverApi; mockedRidesharingDriverApi = MockTestRidesharingDriverApi(); vehicleReporter = RidesharingDriver.vehicleReporter; - TestRidesharingDriverApi.setup(mockedRidesharingDriverApi); + TestRidesharingDriverApi.setUp(mockedRidesharingDriverApi); } else { assert(false, 'Unknown driverApiType: $driverApiType'); } @@ -66,14 +66,21 @@ void main() { test('initialize', () async { await publicCommonDriverApi.initialize( - providerId: providerIdIn, - vehicleId: vehicleIdIn, - onGetToken: (AuthTokenContext context) => Future.value(''), - abnormalTerminationReportingEnabled: true); + providerId: providerIdIn, + vehicleId: vehicleIdIn, + onGetToken: (AuthTokenContext context) => Future.value(''), + abnormalTerminationReportingEnabled: true, + ); // initialize. - final VerificationResult result = verify(mockedCommonDriverApi - .initialize(captureAny, captureAny, captureAny, captureAny)); + final VerificationResult result = verify( + mockedCommonDriverApi.initialize( + captureAny, + captureAny, + captureAny, + captureAny, + ), + ); final String providerIdOut = result.captured[1] as String; final String vehicleIdOut = result.captured[2] as String; final bool abnormalTerminationReportingEnabledOut = @@ -86,83 +93,107 @@ void main() { }); test('getProviderId', () async { // getProviderId. - when(mockedCommonDriverApi.getProviderId(any)) - .thenAnswer((Invocation _) => providerIdIn); + when( + mockedCommonDriverApi.getProviderId(any), + ).thenAnswer((Invocation _) => providerIdIn); final String providerIdOut = await publicCommonDriverApi.getProviderId(); - final VerificationResult result = - verify(mockedCommonDriverApi.getProviderId(captureAny)); + final VerificationResult result = verify( + mockedCommonDriverApi.getProviderId(captureAny), + ); expectDriverApiType(driverApiType, result); expect(providerIdIn, providerIdOut); }); test('getVehicleId', () async { // getVehicleId. - when(mockedCommonDriverApi.getVehicleId(any)) - .thenAnswer((Invocation _) => vehicleIdIn); + when( + mockedCommonDriverApi.getVehicleId(any), + ).thenAnswer((Invocation _) => vehicleIdIn); final String vehicleIdOut = await publicCommonDriverApi.getVehicleId(); - final VerificationResult result = - verify(mockedCommonDriverApi.getVehicleId(captureAny)); + final VerificationResult result = verify( + mockedCommonDriverApi.getVehicleId(captureAny), + ); expectDriverApiType(driverApiType, result); expect(vehicleIdIn, vehicleIdOut); }); test('getDriverSdkVersion', () async { // getDriverSdkVersion. const String sdkVersionIn = '1.0.0'; - when(mockedCommonDriverApi.getDriverSdkVersion(any)) - .thenAnswer((Invocation _) => sdkVersionIn); + when( + mockedCommonDriverApi.getDriverSdkVersion(any), + ).thenAnswer((Invocation _) => sdkVersionIn); final String sdkVersionOut = await publicCommonDriverApi.getDriverSdkVersion(); - final VerificationResult result = - verify(mockedCommonDriverApi.getDriverSdkVersion(captureAny)); + final VerificationResult result = verify( + mockedCommonDriverApi.getDriverSdkVersion(captureAny), + ); expectDriverApiType(driverApiType, result); expect(sdkVersionOut, sdkVersionIn); }); test('setLocationTrackingEnabled', () async { await vehicleReporter.setLocationTrackingEnabled(true); - final VerificationResult result = verify(mockedCommonDriverApi - .setLocationTrackingEnabled(captureAny, captureAny)); + final VerificationResult result = verify( + mockedCommonDriverApi.setLocationTrackingEnabled( + captureAny, + captureAny, + ), + ); expectDriverApiType(driverApiType, result); expect(result.captured[1] as bool, true); }); test('setLocationTrackingEnabled', () async { await vehicleReporter.setLocationTrackingEnabled(false); - final VerificationResult result = verify(mockedCommonDriverApi - .setLocationTrackingEnabled(captureAny, captureAny)); + final VerificationResult result = verify( + mockedCommonDriverApi.setLocationTrackingEnabled( + captureAny, + captureAny, + ), + ); expectDriverApiType(driverApiType, result); expect(result.captured[1] as bool, false); }); test('isLocationTrackingEnabled', () async { - when(mockedCommonDriverApi.isLocationTrackingEnabled(any)) - .thenAnswer((Invocation _) => true); + when( + mockedCommonDriverApi.isLocationTrackingEnabled(any), + ).thenAnswer((Invocation _) => true); await vehicleReporter.isLocationTrackingEnabled(); - final VerificationResult result = - verify(mockedCommonDriverApi.isLocationTrackingEnabled(captureAny)); + final VerificationResult result = verify( + mockedCommonDriverApi.isLocationTrackingEnabled(captureAny), + ); expectDriverApiType(driverApiType, result); }); test('setLocationReportingInterval', () async { const int reportingIntervalIn = 12000; await vehicleReporter.setLocationReportingInterval( - const Duration(milliseconds: reportingIntervalIn)); - final VerificationResult result = verify(mockedCommonDriverApi - .setLocationReportingIntervalMillis(captureAny, captureAny)); + const Duration(milliseconds: reportingIntervalIn), + ); + final VerificationResult result = verify( + mockedCommonDriverApi.setLocationReportingIntervalMillis( + captureAny, + captureAny, + ), + ); expectDriverApiType(driverApiType, result); expect(result.captured[1] as int, reportingIntervalIn); }); test('getLocationReportingInterval', () async { const int reportingIntervalIn = 12000; - when(mockedCommonDriverApi.getLocationReportingIntervalMillis(any)) - .thenAnswer((Invocation _) => reportingIntervalIn); + when( + mockedCommonDriverApi.getLocationReportingIntervalMillis(any), + ).thenAnswer((Invocation _) => reportingIntervalIn); final Duration reportingIntervalOut = await vehicleReporter.getLocationReportingInterval(); - final VerificationResult result = verify(mockedCommonDriverApi - .getLocationReportingIntervalMillis(captureAny)); + final VerificationResult result = verify( + mockedCommonDriverApi.getLocationReportingIntervalMillis(captureAny), + ); expectDriverApiType(driverApiType, result); expect(reportingIntervalIn, reportingIntervalOut.inMilliseconds); }); test('dispose', () async { await publicCommonDriverApi.dispose(); - final VerificationResult result = - verify(mockedCommonDriverApi.dispose(captureAny)); + final VerificationResult result = verify( + mockedCommonDriverApi.dispose(captureAny), + ); expectDriverApiType(driverApiType, result); }); }); @@ -170,6 +201,8 @@ void main() { } void expectDriverApiType( - DriverApiType driverApiType, VerificationResult result) { + DriverApiType driverApiType, + VerificationResult result, +) { expect(driverApiType.toDto(), result.captured[0] as DriverApiTypeDto); } diff --git a/test/google_driver_flutter_test.mocks.dart b/test/google_driver_flutter_test.mocks.dart index 005a398..194a76a 100644 --- a/test/google_driver_flutter_test.mocks.dart +++ b/test/google_driver_flutter_test.mocks.dart @@ -1,4 +1,4 @@ -// Copyright 2024 Google LLC +// Copyright 2025 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.6 from annotations // in google_driver_flutter/test/google_driver_flutter_test.dart. // Do not manually edit this file. @@ -34,6 +34,7 @@ import 'messages_test.g.dart' as _i3; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types @@ -41,13 +42,8 @@ import 'messages_test.g.dart' as _i3; class _FakeDeliveryVehicleDto_0 extends _i1.SmartFake implements _i2.DeliveryVehicleDto { - _FakeDeliveryVehicleDto_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeDeliveryVehicleDto_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [TestCommonDriverApi]. @@ -65,150 +61,106 @@ class MockTestCommonDriverApi extends _i1.Mock String? providerId, String? vehicleId, bool? abnormalTerminationReportingEnabled, - ) => - super.noSuchMethod( - Invocation.method( - #initialize, - [ - type, - providerId, - vehicleId, - abnormalTerminationReportingEnabled, - ], - ), - returnValueForMissingStub: null, - ); - - @override - bool isInitialized(_i2.DriverApiTypeDto? type) => (super.noSuchMethod( - Invocation.method( - #isInitialized, - [type], - ), - returnValue: false, - ) as bool); + ) => super.noSuchMethod( + Invocation.method(#initialize, [ + type, + providerId, + vehicleId, + abnormalTerminationReportingEnabled, + ]), + returnValueForMissingStub: null, + ); + + @override + bool isInitialized(_i2.DriverApiTypeDto? type) => + (super.noSuchMethod( + Invocation.method(#isInitialized, [type]), + returnValue: false, + ) + as bool); @override - String getProviderId(_i2.DriverApiTypeDto? type) => (super.noSuchMethod( - Invocation.method( - #getProviderId, - [type], - ), - returnValue: _i4.dummyValue( - this, - Invocation.method( - #getProviderId, - [type], - ), - ), - ) as String); + String getProviderId(_i2.DriverApiTypeDto? type) => + (super.noSuchMethod( + Invocation.method(#getProviderId, [type]), + returnValue: _i4.dummyValue( + this, + Invocation.method(#getProviderId, [type]), + ), + ) + as String); @override - String getVehicleId(_i2.DriverApiTypeDto? type) => (super.noSuchMethod( - Invocation.method( - #getVehicleId, - [type], - ), - returnValue: _i4.dummyValue( - this, - Invocation.method( - #getVehicleId, - [type], - ), - ), - ) as String); + String getVehicleId(_i2.DriverApiTypeDto? type) => + (super.noSuchMethod( + Invocation.method(#getVehicleId, [type]), + returnValue: _i4.dummyValue( + this, + Invocation.method(#getVehicleId, [type]), + ), + ) + as String); @override bool isLocationTrackingEnabled(_i2.DriverApiTypeDto? type) => (super.noSuchMethod( - Invocation.method( - #isLocationTrackingEnabled, - [type], - ), - returnValue: false, - ) as bool); + Invocation.method(#isLocationTrackingEnabled, [type]), + returnValue: false, + ) + as bool); @override - void setLocationTrackingEnabled( - _i2.DriverApiTypeDto? type, - bool? enabled, - ) => + void setLocationTrackingEnabled(_i2.DriverApiTypeDto? type, bool? enabled) => super.noSuchMethod( - Invocation.method( - #setLocationTrackingEnabled, - [ - type, - enabled, - ], - ), + Invocation.method(#setLocationTrackingEnabled, [type, enabled]), returnValueForMissingStub: null, ); @override int getLocationReportingIntervalMillis(_i2.DriverApiTypeDto? type) => (super.noSuchMethod( - Invocation.method( - #getLocationReportingIntervalMillis, - [type], - ), - returnValue: 0, - ) as int); + Invocation.method(#getLocationReportingIntervalMillis, [type]), + returnValue: 0, + ) + as int); @override void setLocationReportingIntervalMillis( _i2.DriverApiTypeDto? type, int? milliseconds, - ) => - super.noSuchMethod( - Invocation.method( - #setLocationReportingIntervalMillis, - [ - type, - milliseconds, - ], - ), - returnValueForMissingStub: null, - ); + ) => super.noSuchMethod( + Invocation.method(#setLocationReportingIntervalMillis, [ + type, + milliseconds, + ]), + returnValueForMissingStub: null, + ); @override void dispose(_i2.DriverApiTypeDto? type) => super.noSuchMethod( - Invocation.method( - #dispose, - [type], - ), - returnValueForMissingStub: null, - ); + Invocation.method(#dispose, [type]), + returnValueForMissingStub: null, + ); @override - String getDriverSdkVersion(_i2.DriverApiTypeDto? type) => (super.noSuchMethod( - Invocation.method( - #getDriverSdkVersion, - [type], - ), - returnValue: _i4.dummyValue( - this, - Invocation.method( - #getDriverSdkVersion, - [type], - ), - ), - ) as String); + String getDriverSdkVersion(_i2.DriverApiTypeDto? type) => + (super.noSuchMethod( + Invocation.method(#getDriverSdkVersion, [type]), + returnValue: _i4.dummyValue( + this, + Invocation.method(#getDriverSdkVersion, [type]), + ), + ) + as String); @override void setSupplementalLocation( _i2.DriverApiTypeDto? type, _i2.LocationDto? location, - ) => - super.noSuchMethod( - Invocation.method( - #setSupplementalLocation, - [ - type, - location, - ], - ), - returnValueForMissingStub: null, - ); + ) => super.noSuchMethod( + Invocation.method(#setSupplementalLocation, [type, location]), + returnValueForMissingStub: null, + ); } /// A class which mocks [TestDeliveryDriverApi]. @@ -221,75 +173,69 @@ class MockTestDeliveryDriverApi extends _i1.Mock } @override - _i5.Future> arrivedAtStop() => (super.noSuchMethod( - Invocation.method( - #arrivedAtStop, - [], - ), - returnValue: _i5.Future>.value( - <_i2.VehicleStopDto?>[]), - ) as _i5.Future>); + _i5.Future> arrivedAtStop() => + (super.noSuchMethod( + Invocation.method(#arrivedAtStop, []), + returnValue: _i5.Future>.value( + <_i2.VehicleStopDto>[], + ), + ) + as _i5.Future>); @override - _i5.Future> completedStop() => (super.noSuchMethod( - Invocation.method( - #completedStop, - [], - ), - returnValue: _i5.Future>.value( - <_i2.VehicleStopDto?>[]), - ) as _i5.Future>); + _i5.Future> completedStop() => + (super.noSuchMethod( + Invocation.method(#completedStop, []), + returnValue: _i5.Future>.value( + <_i2.VehicleStopDto>[], + ), + ) + as _i5.Future>); @override - _i5.Future> enrouteToNextStop() => + _i5.Future> enrouteToNextStop() => (super.noSuchMethod( - Invocation.method( - #enrouteToNextStop, - [], - ), - returnValue: _i5.Future>.value( - <_i2.VehicleStopDto?>[]), - ) as _i5.Future>); + Invocation.method(#enrouteToNextStop, []), + returnValue: _i5.Future>.value( + <_i2.VehicleStopDto>[], + ), + ) + as _i5.Future>); @override - _i5.Future> getRemainingVehicleStops() => + _i5.Future> getRemainingVehicleStops() => (super.noSuchMethod( - Invocation.method( - #getRemainingVehicleStops, - [], - ), - returnValue: _i5.Future>.value( - <_i2.VehicleStopDto?>[]), - ) as _i5.Future>); + Invocation.method(#getRemainingVehicleStops, []), + returnValue: _i5.Future>.value( + <_i2.VehicleStopDto>[], + ), + ) + as _i5.Future>); @override - _i5.Future> setVehicleStops( - List<_i2.VehicleStopDto?>? stops) => + _i5.Future> setVehicleStops( + List<_i2.VehicleStopDto>? stops, + ) => (super.noSuchMethod( - Invocation.method( - #setVehicleStops, - [stops], - ), - returnValue: _i5.Future>.value( - <_i2.VehicleStopDto?>[]), - ) as _i5.Future>); + Invocation.method(#setVehicleStops, [stops]), + returnValue: _i5.Future>.value( + <_i2.VehicleStopDto>[], + ), + ) + as _i5.Future>); @override _i5.Future<_i2.DeliveryVehicleDto> getDeliveryVehicle() => (super.noSuchMethod( - Invocation.method( - #getDeliveryVehicle, - [], - ), - returnValue: - _i5.Future<_i2.DeliveryVehicleDto>.value(_FakeDeliveryVehicleDto_0( - this, - Invocation.method( - #getDeliveryVehicle, - [], - ), - )), - ) as _i5.Future<_i2.DeliveryVehicleDto>); + Invocation.method(#getDeliveryVehicle, []), + returnValue: _i5.Future<_i2.DeliveryVehicleDto>.value( + _FakeDeliveryVehicleDto_0( + this, + Invocation.method(#getDeliveryVehicle, []), + ), + ), + ) + as _i5.Future<_i2.DeliveryVehicleDto>); } /// A class which mocks [TestRidesharingDriverApi]. @@ -303,10 +249,7 @@ class MockTestRidesharingDriverApi extends _i1.Mock @override void setVehicleState(_i2.VehicleStateDto? state) => super.noSuchMethod( - Invocation.method( - #setVehicleState, - [state], - ), - returnValueForMissingStub: null, - ); + Invocation.method(#setVehicleState, [state]), + returnValueForMissingStub: null, + ); } diff --git a/test/messages_test.g.dart b/test/messages_test.g.dart index 664adb6..15a8d11 100644 --- a/test/messages_test.g.dart +++ b/test/messages_test.g.dart @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. // -// Autogenerated from Pigeon (v15.0.0), do not edit directly. +// Autogenerated from Pigeon (v25.3.2), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import, no_leading_underscores_for_local_identifiers // ignore_for_file: avoid_relative_lib_imports @@ -24,12 +24,48 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:google_driver_flutter/src/method_channel/messages.g.dart'; -class _TestCommonDriverApiCodec extends StandardMessageCodec { - const _TestCommonDriverApiCodec(); +class _PigeonCodec extends StandardMessageCodec { + const _PigeonCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { - if (value is LocationDto) { - buffer.putUint8(128); + if (value is int) { + buffer.putUint8(4); + buffer.putInt64(value); + } else if (value is DriverApiTypeDto) { + buffer.putUint8(129); + writeValue(buffer, value.index); + } else if (value is VehicleStopStateDto) { + buffer.putUint8(130); + writeValue(buffer, value.index); + } else if (value is VehicleStateDto) { + buffer.putUint8(131); + writeValue(buffer, value.index); + } else if (value is DriverStatusLevelDto) { + buffer.putUint8(132); + writeValue(buffer, value.index); + } else if (value is DriverStatusCodeDto) { + buffer.putUint8(133); + writeValue(buffer, value.index); + } else if (value is TaskInfoDto) { + buffer.putUint8(134); + writeValue(buffer, value.encode()); + } else if (value is VehicleStopDto) { + buffer.putUint8(135); + writeValue(buffer, value.encode()); + } else if (value is LatLngDto) { + buffer.putUint8(136); + writeValue(buffer, value.encode()); + } else if (value is NavigationWaypointDto) { + buffer.putUint8(137); + writeValue(buffer, value.encode()); + } else if (value is LocationDto) { + buffer.putUint8(138); + writeValue(buffer, value.encode()); + } else if (value is DeliveryVehicleDto) { + buffer.putUint8(139); + writeValue(buffer, value.encode()); + } else if (value is VehicleUpdateDto) { + buffer.putUint8(140); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); @@ -39,8 +75,35 @@ class _TestCommonDriverApiCodec extends StandardMessageCodec { @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { - case 128: + case 129: + final int? value = readValue(buffer) as int?; + return value == null ? null : DriverApiTypeDto.values[value]; + case 130: + final int? value = readValue(buffer) as int?; + return value == null ? null : VehicleStopStateDto.values[value]; + case 131: + final int? value = readValue(buffer) as int?; + return value == null ? null : VehicleStateDto.values[value]; + case 132: + final int? value = readValue(buffer) as int?; + return value == null ? null : DriverStatusLevelDto.values[value]; + case 133: + final int? value = readValue(buffer) as int?; + return value == null ? null : DriverStatusCodeDto.values[value]; + case 134: + return TaskInfoDto.decode(readValue(buffer)!); + case 135: + return VehicleStopDto.decode(readValue(buffer)!); + case 136: + return LatLngDto.decode(readValue(buffer)!); + case 137: + return NavigationWaypointDto.decode(readValue(buffer)!); + case 138: return LocationDto.decode(readValue(buffer)!); + case 139: + return DeliveryVehicleDto.decode(readValue(buffer)!); + case 140: + return VehicleUpdateDto.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } @@ -50,11 +113,14 @@ class _TestCommonDriverApiCodec extends StandardMessageCodec { abstract class TestCommonDriverApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec pigeonChannelCodec = - _TestCommonDriverApiCodec(); + static const MessageCodec pigeonChannelCodec = _PigeonCodec(); - void initialize(DriverApiTypeDto type, String providerId, String vehicleId, - bool abnormalTerminationReportingEnabled); + void initialize( + DriverApiTypeDto type, + String providerId, + String vehicleId, + bool abnormalTerminationReportingEnabled, + ); bool isInitialized(DriverApiTypeDto type); @@ -69,7 +135,9 @@ abstract class TestCommonDriverApi { int getLocationReportingIntervalMillis(DriverApiTypeDto type); void setLocationReportingIntervalMillis( - DriverApiTypeDto type, int milliseconds); + DriverApiTypeDto type, + int milliseconds, + ); void dispose(DriverApiTypeDto type); @@ -77,202 +145,264 @@ abstract class TestCommonDriverApi { void setSupplementalLocation(DriverApiTypeDto type, LocationDto location); - static void setup(TestCommonDriverApi? api, - {BinaryMessenger? binaryMessenger}) { + static void setUp( + TestCommonDriverApi? api, { + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) { + messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize was null.'); + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler< + Object? + >(pigeonVar_channel, (Object? message) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize was null.', + ); final List args = (message as List?)!; - final DriverApiTypeDto? arg_type = - args[0] == null ? null : DriverApiTypeDto.values[args[0]! as int]; - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize was null, expected non-null DriverApiTypeDto.'); + final DriverApiTypeDto? arg_type = (args[0] as DriverApiTypeDto?); + assert( + arg_type != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize was null, expected non-null DriverApiTypeDto.', + ); final String? arg_providerId = (args[1] as String?); - assert(arg_providerId != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize was null, expected non-null String.'); + assert( + arg_providerId != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize was null, expected non-null String.', + ); final String? arg_vehicleId = (args[2] as String?); - assert(arg_vehicleId != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize was null, expected non-null String.'); + assert( + arg_vehicleId != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize was null, expected non-null String.', + ); final bool? arg_abnormalTerminationReportingEnabled = (args[3] as bool?); - assert(arg_abnormalTerminationReportingEnabled != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize was null, expected non-null bool.'); + assert( + arg_abnormalTerminationReportingEnabled != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.initialize was null, expected non-null bool.', + ); try { - api.initialize(arg_type!, arg_providerId!, arg_vehicleId!, - arg_abnormalTerminationReportingEnabled!); + api.initialize( + arg_type!, + arg_providerId!, + arg_vehicleId!, + arg_abnormalTerminationReportingEnabled!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isInitialized', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isInitialized$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isInitialized was null.'); - final List args = (message as List?)!; - final DriverApiTypeDto? arg_type = - args[0] == null ? null : DriverApiTypeDto.values[args[0]! as int]; - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isInitialized was null, expected non-null DriverApiTypeDto.'); - try { - final bool output = api.isInitialized(arg_type!); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isInitialized was null.', + ); + final List args = (message as List?)!; + final DriverApiTypeDto? arg_type = (args[0] as DriverApiTypeDto?); + assert( + arg_type != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isInitialized was null, expected non-null DriverApiTypeDto.', + ); + try { + final bool output = api.isInitialized(arg_type!); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getProviderId', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getProviderId$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getProviderId was null.'); - final List args = (message as List?)!; - final DriverApiTypeDto? arg_type = - args[0] == null ? null : DriverApiTypeDto.values[args[0]! as int]; - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getProviderId was null, expected non-null DriverApiTypeDto.'); - try { - final String output = api.getProviderId(arg_type!); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getProviderId was null.', + ); + final List args = (message as List?)!; + final DriverApiTypeDto? arg_type = (args[0] as DriverApiTypeDto?); + assert( + arg_type != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getProviderId was null, expected non-null DriverApiTypeDto.', + ); + try { + final String output = api.getProviderId(arg_type!); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getVehicleId', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getVehicleId$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getVehicleId was null.'); - final List args = (message as List?)!; - final DriverApiTypeDto? arg_type = - args[0] == null ? null : DriverApiTypeDto.values[args[0]! as int]; - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getVehicleId was null, expected non-null DriverApiTypeDto.'); - try { - final String output = api.getVehicleId(arg_type!); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getVehicleId was null.', + ); + final List args = (message as List?)!; + final DriverApiTypeDto? arg_type = (args[0] as DriverApiTypeDto?); + assert( + arg_type != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getVehicleId was null, expected non-null DriverApiTypeDto.', + ); + try { + final String output = api.getVehicleId(arg_type!); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isLocationTrackingEnabled', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isLocationTrackingEnabled$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isLocationTrackingEnabled was null.'); - final List args = (message as List?)!; - final DriverApiTypeDto? arg_type = - args[0] == null ? null : DriverApiTypeDto.values[args[0]! as int]; - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isLocationTrackingEnabled was null, expected non-null DriverApiTypeDto.'); - try { - final bool output = api.isLocationTrackingEnabled(arg_type!); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isLocationTrackingEnabled was null.', + ); + final List args = (message as List?)!; + final DriverApiTypeDto? arg_type = (args[0] as DriverApiTypeDto?); + assert( + arg_type != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.isLocationTrackingEnabled was null, expected non-null DriverApiTypeDto.', + ); + try { + final bool output = api.isLocationTrackingEnabled(arg_type!); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationTrackingEnabled', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationTrackingEnabled$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationTrackingEnabled was null.'); + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler< + Object? + >(pigeonVar_channel, (Object? message) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationTrackingEnabled was null.', + ); final List args = (message as List?)!; - final DriverApiTypeDto? arg_type = - args[0] == null ? null : DriverApiTypeDto.values[args[0]! as int]; - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationTrackingEnabled was null, expected non-null DriverApiTypeDto.'); + final DriverApiTypeDto? arg_type = (args[0] as DriverApiTypeDto?); + assert( + arg_type != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationTrackingEnabled was null, expected non-null DriverApiTypeDto.', + ); final bool? arg_enabled = (args[1] as bool?); - assert(arg_enabled != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationTrackingEnabled was null, expected non-null bool.'); + assert( + arg_enabled != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationTrackingEnabled was null, expected non-null bool.', + ); try { api.setLocationTrackingEnabled(arg_type!, arg_enabled!); return wrapResponse(empty: true); @@ -280,167 +410,211 @@ abstract class TestCommonDriverApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getLocationReportingIntervalMillis', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getLocationReportingIntervalMillis$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getLocationReportingIntervalMillis was null.'); - final List args = (message as List?)!; - final DriverApiTypeDto? arg_type = - args[0] == null ? null : DriverApiTypeDto.values[args[0]! as int]; - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getLocationReportingIntervalMillis was null, expected non-null DriverApiTypeDto.'); - try { - final int output = - api.getLocationReportingIntervalMillis(arg_type!); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getLocationReportingIntervalMillis was null.', + ); + final List args = (message as List?)!; + final DriverApiTypeDto? arg_type = (args[0] as DriverApiTypeDto?); + assert( + arg_type != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getLocationReportingIntervalMillis was null, expected non-null DriverApiTypeDto.', + ); + try { + final int output = api.getLocationReportingIntervalMillis( + arg_type!, + ); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationReportingIntervalMillis', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationReportingIntervalMillis$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationReportingIntervalMillis was null.'); + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler< + Object? + >(pigeonVar_channel, (Object? message) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationReportingIntervalMillis was null.', + ); final List args = (message as List?)!; - final DriverApiTypeDto? arg_type = - args[0] == null ? null : DriverApiTypeDto.values[args[0]! as int]; - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationReportingIntervalMillis was null, expected non-null DriverApiTypeDto.'); + final DriverApiTypeDto? arg_type = (args[0] as DriverApiTypeDto?); + assert( + arg_type != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationReportingIntervalMillis was null, expected non-null DriverApiTypeDto.', + ); final int? arg_milliseconds = (args[1] as int?); - assert(arg_milliseconds != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationReportingIntervalMillis was null, expected non-null int.'); + assert( + arg_milliseconds != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setLocationReportingIntervalMillis was null, expected non-null int.', + ); try { api.setLocationReportingIntervalMillis( - arg_type!, arg_milliseconds!); + arg_type!, + arg_milliseconds!, + ); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } } { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.dispose', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.dispose$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.dispose was null.'); - final List args = (message as List?)!; - final DriverApiTypeDto? arg_type = - args[0] == null ? null : DriverApiTypeDto.values[args[0]! as int]; - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.dispose was null, expected non-null DriverApiTypeDto.'); - try { - api.dispose(arg_type!); - return wrapResponse(empty: true); - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.dispose was null.', + ); + final List args = (message as List?)!; + final DriverApiTypeDto? arg_type = (args[0] as DriverApiTypeDto?); + assert( + arg_type != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.dispose was null, expected non-null DriverApiTypeDto.', + ); + try { + api.dispose(arg_type!); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getDriverSdkVersion', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getDriverSdkVersion$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getDriverSdkVersion was null.'); - final List args = (message as List?)!; - final DriverApiTypeDto? arg_type = - args[0] == null ? null : DriverApiTypeDto.values[args[0]! as int]; - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getDriverSdkVersion was null, expected non-null DriverApiTypeDto.'); - try { - final String output = api.getDriverSdkVersion(arg_type!); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getDriverSdkVersion was null.', + ); + final List args = (message as List?)!; + final DriverApiTypeDto? arg_type = (args[0] as DriverApiTypeDto?); + assert( + arg_type != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.getDriverSdkVersion was null, expected non-null DriverApiTypeDto.', + ); + try { + final String output = api.getDriverSdkVersion(arg_type!); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setSupplementalLocation', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setSupplementalLocation$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setSupplementalLocation was null.'); + _testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler< + Object? + >(pigeonVar_channel, (Object? message) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setSupplementalLocation was null.', + ); final List args = (message as List?)!; - final DriverApiTypeDto? arg_type = - args[0] == null ? null : DriverApiTypeDto.values[args[0]! as int]; - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setSupplementalLocation was null, expected non-null DriverApiTypeDto.'); + final DriverApiTypeDto? arg_type = (args[0] as DriverApiTypeDto?); + assert( + arg_type != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setSupplementalLocation was null, expected non-null DriverApiTypeDto.', + ); final LocationDto? arg_location = (args[1] as LocationDto?); - assert(arg_location != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setSupplementalLocation was null, expected non-null LocationDto.'); + assert( + arg_location != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.CommonDriverApi.setSupplementalLocation was null, expected non-null LocationDto.', + ); try { api.setSupplementalLocation(arg_type!, arg_location!); return wrapResponse(empty: true); @@ -448,7 +622,8 @@ abstract class TestCommonDriverApi { return wrapResponse(error: e); } catch (e) { return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); + error: PlatformException(code: 'error', message: e.toString()), + ); } }); } @@ -456,226 +631,230 @@ abstract class TestCommonDriverApi { } } -class _TestDeliveryDriverApiCodec extends StandardMessageCodec { - const _TestDeliveryDriverApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is DeliveryVehicleDto) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else if (value is LatLngDto) { - buffer.putUint8(129); - writeValue(buffer, value.encode()); - } else if (value is NavigationWaypointDto) { - buffer.putUint8(130); - writeValue(buffer, value.encode()); - } else if (value is TaskInfoDto) { - buffer.putUint8(131); - writeValue(buffer, value.encode()); - } else if (value is VehicleStopDto) { - buffer.putUint8(132); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } - } - - @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return DeliveryVehicleDto.decode(readValue(buffer)!); - case 129: - return LatLngDto.decode(readValue(buffer)!); - case 130: - return NavigationWaypointDto.decode(readValue(buffer)!); - case 131: - return TaskInfoDto.decode(readValue(buffer)!); - case 132: - return VehicleStopDto.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } - } -} - abstract class TestDeliveryDriverApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec pigeonChannelCodec = - _TestDeliveryDriverApiCodec(); + static const MessageCodec pigeonChannelCodec = _PigeonCodec(); - Future> arrivedAtStop(); + Future> arrivedAtStop(); - Future> completedStop(); + Future> completedStop(); - Future> enrouteToNextStop(); + Future> enrouteToNextStop(); - Future> getRemainingVehicleStops(); + Future> getRemainingVehicleStops(); - Future> setVehicleStops(List stops); + Future> setVehicleStops(List stops); Future getDeliveryVehicle(); - static void setup(TestDeliveryDriverApi? api, - {BinaryMessenger? binaryMessenger}) { + static void setUp( + TestDeliveryDriverApi? api, { + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) { + messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.arrivedAtStop', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.arrivedAtStop$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - try { - final List output = await api.arrivedAtStop(); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + try { + final List output = await api.arrivedAtStop(); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.completedStop', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.completedStop$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - try { - final List output = await api.completedStop(); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + try { + final List output = await api.completedStop(); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.enrouteToNextStop', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.enrouteToNextStop$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - try { - final List output = await api.enrouteToNextStop(); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + try { + final List output = + await api.enrouteToNextStop(); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.getRemainingVehicleStops', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.getRemainingVehicleStops$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - try { - final List output = - await api.getRemainingVehicleStops(); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + try { + final List output = + await api.getRemainingVehicleStops(); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.setVehicleStops', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.setVehicleStops$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.setVehicleStops was null.'); - final List args = (message as List?)!; - final List? arg_stops = - (args[0] as List?)?.cast(); - assert(arg_stops != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.setVehicleStops was null, expected non-null List.'); - try { - final List output = - await api.setVehicleStops(arg_stops!); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.setVehicleStops was null.', + ); + final List args = (message as List?)!; + final List? arg_stops = + (args[0] as List?)?.cast(); + assert( + arg_stops != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.setVehicleStops was null, expected non-null List.', + ); + try { + final List output = await api.setVehicleStops( + arg_stops!, + ); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.getDeliveryVehicle', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.DeliveryDriverApi.getDeliveryVehicle$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - try { - final DeliveryVehicleDto output = await api.getDeliveryVehicle(); - return [output]; - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + try { + final DeliveryVehicleDto output = + await api.getDeliveryVehicle(); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } } @@ -684,43 +863,56 @@ abstract class TestDeliveryDriverApi { abstract class TestRidesharingDriverApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec pigeonChannelCodec = - StandardMessageCodec(); + static const MessageCodec pigeonChannelCodec = _PigeonCodec(); void setVehicleState(VehicleStateDto state); - static void setup(TestRidesharingDriverApi? api, - {BinaryMessenger? binaryMessenger}) { + static void setUp( + TestRidesharingDriverApi? api, { + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) { + messageChannelSuffix = + messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel __pigeon_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.google_driver_flutter.RidesharingDriverApi.setVehicleState', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); + final BasicMessageChannel + pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.google_driver_flutter.RidesharingDriverApi.setVehicleState$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, null); + .setMockDecodedMessageHandler(pigeonVar_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(__pigeon_channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.RidesharingDriverApi.setVehicleState was null.'); - final List args = (message as List?)!; - final VehicleStateDto? arg_state = - args[0] == null ? null : VehicleStateDto.values[args[0]! as int]; - assert(arg_state != null, - 'Argument for dev.flutter.pigeon.google_driver_flutter.RidesharingDriverApi.setVehicleState was null, expected non-null VehicleStateDto.'); - try { - api.setVehicleState(arg_state!); - return wrapResponse(empty: true); - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + assert( + message != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.RidesharingDriverApi.setVehicleState was null.', + ); + final List args = (message as List?)!; + final VehicleStateDto? arg_state = (args[0] as VehicleStateDto?); + assert( + arg_state != null, + 'Argument for dev.flutter.pigeon.google_driver_flutter.RidesharingDriverApi.setVehicleState was null, expected non-null VehicleStateDto.', + ); + try { + api.setVehicleState(arg_state!); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); } } } diff --git a/tools/test-ios.sh b/tools/test-ios.sh index e7601d3..dae5be4 100755 --- a/tools/test-ios.sh +++ b/tools/test-ios.sh @@ -14,7 +14,8 @@ # limitations under the License. set -e -DEVICE_NAME=${DEVICE:-'iPhone 14 Pro'} # Default to 'iPhone 14 Pro' if no argument is provided +DEVICE_NAME=${TEST_DEVICE:-'iPhone 16 Pro'} # Default to 'iPhone 16 Pro' if no argument is provided +OS_VERSION=${TEST_OS:-'18.1'} # Default to 'iPhone 16 Pro' if no argument is provided # Navigate to the ios directory and run xcodebuild with the provided device name cd ios && xcodebuild test \ @@ -22,5 +23,5 @@ cd ios && xcodebuild test \ -scheme Runner \ -only-testing RunnerTests \ -configuration Debug \ - -sdk iphoneos -destination "platform=iOS Simulator,name=$DEVICE_NAME" \ + -sdk iphoneos -destination "platform=iOS Simulator,name=$DEVICE_NAME,OS=$OS_VERSION" \ -derivedDataPath ../build/ios_unit