From e347eebc904381baee4d01ce9b21b4dd0297a8d0 Mon Sep 17 00:00:00 2001 From: JunsuChoi Date: Mon, 7 Sep 2026 16:34:44 +0900 Subject: [PATCH 1/2] Omit obvious local variable types and reformat with a line length of 100 Migrate the packages governed by the root analysis_options.yaml off the old always_specify_types style with `dart fix --code=omit_obvious_local_variable_types`, reformat them with `dart format`, then enable both `omit_obvious_local_variable_types` and `formatter: page_width: 100` (https://github.com/flutter-tizen/plugins/issues/1089). --- analysis_options.yaml | 9 +- packages/camera/CHANGELOG.md | 5 + .../example/integration_test/camera_test.dart | 42 ++- packages/camera/example/lib/main.dart | 112 +++---- packages/camera/lib/camera_tizen.dart | 30 +- packages/firebase_core/CHANGELOG.md | 5 + .../integration_test/firebase_core_test.dart | 2 +- .../example/lib/firebase_options.dart | 3 +- .../firebase_core/lib/firebase_app_tizen.dart | 3 +- .../lib/firebase_core_tizen.dart | 10 +- packages/google_maps_flutter/CHANGELOG.md | 2 + .../integration_test/src/maps_controller.dart | 141 +++------ .../integration_test/src/maps_inspector.dart | 154 ++++------ .../example/integration_test/src/shared.dart | 3 +- .../integration_test/src/tiles_inspector.dart | 116 +++----- .../example/lib/animate_camera.dart | 20 +- .../example/lib/clustering.dart | 49 +--- .../example/lib/custom_marker_icon.dart | 12 +- .../example/lib/ground_overlay.dart | 26 +- .../example/lib/heatmap.dart | 13 +- .../example/lib/lite_mode.dart | 5 +- .../example/lib/map_click.dart | 37 +-- .../example/lib/map_coordinates.dart | 12 +- .../example/lib/map_map_id.dart | 21 +- .../example/lib/map_ui.dart | 40 +-- .../example/lib/marker_icons.dart | 87 ++---- .../example/lib/move_camera.dart | 24 +- .../example/lib/padding.dart | 21 +- .../example/lib/place_circle.dart | 28 +- .../example/lib/place_marker.dart | 92 ++---- .../example/lib/place_polygon.dart | 40 +-- .../example/lib/place_polyline.dart | 60 +--- .../example/lib/readme_sample.dart | 8 +- .../example/lib/scrolling_map.dart | 30 +- .../example/lib/snapshot.dart | 8 +- .../example/lib/tile_overlay.dart | 44 +-- .../google_maps_flutter/lib/src/circles.dart | 11 +- .../google_maps_flutter/lib/src/convert.dart | 130 +++------ .../lib/src/google_maps_controller.dart | 191 ++++-------- .../lib/src/google_maps_flutter_tizen.dart | 93 ++---- .../lib/src/google_maps_js_bridge.dart | 87 ++---- .../lib/src/ground_overlay.dart | 5 +- .../lib/src/ground_overlays.dart | 26 +- .../google_maps_flutter/lib/src/marker.dart | 17 +- .../lib/src/marker_clustering.dart | 79 ++--- .../google_maps_flutter/lib/src/markers.dart | 25 +- .../google_maps_flutter/lib/src/polygons.dart | 14 +- .../google_maps_flutter/lib/src/polyline.dart | 5 +- .../lib/src/polylines.dart | 14 +- .../google_maps_flutter/lib/src/util.dart | 97 ++---- packages/google_sign_in/CHANGELOG.md | 5 + .../example/lib/credentials.dart | 3 +- packages/google_sign_in/example/lib/main.dart | 61 ++-- .../lib/google_sign_in_tizen.dart | 113 +++---- .../lib/src/authorization_exception.dart | 2 +- .../lib/src/device_flow_widget.dart | 31 +- packages/google_sign_in/lib/src/oauth2.dart | 72 ++--- packages/image_picker/CHANGELOG.md | 5 + packages/image_picker/example/lib/main.dart | 18 +- .../image_picker/lib/image_picker_tizen.dart | 13 +- packages/in_app_purchase/CHANGELOG.md | 2 + .../in_app_purchase/example/lib/main.dart | 53 ++-- .../lib/src/billing_manager.dart | 62 ++-- .../src/in_app_purchase_tizen_platform.dart | 121 ++++---- ..._app_purchase_tizen_platform_addition.dart | 6 +- .../in_app_purchase/lib/src/messages.g.dart | 135 ++++----- packages/integration_test/CHANGELOG.md | 5 + .../integration_test/example_test.dart | 3 +- packages/messageport/CHANGELOG.md | 5 + .../integration_test/messageport_test.dart | 29 +- packages/messageport/example/lib/main.dart | 2 +- .../messageport/lib/messageport_tizen.dart | 9 +- .../lib/src/messageport_manager.dart | 18 +- packages/path_provider/CHANGELOG.md | 5 + .../integration_test/path_provider_test.dart | 14 +- packages/path_provider/example/lib/main.dart | 64 +--- .../lib/path_provider_tizen.dart | 14 +- packages/shared_preferences/CHANGELOG.md | 5 + .../shared_preferences_test.dart | 141 ++++----- .../shared_preferences/example/lib/main.dart | 8 +- .../src/shared_preferences_async_tizen.dart | 17 +- .../lib/src/shared_preferences_tizen.dart | 17 +- packages/tizen_app_control/CHANGELOG.md | 5 + .../tizen_app_control_test.dart | 19 +- .../tizen_app_control/example/lib/main.dart | 23 +- .../lib/src/app_control.dart | 33 +-- packages/tizen_app_control/lib/src/ffi.dart | 2 +- packages/tizen_app_manager/CHANGELOG.md | 5 + .../tizen_app_manager_test.dart | 10 +- .../tizen_app_manager/example/lib/main.dart | 12 +- .../lib/src/app_manager.dart | 14 +- packages/tizen_audio_manager/CHANGELOG.md | 5 + .../integration_test/audio_manager_test.dart | 30 +- .../tizen_audio_manager/example/lib/main.dart | 22 +- .../lib/tizen_audio_manager.dart | 14 +- packages/tizen_bundle/CHANGELOG.md | 5 + .../integration_test/tizen_bundle_test.dart | 111 ++++--- packages/tizen_bundle/lib/tizen_bundle.dart | 22 +- packages/tizen_log/CHANGELOG.md | 5 + .../integration_test/tizen_log_test.dart | 2 +- packages/tizen_log/lib/tizen_log.dart | 13 +- packages/tizen_notification/CHANGELOG.md | 5 + .../tizen_notification_test.dart | 2 +- .../tizen_notification/example/lib/main.dart | 5 +- .../lib/tizen_notification.dart | 6 +- packages/tizen_package_manager/CHANGELOG.md | 5 + .../tizen_package_manager_test.dart | 8 +- .../example/lib/main.dart | 40 +-- .../lib/tizen_package_manager.dart | 9 +- packages/tizen_rpc_port/CHANGELOG.md | 5 + .../integration_test/tizen_rpc_port_test.dart | 68 ++--- .../example/client/lib/message_client.dart | 8 +- .../integration_test/tizen_rpc_port_test.dart | 16 +- .../example/server/lib/main.dart | 3 +- .../example/server/lib/message_server.dart | 8 +- packages/tizen_rpc_port/lib/src/parcel.dart | 19 +- packages/tizen_rpc_port/lib/src/port.dart | 2 +- .../tizen_rpc_port/lib/src/proxy_base.dart | 15 +- .../tizen_rpc_port/lib/src/stub_base.dart | 15 +- packages/tizen_window_manager/CHANGELOG.md | 5 + .../example/lib/main.dart | 15 +- .../lib/tizen_window_manager.dart | 3 +- packages/url_launcher/CHANGELOG.md | 5 + packages/url_launcher/example/lib/main.dart | 4 +- packages/video_player/CHANGELOG.md | 5 + .../integration_test/video_player_test.dart | 99 +++---- packages/video_player/example/lib/main.dart | 26 +- packages/video_player/lib/src/messages.g.dart | 213 +++++--------- .../video_player/lib/video_player_tizen.dart | 52 ++-- packages/video_player_avplay/CHANGELOG.md | 5 + .../integration_test/video_player_test.dart | 16 +- .../video_player_avplay/example/lib/main.dart | 22 +- .../lib/src/ad_info_from_dash.dart | 17 +- .../lib/src/closed_caption_file.dart | 167 ++++------- .../video_player_avplay/lib/src/hole.dart | 6 +- .../lib/src/messages.g.dart | 276 ++++++------------ .../video_player_avplay/lib/src/sub_rip.dart | 17 +- .../lib/src/video_player_tizen.dart | 86 +++--- .../video_player_avplay/lib/src/web_vtt.dart | 23 +- .../video_player_avplay/lib/video_player.dart | 119 +++----- .../lib/video_player_platform_interface.dart | 6 +- packages/video_player_videohole/CHANGELOG.md | 2 + .../integration_test/video_player_test.dart | 16 +- .../example/lib/main.dart | 7 +- .../video_player_videohole/lib/src/hole.dart | 6 +- .../lib/src/sub_rip.dart | 17 +- .../lib/src/video_player_tizen.dart | 54 ++-- .../lib/src/web_vtt.dart | 23 +- .../lib/video_player.dart | 51 ++-- .../lib/video_player_platform_interface.dart | 9 +- packages/wearable_rotary/CHANGELOG.md | 5 + .../wearable_rotary/example/lib/main.dart | 4 +- packages/webview_flutter/CHANGELOG.md | 5 + .../webview_flutter_test.dart | 192 +++++------- .../webview_flutter/example/lib/main.dart | 132 +++------ .../lib/src/tizen_webview.dart | 74 ++--- .../lib/src/tizen_webview_controller.dart | 141 ++++----- .../lib/src/tizen_webview_cookie_manager.dart | 7 +- .../lib/src/tizen_webview_platform.dart | 4 +- packages/webview_flutter_lwe/CHANGELOG.md | 5 + .../webview_flutter_test.dart | 145 ++++----- .../webview_flutter_lwe/example/lib/main.dart | 107 ++----- .../lib/src/lwe_webview.dart | 61 ++-- .../lib/src/lwe_webview_controller.dart | 73 ++--- .../lib/src/lwe_webview_cookie_manager.dart | 7 +- .../lib/src/lwe_webview_platform.dart | 4 +- tools/lib/src/build_examples_command.dart | 8 +- tools/lib/src/device.dart | 81 ++--- tools/lib/src/integration_test_command.dart | 62 ++-- tools/lib/src/main.dart | 8 +- tools/lib/src/process_runner_apis.dart | 8 +- tools/lib/src/publish_command.dart | 48 +-- tools/lib/src/recipe.dart | 14 +- tools/lib/src/tizen_sdk.dart | 46 ++- tools/test/device_test.dart | 10 +- tools/test/integration/device_test.dart | 44 ++- tools/test/integration_test_command_test.dart | 14 +- tools/test/recipe_test.dart | 2 +- tools/test/utils.dart | 8 +- 179 files changed, 2339 insertions(+), 4109 deletions(-) diff --git a/analysis_options.yaml b/analysis_options.yaml index d7b7218d3..629b7c6e6 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -25,11 +25,8 @@ analyzer: - '**/*.g.dart' - '**/*.mocks.dart' # Mockito @GenerateMocks -# TODO(jsuya): Different from flutter/packages. Enable after reformatting the -# existing code, which is still formatted with the default line length of 80 -# (https://github.com/flutter-tizen/plugins/issues/1089). -# formatter: -# page_width: 100 +formatter: + page_width: 100 linter: rules: @@ -144,7 +141,7 @@ linter: - null_check_on_nullable_type_parameter - null_closures # - omit_local_variable_types # superset of omit_obvious_local_variable_types - # - omit_obvious_local_variable_types # TODO(jsuya): Different from flutter/packages. Enable after migrating the existing code, which still follows the old always_specify_types style (https://github.com/flutter-tizen/plugins/issues/1089). + - omit_obvious_local_variable_types # - omit_obvious_property_types # conflicts with type_annotate_public_apis # - one_member_abstracts # too many false positives - only_throw_errors # this does get disabled in a few places where we have legacy code that uses strings et al diff --git a/packages/camera/CHANGELOG.md b/packages/camera/CHANGELOG.md index e1ea0e37f..ddf8f8711 100644 --- a/packages/camera/CHANGELOG.md +++ b/packages/camera/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 0.3.6 * Update code format. diff --git a/packages/camera/example/integration_test/camera_test.dart b/packages/camera/example/integration_test/camera_test.dart index aa8cef1a9..e8403239a 100644 --- a/packages/camera/example/integration_test/camera_test.dart +++ b/packages/camera/example/integration_test/camera_test.dart @@ -26,8 +26,7 @@ void main() { await testDir.delete(recursive: true); }); - final Map presetExpectedSizes = - { + final presetExpectedSizes = { ResolutionPreset.medium: const Size(480, 720), // Don't bother checking for max here since it could be anything. }; @@ -55,7 +54,7 @@ void main() { final XFile file = await controller.takePicture(); // Load picture - final File fileImage = File(file.path); + final fileImage = File(file.path); final Image image = await decodeImageFromList(fileImage.readAsBytesSync()); // Verify image dimensions are as expected @@ -73,11 +72,10 @@ void main() { if (cameras.isEmpty) { return; } - for (final CameraDescription cameraDescription in cameras) { - bool previousPresetExactlySupported = true; - for (final MapEntry preset - in presetExpectedSizes.entries) { - final CameraController controller = CameraController( + for (final cameraDescription in cameras) { + var previousPresetExactlySupported = true; + for (final MapEntry preset in presetExpectedSizes.entries) { + final controller = CameraController( cameraDescription, preset.key, ); @@ -111,8 +109,8 @@ void main() { final XFile file = await controller.stopVideoRecording(); // Load video metadata - final File videoFile = File(file.path); - final VideoPlayerController videoController = VideoPlayerController.file( + final videoFile = File(file.path); + final videoController = VideoPlayerController.file( videoFile, ); await videoController.initialize(); @@ -133,11 +131,10 @@ void main() { if (cameras.isEmpty) { return; } - for (final CameraDescription cameraDescription in cameras) { - bool previousPresetExactlySupported = true; - for (final MapEntry preset - in presetExpectedSizes.entries) { - final CameraController controller = CameraController( + for (final cameraDescription in cameras) { + var previousPresetExactlySupported = true; + for (final MapEntry preset in presetExpectedSizes.entries) { + final controller = CameraController( cameraDescription, preset.key, ); @@ -163,7 +160,7 @@ void main() { return; } - final CameraController controller = CameraController( + final controller = CameraController( cameras[0], ResolutionPreset.low, enableAudio: false, @@ -173,7 +170,7 @@ void main() { // await controller.prepareForVideoRecording(); int startPause; - int timePaused = 0; + var timePaused = 0; await controller.startVideoRecording(); final int recordingStart = DateTime.now().millisecondsSinceEpoch; @@ -196,11 +193,10 @@ void main() { sleep(const Duration(milliseconds: 500)); final XFile file = await controller.stopVideoRecording(); - final int recordingTime = - DateTime.now().millisecondsSinceEpoch - recordingStart; + final int recordingTime = DateTime.now().millisecondsSinceEpoch - recordingStart; - final File videoFile = File(file.path); - final VideoPlayerController videoController = VideoPlayerController.file( + final videoFile = File(file.path); + final videoController = VideoPlayerController.file( videoFile, ); await videoController.initialize(); @@ -216,14 +212,14 @@ void main() { return; } - final CameraController controller = CameraController( + final controller = CameraController( cameras[0], ResolutionPreset.low, enableAudio: false, ); await controller.initialize(); - bool isDetecting = false; + var isDetecting = false; await controller.startImageStream((CameraImage image) { if (isDetecting) { diff --git a/packages/camera/example/lib/main.dart b/packages/camera/example/lib/main.dart index 4021163a7..b51b05b91 100644 --- a/packages/camera/example/lib/main.dart +++ b/packages/camera/example/lib/main.dart @@ -136,10 +136,9 @@ class _CameraExampleHomeState extends State decoration: BoxDecoration( color: Colors.black, border: Border.all( - color: - controller != null && controller!.value.isRecordingVideo - ? Colors.redAccent - : Colors.grey, + color: controller != null && controller!.value.isRecordingVideo + ? Colors.redAccent + : Colors.grey, width: 3.0, ), ), @@ -187,8 +186,7 @@ class _CameraExampleHomeState extends State behavior: HitTestBehavior.opaque, onScaleStart: _handleScaleStart, onScaleUpdate: _handleScaleUpdate, - onTapDown: (TapDownDetails details) => - onViewFinderTap(details, constraints), + onTapDown: (TapDownDetails details) => onViewFinderTap(details, constraints), ); }, ), @@ -237,9 +235,7 @@ class _CameraExampleHomeState extends State // pointing to a location within the browser. It may be displayed // either with Image.network or Image.memory after loading the image // bytes to memory. - kIsWeb - ? Image.network(imageFile!.path) - : Image.file(File(imageFile!.path))) + kIsWeb ? Image.network(imageFile!.path) : Image.file(File(imageFile!.path))) : Container( decoration: BoxDecoration( border: Border.all(color: Colors.pink), @@ -276,15 +272,12 @@ class _CameraExampleHomeState extends State IconButton( icon: const Icon(Icons.exposure), color: Colors.blue, - onPressed: controller != null - ? onExposureModeButtonPressed - : null, + onPressed: controller != null ? onExposureModeButtonPressed : null, ), IconButton( icon: const Icon(Icons.filter_center_focus), color: Colors.blue, - onPressed: - controller != null ? onFocusModeButtonPressed : null, + onPressed: controller != null ? onFocusModeButtonPressed : null, ), ] : [], @@ -300,9 +293,7 @@ class _CameraExampleHomeState extends State : Icons.screen_rotation, ), color: Colors.blue, - onPressed: controller != null - ? onCaptureOrientationLockButtonPressed - : null, + onPressed: controller != null ? onCaptureOrientationLockButtonPressed : null, ), ], ), @@ -322,39 +313,27 @@ class _CameraExampleHomeState extends State children: [ IconButton( icon: const Icon(Icons.flash_off), - color: controller?.value.flashMode == FlashMode.off - ? Colors.orange - : Colors.blue, - onPressed: controller != null - ? () => onSetFlashModeButtonPressed(FlashMode.off) - : null, + color: controller?.value.flashMode == FlashMode.off ? Colors.orange : Colors.blue, + onPressed: + controller != null ? () => onSetFlashModeButtonPressed(FlashMode.off) : null, ), IconButton( icon: const Icon(Icons.flash_auto), - color: controller?.value.flashMode == FlashMode.auto - ? Colors.orange - : Colors.blue, - onPressed: controller != null - ? () => onSetFlashModeButtonPressed(FlashMode.auto) - : null, + color: controller?.value.flashMode == FlashMode.auto ? Colors.orange : Colors.blue, + onPressed: + controller != null ? () => onSetFlashModeButtonPressed(FlashMode.auto) : null, ), IconButton( icon: const Icon(Icons.flash_on), - color: controller?.value.flashMode == FlashMode.always - ? Colors.orange - : Colors.blue, - onPressed: controller != null - ? () => onSetFlashModeButtonPressed(FlashMode.always) - : null, + color: controller?.value.flashMode == FlashMode.always ? Colors.orange : Colors.blue, + onPressed: + controller != null ? () => onSetFlashModeButtonPressed(FlashMode.always) : null, ), IconButton( icon: const Icon(Icons.highlight), - color: controller?.value.flashMode == FlashMode.torch - ? Colors.orange - : Colors.blue, - onPressed: controller != null - ? () => onSetFlashModeButtonPressed(FlashMode.torch) - : null, + color: controller?.value.flashMode == FlashMode.torch ? Colors.orange : Colors.blue, + onPressed: + controller != null ? () => onSetFlashModeButtonPressed(FlashMode.torch) : null, ), ], ), @@ -364,14 +343,12 @@ class _CameraExampleHomeState extends State Widget _exposureModeControlRowWidget() { final ButtonStyle styleAuto = TextButton.styleFrom( - backgroundColor: controller?.value.exposureMode == ExposureMode.auto - ? Colors.orange - : Colors.blue, + backgroundColor: + controller?.value.exposureMode == ExposureMode.auto ? Colors.orange : Colors.blue, ); final ButtonStyle styleLocked = TextButton.styleFrom( - backgroundColor: controller?.value.exposureMode == ExposureMode.locked - ? Colors.orange - : Colors.blue, + backgroundColor: + controller?.value.exposureMode == ExposureMode.locked ? Colors.orange : Colors.blue, ); return SizeTransition( @@ -411,9 +388,7 @@ class _CameraExampleHomeState extends State ), TextButton( style: styleLocked, - onPressed: controller != null - ? () => controller!.setExposureOffset(0.0) - : null, + onPressed: controller != null ? () => controller!.setExposureOffset(0.0) : null, child: const Text('RESET OFFSET'), ), ], @@ -428,8 +403,7 @@ class _CameraExampleHomeState extends State min: _minAvailableExposureOffset, max: _maxAvailableExposureOffset, label: _currentExposureOffset.toString(), - onChanged: _minAvailableExposureOffset == - _maxAvailableExposureOffset + onChanged: _minAvailableExposureOffset == _maxAvailableExposureOffset ? null : setExposureOffset, ), @@ -445,14 +419,11 @@ class _CameraExampleHomeState extends State Widget _focusModeControlRowWidget() { final ButtonStyle styleAuto = TextButton.styleFrom( - backgroundColor: controller?.value.focusMode == FocusMode.auto - ? Colors.orange - : Colors.blue, + backgroundColor: controller?.value.focusMode == FocusMode.auto ? Colors.orange : Colors.blue, ); final ButtonStyle styleLocked = TextButton.styleFrom( - backgroundColor: controller?.value.focusMode == FocusMode.locked - ? Colors.orange - : Colors.blue, + backgroundColor: + controller?.value.focusMode == FocusMode.locked ? Colors.orange : Colors.blue, ); return SizeTransition( @@ -521,8 +492,7 @@ class _CameraExampleHomeState extends State : null, ), IconButton( - icon: cameraController != null && - cameraController.value.isRecordingPaused + icon: cameraController != null && cameraController.value.isRecordingPaused ? const Icon(Icons.play_arrow) : const Icon(Icons.pause), color: Colors.blue, @@ -545,12 +515,10 @@ class _CameraExampleHomeState extends State ), IconButton( icon: const Icon(Icons.pause_presentation), - color: - cameraController != null && cameraController.value.isPreviewPaused - ? Colors.red - : Colors.blue, - onPressed: - cameraController == null ? null : onPausePreviewButtonPressed, + color: cameraController != null && cameraController.value.isPreviewPaused + ? Colors.red + : Colors.blue, + onPressed: cameraController == null ? null : onPausePreviewButtonPressed, ), ], ); @@ -558,7 +526,7 @@ class _CameraExampleHomeState extends State /// Display a row of toggle to select the camera (or a message if no camera is available). Widget _cameraTogglesRowWidget() { - final List toggles = []; + final toggles = []; void onChanged(CameraDescription? description) { if (description == null) { @@ -583,9 +551,7 @@ class _CameraExampleHomeState extends State groupValue: controller?.description, value: cameraDescription, onChanged: - controller != null && controller!.value.isRecordingVideo - ? null - : onChanged, + controller != null && controller!.value.isRecordingVideo ? null : onChanged, ), ), ); @@ -610,7 +576,7 @@ class _CameraExampleHomeState extends State final CameraController cameraController = controller!; - final Offset offset = Offset( + final offset = Offset( details.localPosition.dx / constraints.maxWidth, details.localPosition.dy / constraints.maxHeight, ); @@ -630,7 +596,7 @@ class _CameraExampleHomeState extends State await oldController.dispose(); } - final CameraController cameraController = CameraController( + final cameraController = CameraController( cameraDescription, kIsWeb ? ResolutionPreset.max : ResolutionPreset.medium, enableAudio: enableAudio, @@ -985,7 +951,7 @@ class _CameraExampleHomeState extends State return; } - final VideoPlayerController vController = kIsWeb + final vController = kIsWeb ? VideoPlayerController.network(videoFile!.path) : VideoPlayerController.file(File(videoFile!.path)); diff --git a/packages/camera/lib/camera_tizen.dart b/packages/camera/lib/camera_tizen.dart index 683bd5f80..970440327 100644 --- a/packages/camera/lib/camera_tizen.dart +++ b/packages/camera/lib/camera_tizen.dart @@ -27,8 +27,7 @@ class CameraTizen extends CameraPlatform { /// The name of the channel that device events from the platform side are /// sent on. - static const String _deviceEventChannelName = - 'plugins.flutter.io/camera_tizen/fromPlatform'; + static const String _deviceEventChannelName = 'plugins.flutter.io/camera_tizen/fromPlatform'; /// The controller we need to broadcast the different events coming /// from handleMethodCall, specific to camera events. @@ -48,7 +47,7 @@ class CameraTizen extends CameraPlatform { StreamController _createDeviceEventStreamController() { // Set up the method handler lazily. - const MethodChannel channel = MethodChannel(_deviceEventChannelName); + const channel = MethodChannel(_deviceEventChannelName); channel.setMethodCallHandler(_handleDeviceMethodCall); return StreamController.broadcast(); } @@ -59,16 +58,15 @@ class CameraTizen extends CameraPlatform { // The stream for vending frames to platform interface clients. StreamController? _frameStreamController; - Stream _cameraEvents(int cameraId) => - _cameraEventStreamController.stream.where( + Stream _cameraEvents(int cameraId) => _cameraEventStreamController.stream.where( (CameraEvent event) => event.cameraId == cameraId, ); @override Future> availableCameras() async { try { - final List>? cameras = await _channel - .invokeListMethod>('availableCameras'); + final List>? cameras = + await _channel.invokeListMethod>('availableCameras'); if (cameras == null) { return []; @@ -95,12 +93,11 @@ class CameraTizen extends CameraPlatform { bool enableAudio = false, }) async { try { - final Map? reply = await _channel - .invokeMapMethod('create', { + final Map? reply = + await _channel.invokeMapMethod('create', { 'cameraName': cameraDescription.name, - 'resolutionPreset': resolutionPreset != null - ? _serializeResolutionPreset(resolutionPreset) - : null, + 'resolutionPreset': + resolutionPreset != null ? _serializeResolutionPreset(resolutionPreset) : null, 'enableAudio': enableAudio, }); @@ -116,7 +113,7 @@ class CameraTizen extends CameraPlatform { ImageFormatGroup imageFormatGroup = ImageFormatGroup.unknown, }) { _channels.putIfAbsent(cameraId, () { - final MethodChannel channel = MethodChannel( + final channel = MethodChannel( 'plugins.flutter.io/camera_tizen/camera$cameraId', ); channel.setMethodCallHandler( @@ -125,7 +122,7 @@ class CameraTizen extends CameraPlatform { return channel; }); - final Completer completer = Completer(); + final completer = Completer(); onCameraInitialized(cameraId).first.then((CameraInitializedEvent value) { completer.complete(); @@ -194,8 +191,7 @@ class CameraTizen extends CameraPlatform { @override Stream onDeviceOrientationChanged() { - return _deviceEventStreamController.stream - .whereType(); + return _deviceEventStreamController.stream.whereType(); } @override @@ -301,7 +297,7 @@ class CameraTizen extends CameraPlatform { Future _startPlatformStream() async { await _channel.invokeMethod('startImageStream'); - const EventChannel cameraEventChannel = EventChannel( + const cameraEventChannel = EventChannel( 'plugins.flutter.io/camera_tizen/imageStream', ); _platformImageStreamSubscription = diff --git a/packages/firebase_core/CHANGELOG.md b/packages/firebase_core/CHANGELOG.md index 22d7bec86..6addbc12a 100644 --- a/packages/firebase_core/CHANGELOG.md +++ b/packages/firebase_core/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 0.2.0 * Update firebase_core to 4.14.0. diff --git a/packages/firebase_core/example/integration_test/firebase_core_test.dart b/packages/firebase_core/example/integration_test/firebase_core_test.dart index 48b2dc565..89c6f6634 100644 --- a/packages/firebase_core/example/integration_test/firebase_core_test.dart +++ b/packages/firebase_core/example/integration_test/firebase_core_test.dart @@ -18,7 +18,7 @@ void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('firebase_core', () { - const String testAppName = '[DEFAULT]'; + const testAppName = '[DEFAULT]'; setUpAll(() async { await Firebase.initializeApp( diff --git a/packages/firebase_core/example/lib/firebase_options.dart b/packages/firebase_core/example/lib/firebase_options.dart index ee2edfe85..c86b06cb5 100644 --- a/packages/firebase_core/example/lib/firebase_options.dart +++ b/packages/firebase_core/example/lib/firebase_options.dart @@ -4,8 +4,7 @@ // ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members, no_default_cases, public_member_api_docs import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; -import 'package:flutter/foundation.dart' - show TargetPlatform, defaultTargetPlatform, kIsWeb; +import 'package:flutter/foundation.dart' show TargetPlatform, defaultTargetPlatform, kIsWeb; class DefaultFirebaseOptions { static FirebaseOptions get currentPlatform { diff --git a/packages/firebase_core/lib/firebase_app_tizen.dart b/packages/firebase_core/lib/firebase_app_tizen.dart index 81b75d1d9..0bf56ed94 100644 --- a/packages/firebase_core/lib/firebase_app_tizen.dart +++ b/packages/firebase_core/lib/firebase_app_tizen.dart @@ -17,8 +17,7 @@ class FirebaseApp extends FirebaseAppPlatform { } @override - bool get isAutomaticDataCollectionEnabled => - _isAutomaticDataCollectionEnabled; + bool get isAutomaticDataCollectionEnabled => _isAutomaticDataCollectionEnabled; @override Future setAutomaticDataCollectionEnabled(bool enabled) { diff --git a/packages/firebase_core/lib/firebase_core_tizen.dart b/packages/firebase_core/lib/firebase_core_tizen.dart index db4b856b3..773147642 100644 --- a/packages/firebase_core/lib/firebase_core_tizen.dart +++ b/packages/firebase_core/lib/firebase_core_tizen.dart @@ -42,9 +42,7 @@ class FirebaseCore extends FirebasePlatform { @override List get apps { - return core_dart.Firebase.apps - .map(_mapDartToPlatformApp) - .toList(growable: false); + return core_dart.Firebase.apps.map(_mapDartToPlatformApp).toList(growable: false); } @override @@ -63,11 +61,9 @@ class FirebaseCore extends FirebasePlatform { try { // Initialize the app in firebase_core_dart - final core_dart.FirebaseOptions dartOptions = - core_dart.FirebaseOptions.fromMap(options!.asMap); + final dartOptions = core_dart.FirebaseOptions.fromMap(options!.asMap); final core_dart.FirebaseApp dartApp = - await core_dart.Firebase.initializeApp( - name: name, options: dartOptions); + await core_dart.Firebase.initializeApp(name: name, options: dartOptions); return _mapDartToPlatformApp(dartApp); } on core_dart.FirebaseException catch (e) { diff --git a/packages/google_maps_flutter/CHANGELOG.md b/packages/google_maps_flutter/CHANGELOG.md index 10d29e2f4..1e1be1581 100644 --- a/packages/google_maps_flutter/CHANGELOG.md +++ b/packages/google_maps_flutter/CHANGELOG.md @@ -1,6 +1,8 @@ ## NEXT * Resolve `use_super_parameters` lint. +* Omit obvious local variable types. +* Reformat with a line length of 100. ## 0.2.3 diff --git a/packages/google_maps_flutter/example/integration_test/src/maps_controller.dart b/packages/google_maps_flutter/example/integration_test/src/maps_controller.dart index 603e819c4..5e4994640 100644 --- a/packages/google_maps_flutter/example/integration_test/src/maps_controller.dart +++ b/packages/google_maps_flutter/example/integration_test/src/maps_controller.dart @@ -26,8 +26,7 @@ void runTests() { (WidgetTester tester) async { await tester.binding.setSurfaceSize(const Size(800, 600)); - final Completer mapControllerCompleter = - Completer(); + final mapControllerCompleter = Completer(); final Key key = GlobalKey(); await tester.pumpWidget( Directionality( @@ -41,8 +40,7 @@ void runTests() { ), ), ); - final GoogleMapController mapController = - await mapControllerCompleter.future; + final GoogleMapController mapController = await mapControllerCompleter.future; await tester.pumpAndSettle(); @@ -51,8 +49,9 @@ void runTests() { // https://github.com/flutter/flutter/issues/54758 await Future.delayed(const Duration(seconds: 1)); - final ScreenCoordinate coordinate = await mapController - .getScreenCoordinate(kInitialCameraPosition.target); + final ScreenCoordinate coordinate = await mapController.getScreenCoordinate( + kInitialCameraPosition.target, + ); final Rect rect = tester.getRect(find.byKey(key)); if (isIOS || isWeb) { // On iOS, the coordinate value from the GoogleMapSdk doesn't include the devicePixelRatio`. @@ -62,13 +61,11 @@ void runTests() { } else { expect( coordinate.x, - ((rect.center.dx - rect.topLeft.dx) * tester.view.devicePixelRatio) - .round(), + ((rect.center.dx - rect.topLeft.dx) * tester.view.devicePixelRatio).round(), ); expect( coordinate.y, - ((rect.center.dy - rect.topLeft.dy) * tester.view.devicePixelRatio) - .round(), + ((rect.center.dy - rect.topLeft.dy) * tester.view.devicePixelRatio).round(), ); } await tester.binding.setSurfaceSize(null); @@ -81,13 +78,12 @@ void runTests() { 'testGetVisibleRegion', (WidgetTester tester) async { final Key key = GlobalKey(); - final LatLngBounds zeroLatLngBounds = LatLngBounds( + final zeroLatLngBounds = LatLngBounds( southwest: const LatLng(0, 0), northeast: const LatLng(0, 0), ); - final Completer mapControllerCompleter = - Completer(); + final mapControllerCompleter = Completer(); await pumpMap( tester, @@ -100,8 +96,7 @@ void runTests() { ), ); await tester.pumpAndSettle(); - final GoogleMapController mapController = - await mapControllerCompleter.future; + final GoogleMapController mapController = await mapControllerCompleter.future; // Wait for the visible region to be non-zero. final LatLngBounds firstVisibleRegion = @@ -116,15 +111,15 @@ void runTests() { // Making a new `LatLngBounds` about (10, 10) distance south west to the `firstVisibleRegion`. // The size of the `LatLngBounds` is 10 by 10. - final LatLng southWest = LatLng( + final southWest = LatLng( firstVisibleRegion.southwest.latitude - 20, firstVisibleRegion.southwest.longitude - 20, ); - final LatLng northEast = LatLng( + final northEast = LatLng( firstVisibleRegion.southwest.latitude - 10, firstVisibleRegion.southwest.longitude - 10, ); - final LatLng newCenter = LatLng( + final newCenter = LatLng( (northEast.latitude + southWest.latitude) / 2, (northEast.longitude + southWest.longitude) / 2, ); @@ -132,21 +127,15 @@ void runTests() { expect(firstVisibleRegion.contains(northEast), isFalse); expect(firstVisibleRegion.contains(southWest), isFalse); - final LatLngBounds latLngBounds = LatLngBounds( - southwest: southWest, - northeast: northEast, - ); + final latLngBounds = LatLngBounds(southwest: southWest, northeast: northEast); // TODO(iskakaushik): non-zero padding is needed for some device configurations // https://github.com/flutter/flutter/issues/30575 const double padding = 0; - await mapController.moveCamera( - CameraUpdate.newLatLngBounds(latLngBounds, padding), - ); + await mapController.moveCamera(CameraUpdate.newLatLngBounds(latLngBounds, padding)); await tester.pumpAndSettle(const Duration(seconds: 3)); - final LatLngBounds secondVisibleRegion = await mapController - .getVisibleRegion(); + final LatLngBounds secondVisibleRegion = await mapController.getVisibleRegion(); expect(secondVisibleRegion, isNot(zeroLatLngBounds)); @@ -159,8 +148,7 @@ void runTests() { testWidgets('testSetMapStyle valid Json String', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer controllerCompleter = - Completer(); + final controllerCompleter = Completer(); await pumpMap( tester, @@ -174,19 +162,15 @@ void runTests() { ); final GoogleMapController controller = await controllerCompleter.future; - const String mapStyle = - '[{"elementType":"geometry","stylers":[{"color":"#242f3e"}]}]'; + const mapStyle = '[{"elementType":"geometry","stylers":[{"color":"#242f3e"}]}]'; // Intentionally testing the deprecated code path. // ignore: deprecated_member_use await controller.setMapStyle(mapStyle); }); - testWidgets('testSetMapStyle invalid Json String', ( - WidgetTester tester, - ) async { + testWidgets('testSetMapStyle invalid Json String', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer controllerCompleter = - Completer(); + final controllerCompleter = Completer(); await pumpMap( tester, @@ -212,8 +196,7 @@ void runTests() { testWidgets('testSetMapStyle null string', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer controllerCompleter = - Completer(); + final controllerCompleter = Completer(); await pumpMap( tester, @@ -234,8 +217,7 @@ void runTests() { testWidgets('testGetLatLng', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer controllerCompleter = - Completer(); + final controllerCompleter = Completer(); await pumpMap( tester, @@ -256,13 +238,8 @@ void runTests() { await Future.delayed(const Duration(seconds: 1)); final LatLngBounds visibleRegion = await controller.getVisibleRegion(); - final LatLng topLeft = await controller.getLatLng( - const ScreenCoordinate(x: 0, y: 0), - ); - final LatLng northWest = LatLng( - visibleRegion.northeast.latitude, - visibleRegion.southwest.longitude, - ); + final LatLng topLeft = await controller.getLatLng(const ScreenCoordinate(x: 0, y: 0)); + final northWest = LatLng(visibleRegion.northeast.latitude, visibleRegion.southwest.longitude); expect(topLeft, northWest); }); @@ -271,8 +248,7 @@ void runTests() { 'testGetZoomLevel', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer controllerCompleter = - Completer(); + final controllerCompleter = Completer(); await pumpMap( tester, @@ -308,8 +284,7 @@ void runTests() { 'testScreenCoordinate', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer controllerCompleter = - Completer(); + final controllerCompleter = Completer(); await pumpMap( tester, @@ -330,13 +305,8 @@ void runTests() { await Future.delayed(const Duration(seconds: 1)); final LatLngBounds visibleRegion = await controller.getVisibleRegion(); - final LatLng northWest = LatLng( - visibleRegion.northeast.latitude, - visibleRegion.southwest.longitude, - ); - final ScreenCoordinate topLeft = await controller.getScreenCoordinate( - northWest, - ); + final northWest = LatLng(visibleRegion.northeast.latitude, visibleRegion.southwest.longitude); + final ScreenCoordinate topLeft = await controller.getScreenCoordinate(northWest); expect(topLeft, const ScreenCoordinate(x: 0, y: 0)); }, // TODO(stuartmorgan): Re-enable; see https://github.com/flutter/flutter/issues/139825 @@ -344,8 +314,7 @@ void runTests() { ); testWidgets('testResizeWidget', (WidgetTester tester) async { - final Completer controllerCompleter = - Completer(); + final controllerCompleter = Completer(); await pumpMap( tester, @@ -385,14 +354,13 @@ void runTests() { }); testWidgets('testToggleInfoWindow', (WidgetTester tester) async { - const Marker marker = Marker( + const marker = Marker( markerId: MarkerId('marker'), infoWindow: InfoWindow(title: 'InfoWindow'), ); - final Set markers = {marker}; + final markers = {marker}; - final Completer controllerCompleter = - Completer(); + final controllerCompleter = Completer(); await pumpMap( tester, @@ -414,9 +382,7 @@ void runTests() { // re-evaluated when that issue is fixed. await Future.delayed(const Duration(seconds: 1)); - bool iwVisibleStatus = await controller.isMarkerInfoWindowShown( - marker.markerId, - ); + bool iwVisibleStatus = await controller.isMarkerInfoWindowShown(marker.markerId); expect(iwVisibleStatus, false); await controller.showMarkerInfoWindow(marker.markerId); @@ -437,7 +403,7 @@ void runTests() { }); testWidgets('markerWithAssetMapBitmap', (WidgetTester tester) async { - final Set markers = { + final markers = { Marker( markerId: const MarkerId('1'), icon: AssetMapBitmap('assets/red_square.png', imagePixelRatio: 1.0), @@ -453,16 +419,11 @@ void runTests() { }); testWidgets('markerWithAssetMapBitmapCreate', (WidgetTester tester) async { - final ImageConfiguration imageConfiguration = ImageConfiguration( - devicePixelRatio: tester.view.devicePixelRatio, - ); - final Set markers = { + final imageConfiguration = ImageConfiguration(devicePixelRatio: tester.view.devicePixelRatio); + final markers = { Marker( markerId: const MarkerId('1'), - icon: await AssetMapBitmap.create( - imageConfiguration, - 'assets/red_square.png', - ), + icon: await AssetMapBitmap.create(imageConfiguration, 'assets/red_square.png'), ), }; await pumpMap( @@ -476,13 +437,10 @@ void runTests() { testWidgets('markerWithBytesMapBitmap', (WidgetTester tester) async { final Uint8List bytes = const Base64Decoder().convert(iconImageBase64); - final Set markers = { + final markers = { Marker( markerId: const MarkerId('1'), - icon: BytesMapBitmap( - bytes, - imagePixelRatio: tester.view.devicePixelRatio, - ), + icon: BytesMapBitmap(bytes, imagePixelRatio: tester.view.devicePixelRatio), ), }; await pumpMap( @@ -496,19 +454,16 @@ void runTests() { testWidgets('markerWithLegacyAsset', (WidgetTester tester) async { tester.view.devicePixelRatio = 2.0; - final ImageConfiguration imageConfiguration = ImageConfiguration( + final imageConfiguration = ImageConfiguration( devicePixelRatio: tester.view.devicePixelRatio, size: const Size(100, 100), ); - final Set markers = { + final markers = { Marker( markerId: const MarkerId('1'), // Intentionally testing the deprecated code path. // ignore: deprecated_member_use - icon: await BitmapDescriptor.fromAssetImage( - imageConfiguration, - 'assets/red_square.png', - ), + icon: await BitmapDescriptor.fromAssetImage(imageConfiguration, 'assets/red_square.png'), ), }; await pumpMap( @@ -525,7 +480,7 @@ void runTests() { testWidgets('markerWithLegacyBytes', (WidgetTester tester) async { tester.view.devicePixelRatio = 2.0; final Uint8List bytes = const Base64Decoder().convert(iconImageBase64); - final Set markers = { + final markers = { Marker( markerId: const MarkerId('1'), // Intentionally testing the deprecated code path. @@ -547,8 +502,7 @@ void runTests() { testWidgets( 'testTakeSnapshot', (WidgetTester tester) async { - final Completer controllerCompleter = - Completer(); + final controllerCompleter = Completer(); await pumpMap( tester, @@ -572,7 +526,7 @@ void runTests() { testWidgets( 'testCloudMapId', (WidgetTester tester) async { - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); final Key key = GlobalKey(); await pumpMap( @@ -599,8 +553,7 @@ void runTests() { 'getStyleError reports last error', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer controllerCompleter = - Completer(); + final controllerCompleter = Completer(); await pumpMap( tester, @@ -639,7 +592,7 @@ Future waitForValueMatchingPredicate( bool Function(T) predicate, { int maxTries = 100, }) async { - for (int i = 0; i < maxTries; i++) { + for (var i = 0; i < maxTries; i++) { final T value = await getValue(); if (predicate(value)) { return value; diff --git a/packages/google_maps_flutter/example/integration_test/src/maps_inspector.dart b/packages/google_maps_flutter/example/integration_test/src/maps_inspector.dart index 8275e9311..be2bcc39f 100644 --- a/packages/google_maps_flutter/example/integration_test/src/maps_inspector.dart +++ b/packages/google_maps_flutter/example/integration_test/src/maps_inspector.dart @@ -22,12 +22,11 @@ void main() { void runTests() { GoogleMapsFlutterPlatform.instance.enableDebugInspection(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; testWidgets('testCompassToggle', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); await pumpMap( tester, GoogleMap( @@ -61,7 +60,7 @@ void runTests() { testWidgets('testMapToolbarToggle', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); await pumpMap( tester, @@ -106,11 +105,10 @@ void runTests() { // // Thus we test iOS and Android a little differently here. final Key key = GlobalKey(); - final Completer controllerCompleter = - Completer(); + final controllerCompleter = Completer(); - const MinMaxZoomPreference initialZoomLevel = MinMaxZoomPreference(4, 8); - const MinMaxZoomPreference finalZoomLevel = MinMaxZoomPreference(6, 10); + const initialZoomLevel = MinMaxZoomPreference(4, 8); + const finalZoomLevel = MinMaxZoomPreference(6, 10); await pumpMap( tester, @@ -127,8 +125,9 @@ void runTests() { final GoogleMapController controller = await controllerCompleter.future; if (isIOS) { - final MinMaxZoomPreference zoomLevel = await inspector - .getMinMaxZoomLevels(mapId: controller.mapId); + final MinMaxZoomPreference zoomLevel = await inspector.getMinMaxZoomLevels( + mapId: controller.mapId, + ); expect(zoomLevel, equals(initialZoomLevel)); } else if (isAndroid) { await controller.moveCamera(CameraUpdate.zoomTo(15)); @@ -155,8 +154,9 @@ void runTests() { ); if (isIOS) { - final MinMaxZoomPreference zoomLevel = await inspector - .getMinMaxZoomLevels(mapId: controller.mapId); + final MinMaxZoomPreference zoomLevel = await inspector.getMinMaxZoomLevels( + mapId: controller.mapId, + ); expect(zoomLevel, equals(finalZoomLevel)); } else { await controller.moveCamera(CameraUpdate.zoomTo(15)); @@ -173,7 +173,7 @@ void runTests() { testWidgets('testZoomGesturesEnabled', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); await pumpMap( tester, @@ -188,9 +188,7 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - bool zoomGesturesEnabled = await inspector.areZoomGesturesEnabled( - mapId: mapId, - ); + bool zoomGesturesEnabled = await inspector.areZoomGesturesEnabled(mapId: mapId); expect(zoomGesturesEnabled, false); await pumpMap( @@ -210,7 +208,7 @@ void runTests() { testWidgets('testZoomControlsEnabled', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); await pumpMap( tester, @@ -224,9 +222,7 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - bool zoomControlsEnabled = await inspector.areZoomControlsEnabled( - mapId: mapId, - ); + bool zoomControlsEnabled = await inspector.areZoomControlsEnabled(mapId: mapId); expect(zoomControlsEnabled, !isIOS); /// Zoom Controls functionality is not available on iOS at the moment. @@ -243,16 +239,14 @@ void runTests() { ), ); - zoomControlsEnabled = await inspector.areZoomControlsEnabled( - mapId: mapId, - ); + zoomControlsEnabled = await inspector.areZoomControlsEnabled(mapId: mapId); expect(zoomControlsEnabled, false); } }); testWidgets('testLiteModeEnabled', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); await pumpMap( tester, @@ -287,7 +281,7 @@ void runTests() { testWidgets('testRotateGesturesEnabled', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); await pumpMap( tester, @@ -302,9 +296,7 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - bool rotateGesturesEnabled = await inspector.areRotateGesturesEnabled( - mapId: mapId, - ); + bool rotateGesturesEnabled = await inspector.areRotateGesturesEnabled(mapId: mapId); expect(rotateGesturesEnabled, false); await pumpMap( @@ -318,15 +310,13 @@ void runTests() { ), ); - rotateGesturesEnabled = await inspector.areRotateGesturesEnabled( - mapId: mapId, - ); + rotateGesturesEnabled = await inspector.areRotateGesturesEnabled(mapId: mapId); expect(rotateGesturesEnabled, !isWeb); }); testWidgets('testTiltGesturesEnabled', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); await pumpMap( tester, @@ -341,9 +331,7 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - bool tiltGesturesEnabled = await inspector.areTiltGesturesEnabled( - mapId: mapId, - ); + bool tiltGesturesEnabled = await inspector.areTiltGesturesEnabled(mapId: mapId); expect(tiltGesturesEnabled, false); await pumpMap( @@ -363,7 +351,7 @@ void runTests() { testWidgets('testScrollGesturesEnabled', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); await pumpMap( tester, @@ -378,9 +366,7 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - bool scrollGesturesEnabled = await inspector.areScrollGesturesEnabled( - mapId: mapId, - ); + bool scrollGesturesEnabled = await inspector.areScrollGesturesEnabled(mapId: mapId); expect(scrollGesturesEnabled, false); await pumpMap( @@ -394,15 +380,13 @@ void runTests() { ), ); - scrollGesturesEnabled = await inspector.areScrollGesturesEnabled( - mapId: mapId, - ); + scrollGesturesEnabled = await inspector.areScrollGesturesEnabled(mapId: mapId); expect(scrollGesturesEnabled, true); }); testWidgets('testTraffic', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); await pumpMap( tester, @@ -437,7 +421,7 @@ void runTests() { testWidgets('testBuildings', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); await pumpMap( tester, @@ -451,9 +435,7 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - final bool isBuildingsEnabled = await inspector.areBuildingsEnabled( - mapId: mapId, - ); + final bool isBuildingsEnabled = await inspector.areBuildingsEnabled(mapId: mapId); expect(isBuildingsEnabled, !isWeb); }); @@ -462,7 +444,7 @@ void runTests() { group('MyLocationButton', () { testWidgets('testMyLocationButtonToggle', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); await pumpMap( tester, @@ -476,9 +458,7 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled( - mapId: mapId, - ); + bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, true); await pumpMap( @@ -493,17 +473,13 @@ void runTests() { ), ); - myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled( - mapId: mapId, - ); + myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, false); }); - testWidgets('testMyLocationButton initial value false', ( - WidgetTester tester, - ) async { + testWidgets('testMyLocationButton initial value false', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); await pumpMap( tester, @@ -518,16 +494,13 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - final bool myLocationButtonEnabled = await inspector - .isMyLocationButtonEnabled(mapId: mapId); + final bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, false); }); - testWidgets('testMyLocationButton initial value true', ( - WidgetTester tester, - ) async { + testWidgets('testMyLocationButton initial value true', (WidgetTester tester) async { final Key key = GlobalKey(); - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); await pumpMap( tester, @@ -541,48 +514,37 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - final bool myLocationButtonEnabled = await inspector - .isMyLocationButtonEnabled(mapId: mapId); + final bool myLocationButtonEnabled = await inspector.isMyLocationButtonEnabled(mapId: mapId); expect(myLocationButtonEnabled, true); }); }, skip: !isIOS); testWidgets('marker clustering', (WidgetTester tester) async { final Key key = GlobalKey(); - const int clusterManagersAmount = 2; - const int markersPerClusterManager = 5; - final Map markers = {}; - final Set clusterManagers = {}; - - for (int i = 0; i < clusterManagersAmount; i++) { - final ClusterManagerId clusterManagerId = ClusterManagerId( - 'cluster_manager_$i', - ); - final ClusterManager clusterManager = ClusterManager( - clusterManagerId: clusterManagerId, - ); + const clusterManagersAmount = 2; + const markersPerClusterManager = 5; + final markers = {}; + final clusterManagers = {}; + + for (var i = 0; i < clusterManagersAmount; i++) { + final clusterManagerId = ClusterManagerId('cluster_manager_$i'); + final clusterManager = ClusterManager(clusterManagerId: clusterManagerId); clusterManagers.add(clusterManager); } - for (final ClusterManager cm in clusterManagers) { - for (int i = 0; i < markersPerClusterManager; i++) { - final MarkerId markerId = MarkerId( - '${cm.clusterManagerId.value}_marker_$i', - ); - final Marker marker = Marker( + for (final cm in clusterManagers) { + for (var i = 0; i < markersPerClusterManager; i++) { + final markerId = MarkerId('${cm.clusterManagerId.value}_marker_$i'); + final marker = Marker( markerId: markerId, clusterManagerId: cm.clusterManagerId, - position: LatLng( - kInitialMapCenter.latitude + i, - kInitialMapCenter.longitude, - ), + position: LatLng(kInitialMapCenter.latitude + i, kInitialMapCenter.longitude), ); markers[markerId] = marker; } } - final Completer controllerCompleter = - Completer(); + final controllerCompleter = Completer(); await pumpMap( tester, @@ -599,10 +561,9 @@ void runTests() { final GoogleMapController controller = await controllerCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; - for (final ClusterManager cm in clusterManagers) { + for (final cm in clusterManagers) { final List clusters = await inspector.getClusters( mapId: controller.mapId, clusterManagerId: cm.clusterManagerId, @@ -628,7 +589,7 @@ void runTests() { ), ); - for (final ClusterManager cm in clusterManagers) { + for (final cm in clusterManagers) { final List clusters = await inspector.getClusters( mapId: controller.mapId, clusterManagerId: cm.clusterManagerId, @@ -638,10 +599,7 @@ void runTests() { }); } -Marker _copyMarkerWithClusterManagerId( - Marker marker, - ClusterManagerId? clusterManagerId, -) { +Marker _copyMarkerWithClusterManagerId(Marker marker, ClusterManagerId? clusterManagerId) { return Marker( markerId: marker.markerId, alpha: marker.alpha, diff --git a/packages/google_maps_flutter/example/integration_test/src/shared.dart b/packages/google_maps_flutter/example/integration_test/src/shared.dart index 047072027..9d1fcb4a8 100644 --- a/packages/google_maps_flutter/example/integration_test/src/shared.dart +++ b/packages/google_maps_flutter/example/integration_test/src/shared.dart @@ -28,8 +28,7 @@ const String kCloudMapId = '000000000000000'; // Dummy map ID. final bool isIOS = defaultTargetPlatform == TargetPlatform.iOS; /// True if the test is running in an Android device -final bool isAndroid = - defaultTargetPlatform == TargetPlatform.android && !kIsWeb; +final bool isAndroid = defaultTargetPlatform == TargetPlatform.android && !kIsWeb; /// True if the test is running in a web browser. const bool isWeb = kIsWeb; diff --git a/packages/google_maps_flutter/example/integration_test/src/tiles_inspector.dart b/packages/google_maps_flutter/example/integration_test/src/tiles_inspector.dart index ef937e865..218c40ce6 100644 --- a/packages/google_maps_flutter/example/integration_test/src/tiles_inspector.dart +++ b/packages/google_maps_flutter/example/integration_test/src/tiles_inspector.dart @@ -22,24 +22,23 @@ void main() { } void runTests() { - const double floatTolerance = 1e-8; + const floatTolerance = 1e-8; GoogleMapsFlutterPlatform.instance.enableDebugInspection(); - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; group('Tiles', () { testWidgets('set tileOverlay correctly', (WidgetTester tester) async { - final Completer mapIdCompleter = Completer(); - final TileOverlay tileOverlay1 = TileOverlay( + final mapIdCompleter = Completer(); + final tileOverlay1 = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_1'), tileProvider: _DebugTileProvider(), zIndex: 2, transparency: 0.2, ); - final TileOverlay tileOverlay2 = TileOverlay( + final tileOverlay2 = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_2'), tileProvider: _DebugTileProvider(), zIndex: 1, @@ -74,32 +73,26 @@ void runTests() { expect(tileOverlayInfo1.visible, isTrue); expect(tileOverlayInfo1.fadeIn, isTrue); - expect( - tileOverlayInfo1.transparency, - moreOrLessEquals(0.2, epsilon: 0.001), - ); + expect(tileOverlayInfo1.transparency, moreOrLessEquals(0.2, epsilon: 0.001)); expect(tileOverlayInfo1.zIndex, 2); expect(tileOverlayInfo2.visible, isFalse); expect(tileOverlayInfo2.fadeIn, isFalse); - expect( - tileOverlayInfo2.transparency, - moreOrLessEquals(0.3, epsilon: 0.001), - ); + expect(tileOverlayInfo2.transparency, moreOrLessEquals(0.3, epsilon: 0.001)); expect(tileOverlayInfo2.zIndex, 1); }); testWidgets('update tileOverlays correctly', (WidgetTester tester) async { - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); final Key key = GlobalKey(); - final TileOverlay tileOverlay1 = TileOverlay( + final tileOverlay1 = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_1'), tileProvider: _DebugTileProvider(), zIndex: 2, transparency: 0.2, ); - final TileOverlay tileOverlay2 = TileOverlay( + final tileOverlay2 = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_2'), tileProvider: _DebugTileProvider(), zIndex: 3, @@ -121,7 +114,7 @@ void runTests() { final int mapId = await mapIdCompleter.future; - final TileOverlay tileOverlay1New = TileOverlay( + final tileOverlay1New = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_1'), tileProvider: _DebugTileProvider(), zIndex: 1, @@ -157,19 +150,16 @@ void runTests() { expect(tileOverlayInfo1.visible, isFalse); expect(tileOverlayInfo1.fadeIn, isFalse); - expect( - tileOverlayInfo1.transparency, - moreOrLessEquals(0.3, epsilon: 0.001), - ); + expect(tileOverlayInfo1.transparency, moreOrLessEquals(0.3, epsilon: 0.001)); expect(tileOverlayInfo1.zIndex, 1); expect(tileOverlayInfo2, isNull); }); testWidgets('remove tileOverlays correctly', (WidgetTester tester) async { - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); final Key key = GlobalKey(); - final TileOverlay tileOverlay1 = TileOverlay( + final tileOverlay1 = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_1'), tileProvider: _DebugTileProvider(), zIndex: 2, @@ -216,12 +206,9 @@ void runTests() { }, skip: isWeb /* Tiles not supported on the web */); /// Check that two lists of [WeightedLatLng] are more or less equal. - void expectHeatmapDataMoreOrLessEquals( - List data1, - List data2, - ) { + void expectHeatmapDataMoreOrLessEquals(List data1, List data2) { expect(data1.length, data2.length); - for (int i = 0; i < data1.length; i++) { + for (var i = 0; i < data1.length; i++) { final WeightedLatLng wll1 = data1[i]; final WeightedLatLng wll2 = data2[i]; expect(wll1.weight, wll2.weight); @@ -242,14 +229,11 @@ void runTests() { expect(gradient2, isNotNull); expect(gradient1.colors.length, gradient2.colors.length); - for (int i = 0; i < gradient1.colors.length; i++) { + for (var i = 0; i < gradient1.colors.length; i++) { final HeatmapGradientColor color1 = gradient1.colors[i]; final HeatmapGradientColor color2 = gradient2.colors[i]; expect(color1.color, color2.color); - expect( - color1.startPoint, - moreOrLessEquals(color2.startPoint, epsilon: floatTolerance), - ); + expect(color1.startPoint, moreOrLessEquals(color2.startPoint, epsilon: floatTolerance)); } expect(gradient1.colorMapSize, gradient2.colorMapSize); @@ -274,10 +258,7 @@ void runTests() { if (canHandleMaxIntensity()) { expect(heatmap1.maxIntensity, heatmap2.maxIntensity); } - expect( - heatmap1.opacity, - moreOrLessEquals(heatmap2.opacity, epsilon: floatTolerance), - ); + expect(heatmap1.opacity, moreOrLessEquals(heatmap2.opacity, epsilon: floatTolerance)); expect(heatmap1.radius, heatmap2.radius); if (canHandleZoomIntensity()) { expect(heatmap1.minimumZoomIntensity, heatmap2.minimumZoomIntensity); @@ -285,7 +266,7 @@ void runTests() { } } - const Heatmap heatmap1 = Heatmap( + const heatmap1 = Heatmap( heatmapId: HeatmapId('heatmap_1'), data: [ WeightedLatLng(LatLng(37.782, -122.447)), @@ -319,8 +300,8 @@ void runTests() { ); testWidgets('set heatmap correctly', (WidgetTester tester) async { - final Completer mapIdCompleter = Completer(); - final Heatmap heatmap2 = Heatmap( + final mapIdCompleter = Completer(); + final heatmap2 = Heatmap( heatmapId: const HeatmapId('heatmap_2'), data: heatmap1.data, dissipating: heatmap1.dissipating, @@ -347,18 +328,11 @@ void runTests() { await tester.pumpAndSettle(const Duration(seconds: 3)); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; if (inspector.supportsGettingHeatmapInfo()) { - final Heatmap heatmapInfo1 = (await inspector.getHeatmapInfo( - heatmap1.mapsId, - mapId: mapId, - ))!; - final Heatmap heatmapInfo2 = (await inspector.getHeatmapInfo( - heatmap2.mapsId, - mapId: mapId, - ))!; + final Heatmap heatmapInfo1 = (await inspector.getHeatmapInfo(heatmap1.mapsId, mapId: mapId))!; + final Heatmap heatmapInfo2 = (await inspector.getHeatmapInfo(heatmap2.mapsId, mapId: mapId))!; expectHeatmapEquals(heatmap1, heatmapInfo1); expectHeatmapEquals(heatmap2, heatmapInfo2); @@ -366,7 +340,7 @@ void runTests() { }); testWidgets('update heatmaps correctly', (WidgetTester tester) async { - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); final Key key = GlobalKey(); await tester.pumpWidget( @@ -384,8 +358,7 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; final Heatmap heatmap1New = heatmap1.copyWith( dataParam: heatmap1.data.sublist(5), @@ -415,17 +388,14 @@ void runTests() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingHeatmapInfo()) { - final Heatmap heatmapInfo1 = (await inspector.getHeatmapInfo( - heatmap1.mapsId, - mapId: mapId, - ))!; + final Heatmap heatmapInfo1 = (await inspector.getHeatmapInfo(heatmap1.mapsId, mapId: mapId))!; expectHeatmapEquals(heatmap1New, heatmapInfo1); } }); testWidgets('remove heatmaps correctly', (WidgetTester tester) async { - final Completer mapIdCompleter = Completer(); + final mapIdCompleter = Completer(); final Key key = GlobalKey(); await tester.pumpWidget( @@ -443,8 +413,7 @@ void runTests() { ); final int mapId = await mapIdCompleter.future; - final GoogleMapsInspectorPlatform inspector = - GoogleMapsInspectorPlatform.instance!; + final GoogleMapsInspectorPlatform inspector = GoogleMapsInspectorPlatform.instance!; await tester.pumpWidget( Directionality( @@ -462,10 +431,7 @@ void runTests() { await tester.pumpAndSettle(const Duration(seconds: 3)); if (inspector.supportsGettingHeatmapInfo()) { - final Heatmap? heatmapInfo1 = await inspector.getHeatmapInfo( - heatmap1.mapsId, - mapId: mapId, - ); + final Heatmap? heatmapInfo1 = await inspector.getHeatmapInfo(heatmap1.mapsId, mapId: mapId); expect(heatmapInfo1, isNull); } @@ -487,25 +453,17 @@ class _DebugTileProvider implements TileProvider { @override Future getTile(int x, int y, int? zoom) async { - final ui.PictureRecorder recorder = ui.PictureRecorder(); - final Canvas canvas = Canvas(recorder); - final TextSpan textSpan = TextSpan(text: '$x,$y', style: textStyle); - final TextPainter textPainter = TextPainter( - text: textSpan, - textDirection: TextDirection.ltr, - ); + final recorder = ui.PictureRecorder(); + final canvas = Canvas(recorder); + final textSpan = TextSpan(text: '$x,$y', style: textStyle); + final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr); textPainter.layout(maxWidth: width.toDouble()); textPainter.paint(canvas, Offset.zero); - canvas.drawRect( - Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), - boxPaint, - ); + canvas.drawRect(Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), boxPaint); final ui.Picture picture = recorder.endRecording(); final Uint8List byteData = await picture .toImage(width, height) - .then( - (ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png), - ) + .then((ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png)) .then((ByteData? byteData) => byteData!.buffer.asUint8List()); return Tile(width, height, byteData); } diff --git a/packages/google_maps_flutter/example/lib/animate_camera.dart b/packages/google_maps_flutter/example/lib/animate_camera.dart index dcf5a4872..8e0a3bbec 100644 --- a/packages/google_maps_flutter/example/lib/animate_camera.dart +++ b/packages/google_maps_flutter/example/lib/animate_camera.dart @@ -10,8 +10,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; class AnimateCameraPage extends GoogleMapExampleAppPage { - const AnimateCameraPage({super.key}) - : super(const Icon(Icons.map), 'Camera control, animated'); + const AnimateCameraPage({super.key}) : super(const Icon(Icons.map), 'Camera control, animated'); @override Widget build(BuildContext context) { @@ -45,9 +44,7 @@ class AnimateCameraState extends State { height: 200.0, child: GoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: LatLng(0.0, 0.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(0.0, 0.0)), ), ), ), @@ -74,9 +71,7 @@ class AnimateCameraState extends State { TextButton( onPressed: () { mapController?.animateCamera( - CameraUpdate.newLatLng( - const LatLng(56.1725505, 10.1850512), - ), + CameraUpdate.newLatLng(const LatLng(56.1725505, 10.1850512)), ); }, child: const Text('newLatLng'), @@ -98,19 +93,14 @@ class AnimateCameraState extends State { TextButton( onPressed: () { mapController?.animateCamera( - CameraUpdate.newLatLngZoom( - const LatLng(37.4231613, -122.087159), - 11.0, - ), + CameraUpdate.newLatLngZoom(const LatLng(37.4231613, -122.087159), 11.0), ); }, child: const Text('newLatLngZoom'), ), TextButton( onPressed: () { - mapController?.animateCamera( - CameraUpdate.scrollBy(150.0, -225.0), - ); + mapController?.animateCamera(CameraUpdate.scrollBy(150.0, -225.0)); }, child: const Text('scrollBy'), ), diff --git a/packages/google_maps_flutter/example/lib/clustering.dart b/packages/google_maps_flutter/example/lib/clustering.dart index f9ac0a882..502babbf8 100644 --- a/packages/google_maps_flutter/example/lib/clustering.dart +++ b/packages/google_maps_flutter/example/lib/clustering.dart @@ -12,8 +12,7 @@ import 'page.dart'; /// Page for demonstrating marker clustering support. class ClusteringPage extends GoogleMapExampleAppPage { /// Default Constructor. - const ClusteringPage({super.key}) - : super(const Icon(Icons.place), 'Manage clustering'); + const ClusteringPage({super.key}) : super(const Icon(Icons.place), 'Manage clustering'); @override Widget build(BuildContext context) { @@ -60,8 +59,7 @@ class ClusteringBodyState extends State { GoogleMapController? controller; /// Map of clusterManagers with identifier as the key. - Map clusterManagers = - {}; + Map clusterManagers = {}; /// Map of markers with identifier as the key. Map markers = {}; @@ -102,9 +100,7 @@ class ClusteringBodyState extends State { } selectedMarker = markerId; final Marker newMarker = tappedMarker.copyWith( - iconParam: BitmapDescriptor.defaultMarkerWithHue( - BitmapDescriptor.hueGreen, - ), + iconParam: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueGreen), ); markers[markerId] = newMarker; }); @@ -116,14 +112,11 @@ class ClusteringBodyState extends State { return; } - final String clusterManagerIdVal = - 'cluster_manager_id_$_clusterManagerIdCounter'; + final clusterManagerIdVal = 'cluster_manager_id_$_clusterManagerIdCounter'; _clusterManagerIdCounter++; - final ClusterManagerId clusterManagerId = ClusterManagerId( - clusterManagerIdVal, - ); + final clusterManagerId = ClusterManagerId(clusterManagerIdVal); - final ClusterManager clusterManager = ClusterManager( + final clusterManager = ClusterManager( clusterManagerId: clusterManagerId, onClusterTap: (Cluster cluster) => setState(() { lastCluster = cluster; @@ -140,8 +133,7 @@ class ClusteringBodyState extends State { setState(() { // Remove markers managed by cluster manager to be removed. markers.removeWhere( - (MarkerId key, Marker marker) => - marker.clusterManagerId == clusterManager.clusterManagerId, + (MarkerId key, Marker marker) => marker.clusterManagerId == clusterManager.clusterManagerId, ); // Remove cluster manager. clusterManagers.remove(clusterManager.clusterManagerId); @@ -149,22 +141,19 @@ class ClusteringBodyState extends State { } void _addMarkersToCluster(ClusterManager clusterManager) { - for (int i = 0; i < _markersToAddToClusterManagerCount; i++) { - final String markerIdVal = - '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; + for (var i = 0; i < _markersToAddToClusterManagerCount; i++) { + final markerIdVal = '${clusterManager.clusterManagerId.value}_marker_id_$_markerIdCounter'; _markerIdCounter++; - final MarkerId markerId = MarkerId(markerIdVal); + final markerId = MarkerId(markerIdVal); - final int clusterManagerIndex = clusterManagers.values.toList().indexOf( - clusterManager, - ); + final int clusterManagerIndex = clusterManagers.values.toList().indexOf(clusterManager); // Add additional offset to longitude for each cluster manager to space // out markers in different cluster managers. final double clusterManagerLongitudeOffset = clusterManagerIndex * _clusterManagerLongitudeOffset; - final Marker marker = Marker( + final marker = Marker( clusterManagerId: clusterManager.clusterManagerId, markerId: markerId, position: LatLng( @@ -196,9 +185,7 @@ class ClusteringBodyState extends State { final Marker marker = markers[markerId]!; final double current = marker.alpha; markers[markerId] = marker.copyWith( - alphaParam: current == _fullyVisibleAlpha - ? _halfVisibleAlpha - : _fullyVisibleAlpha, + alphaParam: current == _fullyVisibleAlpha ? _halfVisibleAlpha : _fullyVisibleAlpha, ); } setState(() {}); @@ -236,8 +223,7 @@ class ClusteringBodyState extends State { TextButton( onPressed: clusterManagers.isEmpty ? null - : () => - _removeClusterManager(clusterManagers.values.last), + : () => _removeClusterManager(clusterManagers.values.last), child: const Text('Remove cluster manager'), ), ], @@ -245,8 +231,7 @@ class ClusteringBodyState extends State { Wrap( alignment: WrapAlignment.spaceEvenly, children: [ - for (final MapEntry - clusterEntry + for (final MapEntry clusterEntry in clusterManagers.entries) TextButton( onPressed: () => _addMarkersToCluster(clusterEntry.value), @@ -269,9 +254,7 @@ class ClusteringBodyState extends State { child: const Text('Remove selected marker'), ), TextButton( - onPressed: markers.isEmpty - ? null - : () => _changeMarkersAlpha(), + onPressed: markers.isEmpty ? null : () => _changeMarkersAlpha(), child: const Text('Change all markers alpha'), ), ], diff --git a/packages/google_maps_flutter/example/lib/custom_marker_icon.dart b/packages/google_maps_flutter/example/lib/custom_marker_icon.dart index 02daad7a5..dd082ae26 100644 --- a/packages/google_maps_flutter/example/lib/custom_marker_icon.dart +++ b/packages/google_maps_flutter/example/lib/custom_marker_icon.dart @@ -9,9 +9,9 @@ import 'package:flutter/material.dart'; /// Returns a generated png image in [ByteData] format with the requested size. Future createCustomMarkerIconImage({required Size size}) async { - final ui.PictureRecorder recorder = ui.PictureRecorder(); - final Canvas canvas = Canvas(recorder); - final _MarkerPainter painter = _MarkerPainter(); + final recorder = ui.PictureRecorder(); + final canvas = Canvas(recorder); + final painter = _MarkerPainter(); painter.paint(canvas, size); @@ -20,9 +20,7 @@ Future createCustomMarkerIconImage({required Size size}) async { size.height.floor(), ); - final ByteData? bytes = await image.toByteData( - format: ui.ImageByteFormat.png, - ); + final ByteData? bytes = await image.toByteData(format: ui.ImageByteFormat.png); return bytes!; } @@ -30,7 +28,7 @@ class _MarkerPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { final Rect rect = Offset.zero & size; - const RadialGradient gradient = RadialGradient( + const gradient = RadialGradient( colors: [Colors.yellow, Colors.red], stops: [0.4, 1.0], ); diff --git a/packages/google_maps_flutter/example/lib/ground_overlay.dart b/packages/google_maps_flutter/example/lib/ground_overlay.dart index a81112bb4..424d313f2 100644 --- a/packages/google_maps_flutter/example/lib/ground_overlay.dart +++ b/packages/google_maps_flutter/example/lib/ground_overlay.dart @@ -10,8 +10,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; class GroundOverlayPage extends GoogleMapExampleAppPage { - const GroundOverlayPage({super.key}) - : super(const Icon(Icons.map), 'Ground overlay'); + const GroundOverlayPage({super.key}) : super(const Icon(Icons.map), 'Ground overlay'); @override Widget build(BuildContext context) { @@ -58,7 +57,7 @@ class GroundOverlayBodyState extends State { _groundOverlayIndex += 1; - final GroundOverlay overlay = GroundOverlay.fromBounds( + final overlay = GroundOverlay.fromBounds( groundOverlayId: GroundOverlayId('ground_overlay_$_groundOverlayIndex'), image: image, bounds: _currentBounds, @@ -81,12 +80,8 @@ class GroundOverlayBodyState extends State { return; } setState(() { - final double transparency = _groundOverlay!.transparency == 0.0 - ? 0.5 - : 0.0; - _groundOverlay = _groundOverlay!.copyWith( - transparencyParam: transparency, - ); + final transparency = _groundOverlay!.transparency == 0.0 ? 0.5 : 0.0; + _groundOverlay = _groundOverlay!.copyWith(transparencyParam: transparency); }); } @@ -95,9 +90,7 @@ class GroundOverlayBodyState extends State { return; } setState(() { - _groundOverlay = _groundOverlay!.copyWith( - visibleParam: !_groundOverlay!.visible, - ); + _groundOverlay = _groundOverlay!.copyWith(visibleParam: !_groundOverlay!.visible); }); } @@ -110,9 +103,7 @@ class GroundOverlayBodyState extends State { @override Widget build(BuildContext context) { - final Set overlays = { - if (_groundOverlay != null) _groundOverlay!, - }; + final overlays = {if (_groundOverlay != null) _groundOverlay!}; return Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.spaceEvenly, @@ -120,10 +111,7 @@ class GroundOverlayBodyState extends State { children: [ Expanded( child: GoogleMap( - initialCameraPosition: const CameraPosition( - target: _mapCenter, - zoom: 14.0, - ), + initialCameraPosition: const CameraPosition(target: _mapCenter, zoom: 14.0), groundOverlays: overlays, onMapCreated: _onMapCreated, ), diff --git a/packages/google_maps_flutter/example/lib/heatmap.dart b/packages/google_maps_flutter/example/lib/heatmap.dart index f902a57cf..2772a097a 100644 --- a/packages/google_maps_flutter/example/lib/heatmap.dart +++ b/packages/google_maps_flutter/example/lib/heatmap.dart @@ -94,10 +94,7 @@ class HeatmapBodyState extends State { width: 350.0, height: 300.0, child: GoogleMap( - initialCameraPosition: const CameraPosition( - target: sanFrancisco, - zoom: 13, - ), + initialCameraPosition: const CameraPosition(target: sanFrancisco, zoom: 13), heatmaps: { Heatmap( heatmapId: const HeatmapId('test'), @@ -126,15 +123,11 @@ class HeatmapBodyState extends State { Column( children: [ TextButton( - onPressed: disabledPoints.isNotEmpty - ? _addPoint - : null, + onPressed: disabledPoints.isNotEmpty ? _addPoint : null, child: const Text('Add point'), ), TextButton( - onPressed: enabledPoints.isNotEmpty - ? _removePoint - : null, + onPressed: enabledPoints.isNotEmpty ? _removePoint : null, child: const Text('Remove point'), ), ], diff --git a/packages/google_maps_flutter/example/lib/lite_mode.dart b/packages/google_maps_flutter/example/lib/lite_mode.dart index 2e6e9d088..6b182e432 100644 --- a/packages/google_maps_flutter/example/lib/lite_mode.dart +++ b/packages/google_maps_flutter/example/lib/lite_mode.dart @@ -34,10 +34,7 @@ class _LiteModeBody extends StatelessWidget { child: SizedBox( width: 300.0, height: 300.0, - child: GoogleMap( - initialCameraPosition: _kInitialPosition, - liteModeEnabled: true, - ), + child: GoogleMap(initialCameraPosition: _kInitialPosition, liteModeEnabled: true), ), ), ), diff --git a/packages/google_maps_flutter/example/lib/map_click.dart b/packages/google_maps_flutter/example/lib/map_click.dart index 054dd6468..96813d0c6 100644 --- a/packages/google_maps_flutter/example/lib/map_click.dart +++ b/packages/google_maps_flutter/example/lib/map_click.dart @@ -38,7 +38,7 @@ class _MapClickBodyState extends State<_MapClickBody> { @override Widget build(BuildContext context) { - final GoogleMap googleMap = GoogleMap( + final googleMap = GoogleMap( onMapCreated: onMapCreated, initialCameraPosition: _kInitialPosition, onTap: (LatLng pos) { @@ -53,45 +53,28 @@ class _MapClickBodyState extends State<_MapClickBody> { }, ); - final List columnChildren = [ + final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), ]; if (mapController != null) { - final String lastTap = 'Tap:\n${_lastTap ?? ""}\n'; - final String lastLongPress = 'Long press:\n${_lastLongPress ?? ""}'; - columnChildren.add( - Center(child: Text(lastTap, textAlign: TextAlign.center)), - ); - columnChildren.add( - Center( - child: Text( - _lastTap != null ? 'Tapped' : '', - textAlign: TextAlign.center, - ), - ), - ); + final lastTap = 'Tap:\n${_lastTap ?? ""}\n'; + final lastLongPress = 'Long press:\n${_lastLongPress ?? ""}'; + columnChildren.add(Center(child: Text(lastTap, textAlign: TextAlign.center))); columnChildren.add( - Center(child: Text(lastLongPress, textAlign: TextAlign.center)), + Center(child: Text(_lastTap != null ? 'Tapped' : '', textAlign: TextAlign.center)), ); + columnChildren.add(Center(child: Text(lastLongPress, textAlign: TextAlign.center))); columnChildren.add( Center( - child: Text( - _lastLongPress != null ? 'Long pressed' : '', - textAlign: TextAlign.center, - ), + child: Text(_lastLongPress != null ? 'Long pressed' : '', textAlign: TextAlign.center), ), ); } - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } Future onMapCreated(GoogleMapController controller) async { diff --git a/packages/google_maps_flutter/example/lib/map_coordinates.dart b/packages/google_maps_flutter/example/lib/map_coordinates.dart index 744c6f1a0..8b1ded165 100644 --- a/packages/google_maps_flutter/example/lib/map_coordinates.dart +++ b/packages/google_maps_flutter/example/lib/map_coordinates.dart @@ -14,8 +14,7 @@ const CameraPosition _kInitialPosition = CameraPosition( ); class MapCoordinatesPage extends GoogleMapExampleAppPage { - const MapCoordinatesPage({super.key}) - : super(const Icon(Icons.map), 'Map coordinates'); + const MapCoordinatesPage({super.key}) : super(const Icon(Icons.map), 'Map coordinates'); @override Widget build(BuildContext context) { @@ -41,11 +40,10 @@ class _MapCoordinatesBodyState extends State<_MapCoordinatesBody> { @override Widget build(BuildContext context) { - final GoogleMap googleMap = GoogleMap( + final googleMap = GoogleMap( onMapCreated: onMapCreated, initialCameraPosition: _kInitialPosition, - onCameraIdle: - _updateVisibleRegion, // https://github.com/flutter/flutter/issues/54758 + onCameraIdle: _updateVisibleRegion, // https://github.com/flutter/flutter/issues/54758 ); return NotificationListener( @@ -57,9 +55,7 @@ class _MapCoordinatesBodyState extends State<_MapCoordinatesBody> { children: [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), if (mapController != null) Center( diff --git a/packages/google_maps_flutter/example/lib/map_map_id.dart b/packages/google_maps_flutter/example/lib/map_map_id.dart index 44751445e..592c2251c 100644 --- a/packages/google_maps_flutter/example/lib/map_map_id.dart +++ b/packages/google_maps_flutter/example/lib/map_map_id.dart @@ -8,8 +8,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; class MapIdPage extends GoogleMapExampleAppPage { - const MapIdPage({super.key}) - : super(const Icon(Icons.map), 'Cloud-based maps styling'); + const MapIdPage({super.key}) : super(const Icon(Icons.map), 'Cloud-based maps styling'); @override Widget build(BuildContext context) { @@ -49,22 +48,17 @@ class MapIdBodyState extends State { @override Widget build(BuildContext context) { - final GoogleMap googleMap = GoogleMap( + final googleMap = GoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), key: _key, cloudMapId: _mapId, ); - final List columnChildren = [ + final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), Padding( padding: const EdgeInsets.all(10.0), @@ -82,10 +76,7 @@ class MapIdBodyState extends State { ), ]; - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } @override diff --git a/packages/google_maps_flutter/example/lib/map_ui.dart b/packages/google_maps_flutter/example/lib/map_ui.dart index a581aa0fb..0c97e489c 100644 --- a/packages/google_maps_flutter/example/lib/map_ui.dart +++ b/packages/google_maps_flutter/example/lib/map_ui.dart @@ -96,9 +96,7 @@ class MapUiBodyState extends State { Widget _latLngBoundsToggler() { return TextButton( child: Text( - _cameraTargetBounds.bounds == null - ? 'bound camera target' - : 'release camera target', + _cameraTargetBounds.bounds == null ? 'bound camera target' : 'release camera target', ), onPressed: () { setState(() { @@ -112,9 +110,7 @@ class MapUiBodyState extends State { Widget _zoomBoundsToggler() { return TextButton( - child: Text( - _minMaxZoomPreference.minZoom == null ? 'bound zoom' : 'release zoom', - ), + child: Text(_minMaxZoomPreference.minZoom == null ? 'bound zoom' : 'release zoom'), onPressed: () { setState(() { _minMaxZoomPreference = _minMaxZoomPreference.minZoom == null @@ -126,8 +122,7 @@ class MapUiBodyState extends State { } Widget _mapTypeCycler() { - final MapType nextType = - MapType.values[(_mapType.index + 1) % MapType.values.length]; + final MapType nextType = MapType.values[(_mapType.index + 1) % MapType.values.length]; return TextButton( child: Text('change map type to $nextType'), onPressed: () { @@ -184,9 +179,7 @@ class MapUiBodyState extends State { Widget _zoomControlsToggler() { return TextButton( - child: Text( - '${_zoomControlsEnabled ? 'disable' : 'enable'} zoom controls', - ), + child: Text('${_zoomControlsEnabled ? 'disable' : 'enable'} zoom controls'), onPressed: () { setState(() { _zoomControlsEnabled = !_zoomControlsEnabled; @@ -208,9 +201,7 @@ class MapUiBodyState extends State { Widget _myLocationToggler() { return TextButton( - child: Text( - '${_myLocationEnabled ? 'disable' : 'enable'} my location marker', - ), + child: Text('${_myLocationEnabled ? 'disable' : 'enable'} my location marker'), onPressed: () { setState(() { _myLocationEnabled = !_myLocationEnabled; @@ -221,9 +212,7 @@ class MapUiBodyState extends State { Widget _myLocationButtonToggler() { return TextButton( - child: Text( - '${_myLocationButtonEnabled ? 'disable' : 'enable'} my location button', - ), + child: Text('${_myLocationButtonEnabled ? 'disable' : 'enable'} my location button'), onPressed: () { setState(() { _myLocationButtonEnabled = !_myLocationButtonEnabled; @@ -254,9 +243,7 @@ class MapUiBodyState extends State { child: Text('${_nightMode ? 'disable' : 'enable'} night mode'), onPressed: () async { _nightMode = !_nightMode; - final String style = _nightMode - ? await _getFileData('assets/night_mode.json') - : ''; + final String style = _nightMode ? await _getFileData('assets/night_mode.json') : ''; setState(() { _mapStyle = style; }); @@ -266,7 +253,7 @@ class MapUiBodyState extends State { @override Widget build(BuildContext context) { - final GoogleMap googleMap = GoogleMap( + final googleMap = GoogleMap( onMapCreated: onMapCreated, initialCameraPosition: _kInitialPosition, compassEnabled: _compassEnabled, @@ -287,12 +274,10 @@ class MapUiBodyState extends State { onCameraMove: _updateCameraPosition, ); - final List columnChildren = [ + final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), ]; @@ -329,10 +314,7 @@ class MapUiBodyState extends State { ), ); } - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } void _updateCameraPosition(CameraPosition position) { diff --git a/packages/google_maps_flutter/example/lib/marker_icons.dart b/packages/google_maps_flutter/example/lib/marker_icons.dart index 80c82ac67..e7981379e 100644 --- a/packages/google_maps_flutter/example/lib/marker_icons.dart +++ b/packages/google_maps_flutter/example/lib/marker_icons.dart @@ -15,8 +15,7 @@ import 'custom_marker_icon.dart'; import 'page.dart'; class MarkerIconsPage extends GoogleMapExampleAppPage { - const MarkerIconsPage({super.key}) - : super(const Icon(Icons.image), 'Marker icons'); + const MarkerIconsPage({super.key}) : super(const Icon(Icons.image), 'Marker icons'); @override Widget build(BuildContext context) { @@ -45,8 +44,7 @@ class MarkerIconsBodyState extends State { AssetMapBitmap? _markerIconAsset; BytesMapBitmap? _markerIconBytes; final int _markersAmountPerType = 15; - bool get _customSizeEnabled => - _currentSizeOption != _MarkerSizeOption.original; + bool get _customSizeEnabled => _currentSizeOption != _MarkerSizeOption.original; @override Widget build(BuildContext context) { @@ -63,10 +61,7 @@ class MarkerIconsBodyState extends State { width: 350.0, height: 300.0, child: GoogleMap( - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), markers: _markers, onMapCreated: _onMapCreated, ), @@ -74,11 +69,7 @@ class MarkerIconsBodyState extends State { ), TextButton( onPressed: () => _toggleScaling(context), - child: Text( - _scalingEnabled - ? 'Disable auto scaling' - : 'Enable auto scaling', - ), + child: Text(_scalingEnabled ? 'Disable auto scaling' : 'Enable auto scaling'), ), if (_scalingEnabled) ...[ Container( @@ -90,10 +81,7 @@ class MarkerIconsBodyState extends State { 'Reference box with size of ${referenceSize.width} x ${referenceSize.height} in logical pixels.', ), const SizedBox(height: 10), - Image.asset( - 'assets/red_square.png', - scale: _mipMapsEnabled ? null : 1.0, - ), + Image.asset('assets/red_square.png', scale: _mipMapsEnabled ? null : 1.0), const Text('Asset image rendered with flutter'), const SizedBox(height: 10), Row( @@ -111,9 +99,7 @@ class MarkerIconsBodyState extends State { }); } }, - items: _MarkerSizeOption.values.map(( - _MarkerSizeOption option, - ) { + items: _MarkerSizeOption.values.map((_MarkerSizeOption option) { return DropdownMenuItem<_MarkerSizeOption>( value: option, child: Text(_getMarkerSizeOptionName(option)), @@ -125,9 +111,7 @@ class MarkerIconsBodyState extends State { ], TextButton( onPressed: () => _toggleMipMaps(context), - child: Text( - _mipMapsEnabled ? 'Disable mipmaps' : 'Enable mipmaps', - ), + child: Text(_mipMapsEnabled ? 'Disable mipmaps' : 'Enable mipmaps'), ), ], ), @@ -178,15 +162,9 @@ class MarkerIconsBodyState extends State { if (width != null && height != null) { return Size(width, height); } else if (width != null) { - return Size( - width, - width * _markerAssetImageSize.height / _markerAssetImageSize.width, - ); + return Size(width, width * _markerAssetImageSize.height / _markerAssetImageSize.width); } else if (height != null) { - return Size( - height * _markerAssetImageSize.width / _markerAssetImageSize.height, - height, - ); + return Size(height * _markerAssetImageSize.width / _markerAssetImageSize.height, height); } else { return _markerAssetImageSize; } @@ -209,10 +187,7 @@ class MarkerIconsBodyState extends State { } Marker _createAssetMarker(int index) { - final LatLng position = LatLng( - _kMapCenter.latitude - (index * 0.5), - _kMapCenter.longitude - 1, - ); + final position = LatLng(_kMapCenter.latitude - (index * 0.5), _kMapCenter.longitude - 1); return Marker( markerId: MarkerId('marker_asset_$index'), @@ -222,10 +197,7 @@ class MarkerIconsBodyState extends State { } Marker _createBytesMarker(int index) { - final LatLng position = LatLng( - _kMapCenter.latitude - (index * 0.5), - _kMapCenter.longitude + 1, - ); + final position = LatLng(_kMapCenter.latitude - (index * 0.5), _kMapCenter.longitude + 1); return Marker( markerId: MarkerId('marker_bytes_$index'), @@ -235,8 +207,8 @@ class MarkerIconsBodyState extends State { } void _updateMarkers() { - final Set markers = {}; - for (int i = 0; i < _markersAmountPerType; i++) { + final markers = {}; + for (var i = 0; i < _markersAmountPerType; i++) { if (_markerIconAsset != null) { markers.add(_createAssetMarker(i)); } @@ -251,26 +223,20 @@ class MarkerIconsBodyState extends State { Future _updateMarkerAssetImage(BuildContext context) async { // Width and height are used only for custom size. - final ( - double? width, - double? height, - ) = _scalingEnabled && _customSizeEnabled + final (double? width, double? height) = _scalingEnabled && _customSizeEnabled ? _getCurrentMarkerSize() : (null, null); AssetMapBitmap assetMapBitmap; if (_mipMapsEnabled) { - final ImageConfiguration imageConfiguration = - createLocalImageConfiguration(context); + final ImageConfiguration imageConfiguration = createLocalImageConfiguration(context); assetMapBitmap = await AssetMapBitmap.create( imageConfiguration, 'assets/red_square.png', width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); } else { // Uses hardcoded asset path @@ -280,9 +246,7 @@ class MarkerIconsBodyState extends State { 'assets/red_square.png', width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); } @@ -290,15 +254,13 @@ class MarkerIconsBodyState extends State { } Future _updateMarkerBytesImage(BuildContext context) async { - final double? devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf( - context, - ); + final double? devicePixelRatio = MediaQuery.maybeDevicePixelRatioOf(context); final Size bitmapLogicalSize = _getMarkerReferenceSize(); final double? imagePixelRatio = _scalingEnabled ? devicePixelRatio : null; // Create canvasSize with physical marker size - final Size canvasSize = Size( + final canvasSize = Size( bitmapLogicalSize.width * (imagePixelRatio ?? 1.0), bitmapLogicalSize.height * (imagePixelRatio ?? 1.0), ); @@ -306,21 +268,16 @@ class MarkerIconsBodyState extends State { final ByteData bytes = await createCustomMarkerIconImage(size: canvasSize); // Width and height are used only for custom size. - final ( - double? width, - double? height, - ) = _scalingEnabled && _customSizeEnabled + final (double? width, double? height) = _scalingEnabled && _customSizeEnabled ? _getCurrentMarkerSize() : (null, null); - final BytesMapBitmap bitmap = BytesMapBitmap( + final bitmap = BytesMapBitmap( bytes.buffer.asUint8List(), imagePixelRatio: imagePixelRatio, width: width, height: height, - bitmapScaling: _scalingEnabled - ? MapBitmapScaling.auto - : MapBitmapScaling.none, + bitmapScaling: _scalingEnabled ? MapBitmapScaling.auto : MapBitmapScaling.none, ); _updateBytesBitmap(bitmap); diff --git a/packages/google_maps_flutter/example/lib/move_camera.dart b/packages/google_maps_flutter/example/lib/move_camera.dart index 8b0b1fd05..344111348 100644 --- a/packages/google_maps_flutter/example/lib/move_camera.dart +++ b/packages/google_maps_flutter/example/lib/move_camera.dart @@ -10,8 +10,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; class MoveCameraPage extends GoogleMapExampleAppPage { - const MoveCameraPage({super.key}) - : super(const Icon(Icons.map), 'Camera control'); + const MoveCameraPage({super.key}) : super(const Icon(Icons.map), 'Camera control'); @override Widget build(BuildContext context) { @@ -45,9 +44,7 @@ class MoveCameraState extends State { height: 200.0, child: GoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: LatLng(0.0, 0.0), - ), + initialCameraPosition: const CameraPosition(target: LatLng(0.0, 0.0)), ), ), ), @@ -74,9 +71,7 @@ class MoveCameraState extends State { TextButton( onPressed: () { mapController?.moveCamera( - CameraUpdate.newLatLng( - const LatLng(56.1725505, 10.1850512), - ), + CameraUpdate.newLatLng(const LatLng(56.1725505, 10.1850512)), ); }, child: const Text('newLatLng'), @@ -98,19 +93,14 @@ class MoveCameraState extends State { TextButton( onPressed: () { mapController?.moveCamera( - CameraUpdate.newLatLngZoom( - const LatLng(37.4231613, -122.087159), - 11.0, - ), + CameraUpdate.newLatLngZoom(const LatLng(37.4231613, -122.087159), 11.0), ); }, child: const Text('newLatLngZoom'), ), TextButton( onPressed: () { - mapController?.moveCamera( - CameraUpdate.scrollBy(150.0, -225.0), - ); + mapController?.moveCamera(CameraUpdate.scrollBy(150.0, -225.0)); }, child: const Text('scrollBy'), ), @@ -120,9 +110,7 @@ class MoveCameraState extends State { children: [ TextButton( onPressed: () { - mapController?.moveCamera( - CameraUpdate.zoomBy(-0.5, const Offset(30.0, 20.0)), - ); + mapController?.moveCamera(CameraUpdate.zoomBy(-0.5, const Offset(30.0, 20.0))); }, child: const Text('zoomBy with focus'), ), diff --git a/packages/google_maps_flutter/example/lib/padding.dart b/packages/google_maps_flutter/example/lib/padding.dart index 159fdeb29..d1e29430f 100644 --- a/packages/google_maps_flutter/example/lib/padding.dart +++ b/packages/google_maps_flutter/example/lib/padding.dart @@ -9,8 +9,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; class PaddingPage extends GoogleMapExampleAppPage { - const PaddingPage({super.key}) - : super(const Icon(Icons.map), 'Add padding to the map'); + const PaddingPage({super.key}) : super(const Icon(Icons.map), 'Add padding to the map'); @override Widget build(BuildContext context) { @@ -34,21 +33,16 @@ class MarkerIconsBodyState extends State { @override Widget build(BuildContext context) { - final GoogleMap googleMap = GoogleMap( + final googleMap = GoogleMap( onMapCreated: _onMapCreated, - initialCameraPosition: const CameraPosition( - target: _kMapCenter, - zoom: 7.0, - ), + initialCameraPosition: const CameraPosition(target: _kMapCenter, zoom: 7.0), padding: _padding, ); - final List columnChildren = [ + final columnChildren = [ Padding( padding: const EdgeInsets.all(10.0), - child: Center( - child: SizedBox(width: 300.0, height: 200.0, child: googleMap), - ), + child: Center(child: SizedBox(width: 300.0, height: 200.0, child: googleMap)), ), const Padding( padding: EdgeInsets.only(top: 20), @@ -63,10 +57,7 @@ class MarkerIconsBodyState extends State { columnChildren.addAll([_paddingInput(), _buttons()]); - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: columnChildren, - ); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: columnChildren); } void _onMapCreated(GoogleMapController controllerParam) { diff --git a/packages/google_maps_flutter/example/lib/place_circle.dart b/packages/google_maps_flutter/example/lib/place_circle.dart index 65367511d..e56ec563f 100644 --- a/packages/google_maps_flutter/example/lib/place_circle.dart +++ b/packages/google_maps_flutter/example/lib/place_circle.dart @@ -10,8 +10,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; class PlaceCirclePage extends GoogleMapExampleAppPage { - const PlaceCirclePage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place circle'); + const PlaceCirclePage({super.key}) : super(const Icon(Icons.linear_scale), 'Place circle'); @override Widget build(BuildContext context) { @@ -37,12 +36,7 @@ class PlaceCircleBodyState extends State { // Values when toggling circle color int fillColorsIndex = 0; int strokeColorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling circle stroke width int widthsIndex = 0; @@ -82,11 +76,11 @@ class PlaceCircleBodyState extends State { return; } - final String circleIdVal = 'circle_id_$_circleIdCounter'; + final circleIdVal = 'circle_id_$_circleIdCounter'; _circleIdCounter++; - final CircleId circleId = CircleId(circleIdVal); + final circleId = CircleId(circleIdVal); - final Circle circle = Circle( + final circle = Circle( circleId: circleId, consumeTapEvents: true, strokeColor: Colors.orange, @@ -132,9 +126,7 @@ class PlaceCircleBodyState extends State { void _changeStrokeWidth(CircleId circleId) { final Circle circle = circles[circleId]!; setState(() { - circles[circleId] = circle.copyWith( - strokeWidthParam: widths[++widthsIndex % widths.length], - ); + circles[circleId] = circle.copyWith(strokeWidthParam: widths[++widthsIndex % widths.length]); }); } @@ -170,15 +162,11 @@ class PlaceCircleBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), ], diff --git a/packages/google_maps_flutter/example/lib/place_marker.dart b/packages/google_maps_flutter/example/lib/place_marker.dart index 3611a9aa5..c51d9fbb7 100644 --- a/packages/google_maps_flutter/example/lib/place_marker.dart +++ b/packages/google_maps_flutter/example/lib/place_marker.dart @@ -15,8 +15,7 @@ import 'custom_marker_icon.dart'; import 'page.dart'; class PlaceMarkerPage extends GoogleMapExampleAppPage { - const PlaceMarkerPage({super.key}) - : super(const Icon(Icons.place), 'Place marker'); + const PlaceMarkerPage({super.key}) : super(const Icon(Icons.place), 'Place marker'); @override Widget build(BuildContext context) { @@ -66,9 +65,7 @@ class PlaceMarkerBodyState extends State { } selectedMarker = markerId; final Marker newMarker = tappedMarker.copyWith( - iconParam: BitmapDescriptor.defaultMarkerWithHue( - BitmapDescriptor.hueGreen, - ), + iconParam: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueGreen), ); markers[markerId] = newMarker; @@ -94,10 +91,7 @@ class PlaceMarkerBodyState extends State { builder: (BuildContext context) { return AlertDialog( actions: [ - TextButton( - child: const Text('OK'), - onPressed: () => Navigator.of(context).pop(), - ), + TextButton(child: const Text('OK'), onPressed: () => Navigator.of(context).pop()), ], content: Padding( padding: const EdgeInsets.symmetric(vertical: 66), @@ -122,11 +116,11 @@ class PlaceMarkerBodyState extends State { return; } - final String markerIdVal = 'marker_id_$_markerIdCounter'; + final markerIdVal = 'marker_id_$_markerIdCounter'; _markerIdCounter++; - final MarkerId markerId = MarkerId(markerIdVal); + final markerId = MarkerId(markerIdVal); - final Marker marker = Marker( + final marker = Marker( markerId: markerId, position: LatLng( center.latitude + sin(_markerIdCounter * pi / 6.0) / 20.0, @@ -154,16 +148,10 @@ class PlaceMarkerBodyState extends State { void _changePosition(MarkerId markerId) { final Marker marker = markers[markerId]!; final LatLng current = marker.position; - final Offset offset = Offset( - center.latitude - current.latitude, - center.longitude - current.longitude, - ); + final offset = Offset(center.latitude - current.latitude, center.longitude - current.longitude); setState(() { markers[markerId] = marker.copyWith( - positionParam: LatLng( - center.latitude + offset.dy, - center.longitude + offset.dx, - ), + positionParam: LatLng(center.latitude + offset.dy, center.longitude + offset.dx), ); }); } @@ -171,7 +159,7 @@ class PlaceMarkerBodyState extends State { void _changeAnchor(MarkerId markerId) { final Marker marker = markers[markerId]!; final Offset currentAnchor = marker.anchor; - final Offset newAnchor = Offset(1.0 - currentAnchor.dy, currentAnchor.dx); + final newAnchor = Offset(1.0 - currentAnchor.dy, currentAnchor.dx); setState(() { markers[markerId] = marker.copyWith(anchorParam: newAnchor); }); @@ -180,7 +168,7 @@ class PlaceMarkerBodyState extends State { Future _changeInfoAnchor(MarkerId markerId) async { final Marker marker = markers[markerId]!; final Offset currentAnchor = marker.infoWindow.anchor; - final Offset newAnchor = Offset(1.0 - currentAnchor.dy, currentAnchor.dx); + final newAnchor = Offset(1.0 - currentAnchor.dy, currentAnchor.dx); setState(() { markers[markerId] = marker.copyWith( infoWindowParam: marker.infoWindow.copyWith(anchorParam: newAnchor), @@ -204,7 +192,7 @@ class PlaceMarkerBodyState extends State { Future _changeInfo(MarkerId markerId) async { final Marker marker = markers[markerId]!; - final String newSnippet = '${marker.infoWindow.snippet!}*'; + final newSnippet = '${marker.infoWindow.snippet!}*'; setState(() { markers[markerId] = marker.copyWith( infoWindowParam: marker.infoWindow.copyWith(snippetParam: newSnippet), @@ -216,9 +204,7 @@ class PlaceMarkerBodyState extends State { final Marker marker = markers[markerId]!; final double current = marker.alpha; setState(() { - markers[markerId] = marker.copyWith( - alphaParam: current < 0.1 ? 1.0 : current * 0.75, - ); + markers[markerId] = marker.copyWith(alphaParam: current < 0.1 ? 1.0 : current * 0.75); }); } @@ -226,9 +212,7 @@ class PlaceMarkerBodyState extends State { final Marker marker = markers[markerId]!; final double current = marker.rotation; setState(() { - markers[markerId] = marker.copyWith( - rotationParam: current == 330.0 ? 0.0 : current + 30.0, - ); + markers[markerId] = marker.copyWith(rotationParam: current == 330.0 ? 0.0 : current + 30.0); }); } @@ -243,9 +227,7 @@ class PlaceMarkerBodyState extends State { final Marker marker = markers[markerId]!; final double current = marker.zIndex; setState(() { - markers[markerId] = marker.copyWith( - zIndexParam: current == 12.0 ? 0.0 : current + 1.0, - ); + markers[markerId] = marker.copyWith(zIndexParam: current == 12.0 ? 0.0 : current + 1.0); }); } @@ -257,7 +239,7 @@ class PlaceMarkerBodyState extends State { } Future _getMarkerIcon(BuildContext context) async { - const Size canvasSize = Size(48, 48); + const canvasSize = Size(48, 48); final ByteData bytes = await createCustomMarkerIconImage(size: canvasSize); return BytesMapBitmap(bytes.buffer.asUint8List()); } @@ -286,9 +268,7 @@ class PlaceMarkerBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('Add')), TextButton( - onPressed: selectedId == null - ? null - : () => _remove(selectedId), + onPressed: selectedId == null ? null : () => _remove(selectedId), child: const Text('Remove'), ), ], @@ -297,63 +277,43 @@ class PlaceMarkerBodyState extends State { alignment: WrapAlignment.spaceEvenly, children: [ TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfo(selectedId), + onPressed: selectedId == null ? null : () => _changeInfo(selectedId), child: const Text('change info'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeInfoAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeInfoAnchor(selectedId), child: const Text('change info anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAlpha(selectedId), + onPressed: selectedId == null ? null : () => _changeAlpha(selectedId), child: const Text('change alpha'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeAnchor(selectedId), + onPressed: selectedId == null ? null : () => _changeAnchor(selectedId), child: const Text('change anchor'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleDraggable(selectedId), + onPressed: selectedId == null ? null : () => _toggleDraggable(selectedId), child: const Text('toggle draggable'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleFlat(selectedId), + onPressed: selectedId == null ? null : () => _toggleFlat(selectedId), child: const Text('toggle flat'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changePosition(selectedId), + onPressed: selectedId == null ? null : () => _changePosition(selectedId), child: const Text('change position'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeRotation(selectedId), + onPressed: selectedId == null ? null : () => _changeRotation(selectedId), child: const Text('change rotation'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _toggleVisible(selectedId), + onPressed: selectedId == null ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( - onPressed: selectedId == null - ? null - : () => _changeZIndex(selectedId), + onPressed: selectedId == null ? null : () => _changeZIndex(selectedId), child: const Text('change zIndex'), ), TextButton( diff --git a/packages/google_maps_flutter/example/lib/place_polygon.dart b/packages/google_maps_flutter/example/lib/place_polygon.dart index 7646e489d..d500601d5 100644 --- a/packages/google_maps_flutter/example/lib/place_polygon.dart +++ b/packages/google_maps_flutter/example/lib/place_polygon.dart @@ -10,8 +10,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; class PlacePolygonPage extends GoogleMapExampleAppPage { - const PlacePolygonPage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place polygon'); + const PlacePolygonPage({super.key}) : super(const Icon(Icons.linear_scale), 'Place polygon'); @override Widget build(BuildContext context) { @@ -38,12 +37,7 @@ class PlacePolygonBodyState extends State { // Values when toggling polygon color int strokeColorsIndex = 0; int fillColorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling polygon width int widthsIndex = 0; @@ -81,10 +75,10 @@ class PlacePolygonBodyState extends State { return; } - final String polygonIdVal = 'polygon_id_$_polygonIdCounter'; - final PolygonId polygonId = PolygonId(polygonIdVal); + final polygonIdVal = 'polygon_id_$_polygonIdCounter'; + final polygonId = PolygonId(polygonIdVal); - final Polygon polygon = Polygon( + final polygon = Polygon( polygonId: polygonId, consumeTapEvents: true, strokeColor: Colors.orange, @@ -148,9 +142,7 @@ class PlacePolygonBodyState extends State { void _addHoles(PolygonId polygonId) { final Polygon polygon = polygons[polygonId]!; setState(() { - polygons[polygonId] = polygon.copyWith( - holesParam: _createHoles(polygonId), - ); + polygons[polygonId] = polygon.copyWith(holesParam: _createHoles(polygonId)); }); } @@ -193,15 +185,11 @@ class PlacePolygonBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( @@ -231,9 +219,7 @@ class PlacePolygonBodyState extends State { child: const Text('remove holes'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) ? null : () => _changeWidth(selectedId), child: const Text('change stroke width'), ), TextButton( @@ -261,7 +247,7 @@ class PlacePolygonBodyState extends State { } List _createPoints() { - final List points = []; + final points = []; final double offset = _polygonIdCounter.ceilToDouble(); points.add(_createLatLng(51.2395 + offset, -3.4314)); points.add(_createLatLng(53.5234 + offset, -3.5314)); @@ -271,17 +257,17 @@ class PlacePolygonBodyState extends State { } List> _createHoles(PolygonId polygonId) { - final List> holes = >[]; + final holes = >[]; final double offset = polygonOffsets[polygonId]!; - final List hole1 = []; + final hole1 = []; hole1.add(_createLatLng(51.8395 + offset, -3.8814)); hole1.add(_createLatLng(52.0234 + offset, -3.9914)); hole1.add(_createLatLng(52.1351 + offset, -4.4435)); hole1.add(_createLatLng(52.0231 + offset, -4.5829)); holes.add(hole1); - final List hole2 = []; + final hole2 = []; hole2.add(_createLatLng(52.2395 + offset, -3.6814)); hole2.add(_createLatLng(52.4234 + offset, -3.7914)); hole2.add(_createLatLng(52.5351 + offset, -4.2435)); diff --git a/packages/google_maps_flutter/example/lib/place_polyline.dart b/packages/google_maps_flutter/example/lib/place_polyline.dart index 2dcee5e0e..a81229784 100644 --- a/packages/google_maps_flutter/example/lib/place_polyline.dart +++ b/packages/google_maps_flutter/example/lib/place_polyline.dart @@ -11,8 +11,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; class PlacePolylinePage extends GoogleMapExampleAppPage { - const PlacePolylinePage({super.key}) - : super(const Icon(Icons.linear_scale), 'Place polyline'); + const PlacePolylinePage({super.key}) : super(const Icon(Icons.linear_scale), 'Place polyline'); @override Widget build(BuildContext context) { @@ -37,23 +36,14 @@ class PlacePolylineBodyState extends State { // Values when toggling polyline color int colorsIndex = 0; - List colors = [ - Colors.purple, - Colors.red, - Colors.green, - Colors.pink, - ]; + List colors = [Colors.purple, Colors.red, Colors.green, Colors.pink]; // Values when toggling polyline width int widthsIndex = 0; List widths = [10, 20, 5]; int jointTypesIndex = 0; - List jointTypes = [ - JointType.mitered, - JointType.bevel, - JointType.round, - ]; + List jointTypes = [JointType.mitered, JointType.bevel, JointType.round]; // Values when toggling polyline end cap type int endCapsIndex = 0; @@ -109,11 +99,11 @@ class PlacePolylineBodyState extends State { return; } - final String polylineIdVal = 'polyline_id_$_polylineIdCounter'; + final polylineIdVal = 'polyline_id_$_polylineIdCounter'; _polylineIdCounter++; - final PolylineId polylineId = PolylineId(polylineIdVal); + final polylineId = PolylineId(polylineIdVal); - final Polyline polyline = Polyline( + final polyline = Polyline( polylineId: polylineId, consumeTapEvents: true, color: Colors.orange, @@ -132,36 +122,28 @@ class PlacePolylineBodyState extends State { void _toggleGeodesic(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - geodesicParam: !polyline.geodesic, - ); + polylines[polylineId] = polyline.copyWith(geodesicParam: !polyline.geodesic); }); } void _toggleVisible(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - visibleParam: !polyline.visible, - ); + polylines[polylineId] = polyline.copyWith(visibleParam: !polyline.visible); }); } void _changeColor(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - colorParam: colors[++colorsIndex % colors.length], - ); + polylines[polylineId] = polyline.copyWith(colorParam: colors[++colorsIndex % colors.length]); }); } void _changeWidth(PolylineId polylineId) { final Polyline polyline = polylines[polylineId]!; setState(() { - polylines[polylineId] = polyline.copyWith( - widthParam: widths[++widthsIndex % widths.length], - ); + polylines[polylineId] = polyline.copyWith(widthParam: widths[++widthsIndex % widths.length]); }); } @@ -236,15 +218,11 @@ class PlacePolylineBodyState extends State { children: [ TextButton(onPressed: _add, child: const Text('add')), TextButton( - onPressed: (selectedId == null) - ? null - : () => _remove(selectedId), + onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _toggleVisible(selectedId), + onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), TextButton( @@ -258,15 +236,11 @@ class PlacePolylineBodyState extends State { Column( children: [ TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeWidth(selectedId), + onPressed: (selectedId == null) ? null : () => _changeWidth(selectedId), child: const Text('change width'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changeColor(selectedId), + onPressed: (selectedId == null) ? null : () => _changeColor(selectedId), child: const Text('change color'), ), TextButton( @@ -288,9 +262,7 @@ class PlacePolylineBodyState extends State { child: const Text('change joint type [Android only]'), ), TextButton( - onPressed: (selectedId == null) - ? null - : () => _changePattern(selectedId), + onPressed: (selectedId == null) ? null : () => _changePattern(selectedId), child: const Text('change pattern'), ), ], @@ -306,7 +278,7 @@ class PlacePolylineBodyState extends State { } List _createPoints() { - final List points = []; + final points = []; final double offset = _polylineIdCounter.ceilToDouble(); points.add(_createLatLng(51.4816 + offset, -3.1791)); points.add(_createLatLng(53.0430 + offset, -2.9925)); diff --git a/packages/google_maps_flutter/example/lib/readme_sample.dart b/packages/google_maps_flutter/example/lib/readme_sample.dart index dd7791914..7dc360388 100644 --- a/packages/google_maps_flutter/example/lib/readme_sample.dart +++ b/packages/google_maps_flutter/example/lib/readme_sample.dart @@ -16,10 +16,7 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - title: 'Flutter Google Maps Demo', - home: MapSample(), - ); + return const MaterialApp(title: 'Flutter Google Maps Demo', home: MapSample()); } } @@ -32,8 +29,7 @@ class MapSample extends StatefulWidget { } class MapSampleState extends State { - final Completer _controller = - Completer(); + final Completer _controller = Completer(); static const CameraPosition _kGooglePlex = CameraPosition( target: LatLng(37.42796133580664, -122.085749655962), diff --git a/packages/google_maps_flutter/example/lib/scrolling_map.dart b/packages/google_maps_flutter/example/lib/scrolling_map.dart index 15835db63..86b66a871 100644 --- a/packages/google_maps_flutter/example/lib/scrolling_map.dart +++ b/packages/google_maps_flutter/example/lib/scrolling_map.dart @@ -14,8 +14,7 @@ import 'page.dart'; const LatLng _center = LatLng(32.080664, 34.9563837); class ScrollingMapPage extends GoogleMapExampleAppPage { - const ScrollingMapPage({super.key}) - : super(const Icon(Icons.map), 'Scrolling map'); + const ScrollingMapPage({super.key}) : super(const Icon(Icons.map), 'Scrolling map'); @override Widget build(BuildContext context) { @@ -44,15 +43,10 @@ class ScrollingMapBody extends StatelessWidget { width: 300.0, height: 300.0, child: GoogleMap( - initialCameraPosition: const CameraPosition( - target: _center, - zoom: 11.0, - ), + initialCameraPosition: const CameraPosition(target: _center, zoom: 11.0), gestureRecognizers: // >{ - Factory( - () => EagerGestureRecognizer(), - ), + Factory(() => EagerGestureRecognizer()), }, ), ), @@ -69,19 +63,14 @@ class ScrollingMapBody extends StatelessWidget { const Text("This map doesn't consume the vertical drags."), const Padding( padding: EdgeInsets.only(bottom: 12.0), - child: Text( - 'It still gets other gestures (e.g scale or tap).', - ), + child: Text('It still gets other gestures (e.g scale or tap).'), ), Center( child: SizedBox( width: 300.0, height: 300.0, child: GoogleMap( - initialCameraPosition: const CameraPosition( - target: _center, - zoom: 11.0, - ), + initialCameraPosition: const CameraPosition(target: _center, zoom: 11.0), markers: { Marker( markerId: const MarkerId('test_marker_id'), @@ -92,12 +81,9 @@ class ScrollingMapBody extends StatelessWidget { ), ), }, - gestureRecognizers: - >{ - Factory( - () => ScaleGestureRecognizer(), - ), - }, + gestureRecognizers: >{ + Factory(() => ScaleGestureRecognizer()), + }, ), ), ), diff --git a/packages/google_maps_flutter/example/lib/snapshot.dart b/packages/google_maps_flutter/example/lib/snapshot.dart index deb33a9ec..08f52c3f8 100644 --- a/packages/google_maps_flutter/example/lib/snapshot.dart +++ b/packages/google_maps_flutter/example/lib/snapshot.dart @@ -44,16 +44,12 @@ class _SnapshotBodyState extends State<_SnapshotBody> { children: [ SizedBox( height: 180, - child: GoogleMap( - onMapCreated: onMapCreated, - initialCameraPosition: _kInitialPosition, - ), + child: GoogleMap(onMapCreated: onMapCreated, initialCameraPosition: _kInitialPosition), ), TextButton( child: const Text('Take a snapshot'), onPressed: () async { - final Uint8List? imageBytes = await _mapController - ?.takeSnapshot(); + final Uint8List? imageBytes = await _mapController?.takeSnapshot(); setState(() { _imageBytes = imageBytes; }); diff --git a/packages/google_maps_flutter/example/lib/tile_overlay.dart b/packages/google_maps_flutter/example/lib/tile_overlay.dart index c7830397b..70a59b0cc 100644 --- a/packages/google_maps_flutter/example/lib/tile_overlay.dart +++ b/packages/google_maps_flutter/example/lib/tile_overlay.dart @@ -13,8 +13,7 @@ import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'page.dart'; class TileOverlayPage extends GoogleMapExampleAppPage { - const TileOverlayPage({super.key}) - : super(const Icon(Icons.map), 'Tile overlay'); + const TileOverlayPage({super.key}) : super(const Icon(Icons.map), 'Tile overlay'); @override Widget build(BuildContext context) { @@ -52,7 +51,7 @@ class TileOverlayBodyState extends State { } void _addTileOverlay() { - final TileOverlay tileOverlay = TileOverlay( + final tileOverlay = TileOverlay( tileOverlayId: const TileOverlayId('tile_overlay_1'), tileProvider: _DebugTileProvider(), ); @@ -69,9 +68,7 @@ class TileOverlayBodyState extends State { @override Widget build(BuildContext context) { - final Set overlays = { - if (_tileOverlay != null) _tileOverlay!, - }; + final overlays = {if (_tileOverlay != null) _tileOverlay!}; return Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.spaceEvenly, @@ -91,18 +88,9 @@ class TileOverlayBodyState extends State { ), ), ), - TextButton( - onPressed: _addTileOverlay, - child: const Text('Add tile overlay'), - ), - TextButton( - onPressed: _removeTileOverlay, - child: const Text('Remove tile overlay'), - ), - TextButton( - onPressed: _clearTileCache, - child: const Text('Clear tile cache'), - ), + TextButton(onPressed: _addTileOverlay, child: const Text('Add tile overlay')), + TextButton(onPressed: _removeTileOverlay, child: const Text('Remove tile overlay')), + TextButton(onPressed: _clearTileCache, child: const Text('Clear tile cache')), ], ); } @@ -123,25 +111,17 @@ class _DebugTileProvider implements TileProvider { @override Future getTile(int x, int y, int? zoom) async { - final ui.PictureRecorder recorder = ui.PictureRecorder(); - final Canvas canvas = Canvas(recorder); - final TextSpan textSpan = TextSpan(text: '$x,$y', style: textStyle); - final TextPainter textPainter = TextPainter( - text: textSpan, - textDirection: TextDirection.ltr, - ); + final recorder = ui.PictureRecorder(); + final canvas = Canvas(recorder); + final textSpan = TextSpan(text: '$x,$y', style: textStyle); + final textPainter = TextPainter(text: textSpan, textDirection: TextDirection.ltr); textPainter.layout(maxWidth: width.toDouble()); textPainter.paint(canvas, Offset.zero); - canvas.drawRect( - Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), - boxPaint, - ); + canvas.drawRect(Rect.fromLTRB(0, 0, width.toDouble(), width.toDouble()), boxPaint); final ui.Picture picture = recorder.endRecording(); final Uint8List byteData = await picture .toImage(width, height) - .then( - (ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png), - ) + .then((ui.Image image) => image.toByteData(format: ui.ImageByteFormat.png)) .then((ByteData? byteData) => byteData!.buffer.asUint8List()); return Tile(width, height, byteData); } diff --git a/packages/google_maps_flutter/lib/src/circles.dart b/packages/google_maps_flutter/lib/src/circles.dart index 9f0a22a4a..97c47319d 100644 --- a/packages/google_maps_flutter/lib/src/circles.dart +++ b/packages/google_maps_flutter/lib/src/circles.dart @@ -37,11 +37,9 @@ class CirclesController extends GeometryController { return; } - final util.GCircleOptions populationOptions = _circleOptionsFromCircle( - circle, - ); - final util.GCircle gCircle = util.GCircle(_bridge, populationOptions); - final CircleController controller = CircleController( + final util.GCircleOptions populationOptions = _circleOptionsFromCircle(circle); + final gCircle = util.GCircle(_bridge, populationOptions); + final controller = CircleController( circle: gCircle, consumeTapEvents: circle.consumeTapEvents, onTap: () { @@ -59,8 +57,7 @@ class CirclesController extends GeometryController { } void _changeCircle(Circle circle) { - final CircleController? circleController = - _circleIdToController[circle.circleId]; + final CircleController? circleController = _circleIdToController[circle.circleId]; circleController?.update(_circleOptionsFromCircle(circle)); } diff --git a/packages/google_maps_flutter/lib/src/convert.dart b/packages/google_maps_flutter/lib/src/convert.dart index 1e6e13852..a90cc004a 100644 --- a/packages/google_maps_flutter/lib/src/convert.dart +++ b/packages/google_maps_flutter/lib/src/convert.dart @@ -29,43 +29,27 @@ Map _mapOptionsFromConfiguration(MapConfiguration config) { final EdgeInsets? padding = config.padding; return { if (config.compassEnabled != null) 'compassEnabled': config.compassEnabled, - if (config.mapToolbarEnabled != null) - 'mapToolbarEnabled': config.mapToolbarEnabled, + if (config.mapToolbarEnabled != null) 'mapToolbarEnabled': config.mapToolbarEnabled, if (config.cameraTargetBounds != null) 'cameraTargetBounds': config.cameraTargetBounds!.toJson(), if (config.mapType != null) 'mapType': config.mapType!.index, if (config.minMaxZoomPreference != null) 'minMaxZoomPreference': config.minMaxZoomPreference!.toJson(), - if (config.rotateGesturesEnabled != null) - 'rotateGesturesEnabled': config.rotateGesturesEnabled, - if (config.scrollGesturesEnabled != null) - 'scrollGesturesEnabled': config.scrollGesturesEnabled, - if (config.tiltGesturesEnabled != null) - 'tiltGesturesEnabled': config.tiltGesturesEnabled, - if (config.zoomControlsEnabled != null) - 'zoomControlsEnabled': config.zoomControlsEnabled, - if (config.zoomGesturesEnabled != null) - 'zoomGesturesEnabled': config.zoomGesturesEnabled, - if (config.liteModeEnabled != null) - 'liteModeEnabled': config.liteModeEnabled, - if (config.trackCameraPosition != null) - 'trackCameraPosition': config.trackCameraPosition, - if (config.myLocationEnabled != null) - 'myLocationEnabled': config.myLocationEnabled, + if (config.rotateGesturesEnabled != null) 'rotateGesturesEnabled': config.rotateGesturesEnabled, + if (config.scrollGesturesEnabled != null) 'scrollGesturesEnabled': config.scrollGesturesEnabled, + if (config.tiltGesturesEnabled != null) 'tiltGesturesEnabled': config.tiltGesturesEnabled, + if (config.zoomControlsEnabled != null) 'zoomControlsEnabled': config.zoomControlsEnabled, + if (config.zoomGesturesEnabled != null) 'zoomGesturesEnabled': config.zoomGesturesEnabled, + if (config.liteModeEnabled != null) 'liteModeEnabled': config.liteModeEnabled, + if (config.trackCameraPosition != null) 'trackCameraPosition': config.trackCameraPosition, + if (config.myLocationEnabled != null) 'myLocationEnabled': config.myLocationEnabled, if (config.myLocationButtonEnabled != null) 'myLocationButtonEnabled': config.myLocationButtonEnabled, if (padding != null) - 'padding': [ - padding.top, - padding.left, - padding.bottom, - padding.right, - ], - if (config.indoorViewEnabled != null) - 'indoorEnabled': config.indoorViewEnabled, + 'padding': [padding.top, padding.left, padding.bottom, padding.right], + if (config.indoorViewEnabled != null) 'indoorEnabled': config.indoorViewEnabled, if (config.trafficEnabled != null) 'trafficEnabled': config.trafficEnabled, - if (config.buildingsEnabled != null) - 'buildingsEnabled': config.buildingsEnabled, + if (config.buildingsEnabled != null) 'buildingsEnabled': config.buildingsEnabled, if (config.mapId != null) 'mapId': config.mapId, if (config.style != null) 'style': config.style, if (config.colorScheme != null) 'colorScheme': config.colorScheme!.index, @@ -77,11 +61,11 @@ String? _getCameraBounds(dynamic option) { return null; } - final List bound = option[0]! as List; + final bound = option[0]! as List; final LatLng? southwest = LatLng.fromJson(bound[0]); final LatLng? northeast = LatLng.fromJson(bound[1]); - final String restrictedBound = + final restrictedBound = '{south:${southwest?.latitude}, west:${southwest?.longitude}, north:${northeast?.latitude}, east:${northeast?.longitude}}'; return restrictedBound; @@ -107,8 +91,7 @@ String? _getCameraBounds(dynamic option) { String _rawOptionsToString(Map rawOptions) { // These don't have any rawOptions entry, but they seem to be off in the // native maps. - String options = - 'mapTypeControl: false, fullscreenControl: false, streetViewControl: false'; + var options = 'mapTypeControl: false, fullscreenControl: false, streetViewControl: false'; if (_mapTypeToMapTypeId.containsKey(rawOptions['mapType'])) { options += ", mapTypeId: '${_mapTypeToMapTypeId[rawOptions['mapType']]}'"; @@ -132,15 +115,13 @@ String _rawOptionsToString(Map rawOptions) { options += ', zoomControl: ${rawOptions['zoomControlsEnabled']}'; } - if (rawOptions['style'] != null && - (rawOptions['style'] as String).isNotEmpty) { + if (rawOptions['style'] != null && (rawOptions['style'] as String).isNotEmpty) { options += ', styles: ${rawOptions['style']}'; } else { options += ', styles: null'; } - if (rawOptions['scrollGesturesEnabled'] == false || - rawOptions['zoomGesturesEnabled'] == false) { + if (rawOptions['scrollGesturesEnabled'] == false || rawOptions['zoomGesturesEnabled'] == false) { options += ", gestureHandling: 'none'"; } else { options += ", gestureHandling: 'auto'"; @@ -189,11 +170,7 @@ bool _isTrafficLayerEnabled(Map rawOptions) { } // The keys we'd expect to see in a serialized MapTypeStyle JSON object. -final Set _mapStyleKeys = { - 'elementType', - 'featureType', - 'stylers', -}; +final Set _mapStyleKeys = {'elementType', 'featureType', 'stylers'}; // Checks if the passed in Map contains some of the _mapStyleKeys. bool _isJsonMapStyle(Map value) { @@ -219,8 +196,7 @@ String _mapStyles(String? mapStyleJson) { .decode( mapStyleJson, reviver: (Object? key, Object? value) { - if (value is Map && - _isJsonMapStyle(value as Map)) { + if (value is Map && _isJsonMapStyle(value as Map)) { return MapTypeStyle() ..elementType = value['elementType'] as String? ..featureType = value['featureType'] as String? @@ -279,15 +255,11 @@ LatLng _convertToLatLng(String value) { ScreenCoordinate _convertToPoint(String value) { try { final dynamic latlng = json.decode(value); - int x = 0, y = 0; + var x = 0, y = 0; if (latlng is Map) { - x = latlng['x'] is int - ? latlng['x'] as int - : (latlng['x'] as double).toInt(); - y = latlng['y'] is int - ? latlng['y'] as int - : (latlng['y'] as double).toInt(); + x = latlng['x'] is int ? latlng['x'] as int : (latlng['x'] as double).toInt(); + y = latlng['y'] is int ? latlng['y'] as int : (latlng['y'] as double).toInt(); return ScreenCoordinate(x: x, y: y); } @@ -310,7 +282,7 @@ util.GInfoWindowOptions? _infoWindowOptionsFromMarker(Marker marker) { // Add an outer wrapper to the contents of the infowindow. The content is // JSON-encoded by its consumers (GInfoWindowOptions.toString and // GInfoWindow._setContent), so it must be raw, unquoted HTML here. - final StringBuffer buffer = StringBuffer(); + final buffer = StringBuffer(); buffer.write('
'); if (markerTitle.isNotEmpty) { buffer.write('

'); @@ -333,44 +305,30 @@ util.GInfoWindowOptions? _infoWindowOptionsFromMarker(Marker marker) { // Computes the options for a new [GMarker] from an incoming set of options // [marker], and the existing marker registered with the map: [currentMarker]. // Preserves the position from the [currentMarker], if set. -util.GMarkerOptions _markerOptionsFromMarker( - Marker marker, - util.GMarker? currentMarker, -) { - final List iconConfig = marker.icon.toJson() as List; +util.GMarkerOptions _markerOptionsFromMarker(Marker marker, util.GMarker? currentMarker) { + final iconConfig = marker.icon.toJson() as List; util.GIcon? icon; if (iconConfig.isNotEmpty) { if (iconConfig[0] == 'asset') { assert(iconConfig.length >= 2); - final Map assetConfig = - iconConfig[1]! as Map; + final assetConfig = iconConfig[1]! as Map; icon = util.GIcon()..url = '../${assetConfig['assetName']}'; if (assetConfig['width'] != null || assetConfig['height'] != null) { icon.size = util.GSize( - assetConfig['width'] != null - ? double.parse(assetConfig['width']!.toString()) - : null, - assetConfig['height'] != null - ? double.parse(assetConfig['height']!.toString()) - : null, + assetConfig['width'] != null ? double.parse(assetConfig['width']!.toString()) : null, + assetConfig['height'] != null ? double.parse(assetConfig['height']!.toString()) : null, ); } } else if (iconConfig[0] == 'bytes') { assert(iconConfig.length >= 2); - final Map assetConfig = - iconConfig[1]! as Map; + final assetConfig = iconConfig[1]! as Map; icon = util.GIcon() - ..url = - 'data:image/png;base64,${base64Encode(assetConfig['byteData']! as List)}'; + ..url = 'data:image/png;base64,${base64Encode(assetConfig['byteData']! as List)}'; if (assetConfig['width'] != null || assetConfig['height'] != null) { icon.size = util.GSize( - assetConfig['width'] != null - ? double.parse(assetConfig['width']!.toString()) - : null, - assetConfig['height'] != null - ? double.parse(assetConfig['height']!.toString()) - : null, + assetConfig['width'] != null ? double.parse(assetConfig['width']!.toString()) : null, + assetConfig['height'] != null ? double.parse(assetConfig['height']!.toString()) : null, ); } } @@ -421,10 +379,10 @@ util.GPolylineOptions _polylineOptionsFromPolyline(Polyline polyline) { util.GPolygonOptions _polygonOptionsFromPolygon(Polygon polygon) { final List path = polygon.points; final bool polygonDirection = _isPolygonClockwise(path); - final List> paths = >[path]; - int holeIndex = 0; + final paths = >[path]; + var holeIndex = 0; - for (int i = 0; i < polygon.holes.length; i++) { + for (var i = 0; i < polygon.holes.length; i++) { List holePath = polygon.holes[i]; if (_isPolygonClockwise(holePath) == polygonDirection) { holePath = holePath.reversed.toList(); @@ -462,8 +420,8 @@ util.GPolygonOptions _polygonOptionsFromPolygon(Polygon polygon) { /// the `path` is a transformed version of [Polygon.points] or each of the /// [Polygon.holes], guaranteeing that `lat` and `lng` can be accessed with `!`. bool _isPolygonClockwise(List path) { - double direction = 0.0; - for (int i = 0; i < path.length; i++) { + var direction = 0.0; + for (var i = 0; i < path.length; i++) { direction = direction + ((path[(i + 1) % path.length].latitude - path[i].latitude) * @@ -485,9 +443,7 @@ util.GCircleOptions _circleOptionsFromCircle(Circle circle) { ..zIndex = circle.zIndex; } -util.GGroundOverlayOptions? _groundOverlayOptionsFromGroundOverlay( - GroundOverlay groundOverlay, -) { +util.GGroundOverlayOptions? _groundOverlayOptionsFromGroundOverlay(GroundOverlay groundOverlay) { // The JS Maps GroundOverlay only supports bounds-based positioning. Skip // position-only overlays — the platform interface allows the field but the // JS API has no equivalent. @@ -521,19 +477,17 @@ util.GGroundOverlayOptions? _groundOverlayOptionsFromGroundOverlay( } String? _imageUrlFromMapBitmap(MapBitmap bitmap) { - final List iconConfig = bitmap.toJson() as List; + final iconConfig = bitmap.toJson() as List; if (iconConfig.isEmpty) { return null; } if (iconConfig[0] == 'asset' && iconConfig.length >= 2) { - final Map assetConfig = - iconConfig[1]! as Map; + final assetConfig = iconConfig[1]! as Map; return '../${assetConfig['assetName']}'; } if (iconConfig[0] == 'bytes' && iconConfig.length >= 2) { - final Map assetConfig = - iconConfig[1]! as Map; - final List bytes = assetConfig['byteData']! as List; + final assetConfig = iconConfig[1]! as Map; + final bytes = assetConfig['byteData']! as List; return 'data:image/png;base64,${base64Encode(bytes)}'; } return null; diff --git a/packages/google_maps_flutter/lib/src/google_maps_controller.dart b/packages/google_maps_flutter/lib/src/google_maps_controller.dart index 957b1a61d..0fabc520a 100644 --- a/packages/google_maps_flutter/lib/src/google_maps_controller.dart +++ b/packages/google_maps_flutter/lib/src/google_maps_controller.dart @@ -31,18 +31,9 @@ class GoogleMapsController { _clusterManagers = clusterManagers, _groundOverlays = groundOverlays, _rawMapOptions = mapOptions { - _circlesController = CirclesController( - stream: _streamController, - bridge: _bridge, - ); - _polygonsController = PolygonsController( - stream: _streamController, - bridge: _bridge, - ); - _polylinesController = PolylinesController( - stream: _streamController, - bridge: _bridge, - ); + _circlesController = CirclesController(stream: _streamController, bridge: _bridge); + _polygonsController = PolygonsController(stream: _streamController, bridge: _bridge); + _polylinesController = PolylinesController(stream: _streamController, bridge: _bridge); _clusterManagersController = ClusterManagersController( stream: _streamController, bridge: _bridge, @@ -85,23 +76,17 @@ class GoogleMapsController { /// Returns min-max zoom levels. Test only. @visibleForTesting Future getMinMaxZoomLevels() async { - final String value = - await _bridge.runJavaScriptReturningResult( - 'JSON.stringify([map.minZoom, map.maxZoom])', - ) + final value = + await _bridge.runJavaScriptReturningResult('JSON.stringify([map.minZoom, map.maxZoom])') as String; final dynamic bound = json.decode(value); double min = 0, max = 0; if (bound is List) { if (bound[0] is num) { - min = (bound[0] is double) - ? (bound[0] as double) - : (bound[0] as int).toDouble(); + min = (bound[0] is double) ? (bound[0] as double) : (bound[0] as int).toDouble(); } if (bound[1] is num) { - max = (bound[1] is double) - ? (bound[1] as double) - : (bound[1] as int).toDouble(); + max = (bound[1] is double) ? (bound[1] as double) : (bound[1] as int).toDouble(); } return MinMaxZoomPreference(min, max); } @@ -111,26 +96,21 @@ class GoogleMapsController { /// Returns if zoomGestures property is enabled. Test only. @visibleForTesting Future isZoomGesturesEnabled() async { - final String value = - await _bridge.runJavaScriptReturningResult('map.gestureHandling') - as String; + final value = await _bridge.runJavaScriptReturningResult('map.gestureHandling') as String; return value != 'none'; } /// Returns if zoomControls property is enabled. Test only. @visibleForTesting Future isZoomControlsEnabled() async { - final String value = - await _bridge.runJavaScriptReturningResult('map.zoomControl') as String; + final value = await _bridge.runJavaScriptReturningResult('map.zoomControl') as String; return value != 'false'; } /// Returns if scrollGestures property is enabled. Test only. @visibleForTesting Future isScrollGesturesEnabled() async { - final String value = - await _bridge.runJavaScriptReturningResult('map.gestureHandling') - as String; + final value = await _bridge.runJavaScriptReturningResult('map.gestureHandling') as String; return value != 'none'; } @@ -230,10 +210,7 @@ class GoogleMapsController { } _streamController.add( - CameraMoveEvent( - _mapId, - CameraPosition(target: center, zoom: zoom.toDouble()), - ), + CameraMoveEvent(_mapId, CameraPosition(target: center, zoom: zoom.toDouble())), ); } } @@ -260,10 +237,7 @@ class GoogleMapsController { final dynamic event = json.decode(message); if (event is Map) { assert(event['latLng'] != null); - final LatLng position = LatLng( - event['latLng']['lat'] as double, - event['latLng']['lng'] as double, - ); + final position = LatLng(event['latLng']['lat'] as double, event['latLng']['lng'] as double); _streamController.add(MapTapEvent(_mapId, position)); } } catch (e) { @@ -276,10 +250,7 @@ class GoogleMapsController { final dynamic event = json.decode(message); if (event is Map) { assert(event['latLng'] != null); - final LatLng position = LatLng( - event['latLng']['lat'] as double, - event['latLng']['lng'] as double, - ); + final position = LatLng(event['latLng']['lat'] as double, event['latLng']['lng'] as double); _streamController.add(MapLongPressEvent(_mapId, position)); } } catch (e) { @@ -291,20 +262,16 @@ class GoogleMapsController { try { final dynamic result = json.decode(message); - final String id = result['id'] as String; + final id = result['id'] as String; final ClusterManagerId? clusterManagerId = _clusterManagersController?.idToClusterManagerId[id]; if (clusterManagerId == null) { return; } - final Map markerClustererCluster = - result['cluster'] as Map; + final markerClustererCluster = result['cluster'] as Map; - _clusterManagersController?.clusterClicked( - clusterManagerId, - markerClustererCluster, - ); + _clusterManagersController?.clusterClicked(clusterManagerId, markerClustererCluster); } catch (e) { debugPrint('JavaScript Error: $e'); } @@ -315,8 +282,7 @@ class GoogleMapsController { final dynamic id = json.decode(message); if (_markersController != null && id is int) { final MarkerId? markerId = _markersController!._idToMarkerId[id]; - final MarkerController? marker = - _markersController!._markerIdToController[markerId]; + final MarkerController? marker = _markersController!._markerIdToController[markerId]; if (marker?.tapEvent != null) { marker?.tapEvent!(); } @@ -332,12 +298,10 @@ class GoogleMapsController { if (result is Map) { assert(result['id'] != null && result['event'] != null); if (_markersController != null && result['id'] is int) { - final MarkerId? markerId = - _markersController!._idToMarkerId[result['id']]; - final MarkerController? marker = - _markersController!._markerIdToController[markerId]; + final MarkerId? markerId = _markersController!._idToMarkerId[result['id']]; + final MarkerController? marker = _markersController!._markerIdToController[markerId]; - final LatLng position = LatLng( + final position = LatLng( result['event']['latLng']['lat'] as double, result['event']['latLng']['lng'] as double, ); @@ -358,12 +322,10 @@ class GoogleMapsController { if (result is Map) { assert(result['id'] != null && result['event'] != null); if (_markersController != null && result['id'] is int) { - final MarkerId? markerId = - _markersController!._idToMarkerId[result['id']]; - final MarkerController? marker = - _markersController!._markerIdToController[markerId]; + final MarkerId? markerId = _markersController!._idToMarkerId[result['id']]; + final MarkerController? marker = _markersController!._markerIdToController[markerId]; - final LatLng position = LatLng( + final position = LatLng( result['event']['latLng']['lat'] as double, result['event']['latLng']['lng'] as double, ); @@ -384,12 +346,10 @@ class GoogleMapsController { if (result is Map) { assert(result['id'] != null && result['event'] != null); if (_markersController != null && result['id'] is int) { - final MarkerId? markerId = - _markersController!._idToMarkerId[result['id']]; - final MarkerController? marker = - _markersController!._markerIdToController[markerId]; + final MarkerId? markerId = _markersController!._idToMarkerId[result['id']]; + final MarkerController? marker = _markersController!._markerIdToController[markerId]; - final LatLng position = LatLng( + final position = LatLng( result['event']['latLng']['lat'] as double, result['event']['latLng']['lng'] as double, ); @@ -408,8 +368,7 @@ class GoogleMapsController { try { final dynamic id = json.decode(message); if (_polylinesController != null && id is int) { - final PolylineId? polylineId = - _polylinesController!._idToPolylineId[id]; + final PolylineId? polylineId = _polylinesController!._idToPolylineId[id]; final PolylineController? polyline = _polylinesController!._polylineIdToController[polylineId]; if (polyline?.tapEvent != null) { @@ -426,8 +385,7 @@ class GoogleMapsController { final dynamic id = json.decode(message); if (_polygonsController != null && id is int) { final PolygonId? polygonId = _polygonsController!._idToPolygonId[id]; - final PolygonController? polygon = - _polygonsController!._polygonIdToController[polygonId]; + final PolygonController? polygon = _polygonsController!._polygonIdToController[polygonId]; if (polygon?.tapEvent != null) { polygon?.tapEvent!(); } @@ -442,8 +400,7 @@ class GoogleMapsController { final dynamic id = json.decode(message); if (_circlesController != null && id is int) { final CircleId? circleId = _circlesController!._idToCircleId[id]; - final CircleController? circle = - _circlesController!._circleIdToController[circleId]; + final CircleController? circle = _circlesController!._circleIdToController[circleId]; if (circle?.tapEvent != null) { circle?.tapEvent!(); } @@ -460,8 +417,7 @@ class GoogleMapsController { final GroundOverlayId? groundOverlayId = _groundOverlaysController!._idToGroundOverlayId[id]; final GroundOverlayController? groundOverlay = - _groundOverlaysController! - ._groundOverlayIdToController[groundOverlayId]; + _groundOverlaysController!._groundOverlayIdToController[groundOverlayId]; if (groundOverlay?.tapEvent != null) { groundOverlay?.tapEvent!(); } @@ -506,10 +462,7 @@ class GoogleMapsController { Future _attachGeometryControllers() async { // Now we can add the initial geometry. // And bind the (ready) map instance to the other geometry controllers. - assert( - _circlesController != null, - 'Cannot attach a map to a null CirclesController instance.', - ); + assert(_circlesController != null, 'Cannot attach a map to a null CirclesController instance.'); assert( _polygonsController != null, 'Cannot attach a map to a null PolygonsController instance.', @@ -518,10 +471,7 @@ class GoogleMapsController { _polylinesController != null, 'Cannot attach a map to a null PolylinesController instance.', ); - assert( - _markersController != null, - 'Cannot attach a map to a null MarkersController instance.', - ); + assert(_markersController != null, 'Cannot attach a map to a null MarkersController instance.'); assert( _clusterManagersController != null, 'Cannot attach a map to a null ClusterManagersController instance.', @@ -599,7 +549,7 @@ class GoogleMapsController { // Attaches/detaches a Traffic Layer on the `map` if `attach` is true/false. Future _setTrafficLayer(bool attach) async { - final String command = + final command = ''' var trafficLayer; if ($attach == true && trafficLayer == null) { @@ -647,16 +597,12 @@ class GoogleMapsController { /// Returns the [LatLngBounds] of the current viewport. Future getVisibleRegion() async { - return _convertToBounds( - await _callMethod('getBounds', []) as String, - ); + return _convertToBounds(await _callMethod('getBounds', []) as String); } /// Returns the [LatLng] at the center of the map. Future getCenter() async { - return _convertToLatLng( - await _callMethod('getCenter', []) as String, - ); + return _convertToLatLng(await _callMethod('getCenter', []) as String); } /// Returns the [ScreenCoordinate] for a given viewport [LatLng]. @@ -678,15 +624,13 @@ class GoogleMapsController { // Translates a [CameraUpdate] into operations on a [Javascript]. Future _applyCameraUpdate(CameraUpdate update) async { - final List json = update.toJson() as List; + final json = update.toJson() as List; switch (json[0]) { case 'newCameraPosition': await _setMoveCamera( '{heading: ${json[1]['bearing']}, zoom: ${json[1]['zoom']}, tilt: ${json[1]['tilt']}}', ); - await _setPanTo( - '{lat:${json[1]['target'][0]}, lng: ${json[1]['target'][1]}}', - ); + await _setPanTo('{lat:${json[1]['target'][0]}, lng: ${json[1]['target'][1]}}'); case 'newLatLng': await _setPanTo('{lat:${json[1][0]}, lng:${json[1][1]}}'); case 'newLatLngZoom': @@ -701,21 +645,16 @@ class GoogleMapsController { await _setPanBy(json[1] as num, json[2] as num); case 'zoomBy': String? focusLatLng; - double zoomDelta = 0.0; + var zoomDelta = 0.0; if (json[1] != null) { zoomDelta = (json[1] as num) + 0.0; } // Web only supports integer changes... - final int newZoomDelta = zoomDelta < 0 - ? zoomDelta.floor() - : zoomDelta.ceil(); + final int newZoomDelta = zoomDelta < 0 ? zoomDelta.floor() : zoomDelta.ceil(); if (json.length == 3) { // With focus try { - focusLatLng = await _pixelToLatLng( - json[2][0] as double, - json[2][1] as double, - ); + focusLatLng = await _pixelToLatLng(json[2][0] as double, json[2][1] as double); } catch (e) { debugPrint('Error computing focus LatLng. JS Error: $e'); } @@ -736,7 +675,7 @@ class GoogleMapsController { } Future _pixelToLatLng(double x, double y) async { - final String command = + final command = ''' function getPixelToLatLng() { var projection = map.getProjection(); @@ -755,7 +694,7 @@ class GoogleMapsController { } Future _latLngToPoint(LatLng latLng) async { - final String command = + final command = ''' function getLatLngToPixel() { var ne = map.getBounds().getNorthEast(); @@ -784,10 +723,7 @@ class GoogleMapsController { /// Applies [CircleUpdates] to the currently managed circles. void updateCircles(CircleUpdates updates) { - assert( - _circlesController != null, - 'Cannot update circles after dispose().', - ); + assert(_circlesController != null, 'Cannot update circles after dispose().'); _circlesController?.addCircles(updates.circlesToAdd); _circlesController?.changeCircles(updates.circlesToChange); _circlesController?.removeCircles(updates.circleIdsToRemove); @@ -795,10 +731,7 @@ class GoogleMapsController { /// Applies [PolygonUpdates] to the currently managed polygons. void updatePolygons(PolygonUpdates updates) { - assert( - _polygonsController != null, - 'Cannot update polygons after dispose().', - ); + assert(_polygonsController != null, 'Cannot update polygons after dispose().'); _polygonsController?.addPolygons(updates.polygonsToAdd); _polygonsController?.changePolygons(updates.polygonsToChange); _polygonsController?.removePolygons(updates.polygonIdsToRemove); @@ -806,10 +739,7 @@ class GoogleMapsController { /// Applies [PolylineUpdates] to the currently managed lines. void updatePolylines(PolylineUpdates updates) { - assert( - _polylinesController != null, - 'Cannot update polylines after dispose().', - ); + assert(_polylinesController != null, 'Cannot update polylines after dispose().'); _polylinesController?.addPolylines(updates.polylinesToAdd); _polylinesController?.changePolylines(updates.polylinesToChange); _polylinesController?.removePolylines(updates.polylineIdsToRemove); @@ -817,10 +747,7 @@ class GoogleMapsController { /// Applies [MarkerUpdates] to the currently managed markers. void updateMarkers(MarkerUpdates updates) { - assert( - _markersController != null, - 'Cannot update markers after dispose().', - ); + assert(_markersController != null, 'Cannot update markers after dispose().'); _markersController?.addMarkers(updates.markersToAdd); _markersController?.changeMarkers(updates.markersToChange); _markersController?.removeMarkers(updates.markerIdsToRemove); @@ -828,31 +755,17 @@ class GoogleMapsController { /// Applies [ClusterManagerUpdates] to the currently managed cluster managers. void updateClusterManagers(ClusterManagerUpdates updates) { - assert( - _clusterManagersController != null, - 'Cannot update markers after dispose().', - ); - _clusterManagersController?.addClusterManagers( - updates.clusterManagersToAdd, - ); - _clusterManagersController?.removeClusterManagers( - updates.clusterManagerIdsToRemove, - ); + assert(_clusterManagersController != null, 'Cannot update markers after dispose().'); + _clusterManagersController?.addClusterManagers(updates.clusterManagersToAdd); + _clusterManagersController?.removeClusterManagers(updates.clusterManagerIdsToRemove); } /// Applies [GroundOverlayUpdates] to the currently managed ground overlays. void updateGroundOverlays(GroundOverlayUpdates updates) { - assert( - _groundOverlaysController != null, - 'Cannot update ground overlays after dispose().', - ); + assert(_groundOverlaysController != null, 'Cannot update ground overlays after dispose().'); _groundOverlaysController?.addGroundOverlays(updates.groundOverlaysToAdd); - _groundOverlaysController?.changeGroundOverlays( - updates.groundOverlaysToChange, - ); - _groundOverlaysController?.removeGroundOverlays( - updates.groundOverlayIdsToRemove, - ); + _groundOverlaysController?.changeGroundOverlays(updates.groundOverlaysToChange); + _groundOverlaysController?.removeGroundOverlays(updates.groundOverlayIdsToRemove); } /// Shows the [InfoWindow] of the marker identified by its [MarkerId]. diff --git a/packages/google_maps_flutter/lib/src/google_maps_flutter_tizen.dart b/packages/google_maps_flutter/lib/src/google_maps_flutter_tizen.dart index 9172efea7..7b439cf8f 100644 --- a/packages/google_maps_flutter/lib/src/google_maps_flutter_tizen.dart +++ b/packages/google_maps_flutter/lib/src/google_maps_flutter_tizen.dart @@ -35,10 +35,7 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { // Convenience getter for a map controller by its mapId. GoogleMapsController _map(int mapId) { final GoogleMapsController? controller = _mapById[mapId]; - assert( - controller != null, - 'Maps cannot be retrieved before calling buildView!', - ); + assert(controller != null, 'Maps cannot be retrieved before calling buildView!'); return controller!; } @@ -52,46 +49,31 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { /// This attempts to merge the new `optionsUpdate` passed in, with the previous /// options passed to the map (in other updates, or when creating it). @override - Future updateMapOptions( - Map optionsUpdate, { - required int mapId, - }) async { + Future updateMapOptions(Map optionsUpdate, {required int mapId}) async { _map(mapId).updateRawOptions(optionsUpdate); } /// Applies the passed in `markerUpdates` to the `mapId`. @override - Future updateMarkers( - MarkerUpdates markerUpdates, { - required int mapId, - }) async { + Future updateMarkers(MarkerUpdates markerUpdates, {required int mapId}) async { _map(mapId).updateMarkers(markerUpdates); } /// Applies the passed in `polygonUpdates` to the `mapId`. @override - Future updatePolygons( - PolygonUpdates polygonUpdates, { - required int mapId, - }) async { + Future updatePolygons(PolygonUpdates polygonUpdates, {required int mapId}) async { _map(mapId).updatePolygons(polygonUpdates); } /// Applies the passed in `polylineUpdates` to the `mapId`. @override - Future updatePolylines( - PolylineUpdates polylineUpdates, { - required int mapId, - }) async { + Future updatePolylines(PolylineUpdates polylineUpdates, {required int mapId}) async { _map(mapId).updatePolylines(polylineUpdates); } /// Applies the passed in `circleUpdates` to the `mapId`. @override - Future updateCircles( - CircleUpdates circleUpdates, { - required int mapId, - }) async { + Future updateCircles(CircleUpdates circleUpdates, {required int mapId}) async { _map(mapId).updateCircles(circleUpdates); } @@ -104,10 +86,7 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { } @override - Future updateHeatmaps( - HeatmapUpdates heatmapUpdates, { - required int mapId, - }) async { + Future updateHeatmaps(HeatmapUpdates heatmapUpdates, {required int mapId}) async { return; // Noop for now! } @@ -128,28 +107,19 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { } @override - Future clearTileCache( - TileOverlayId tileOverlayId, { - required int mapId, - }) async { + Future clearTileCache(TileOverlayId tileOverlayId, {required int mapId}) async { return; // Noop for now! } /// Applies the given `cameraUpdate` to the current viewport (with animation). @override - Future animateCamera( - CameraUpdate cameraUpdate, { - required int mapId, - }) async { + Future animateCamera(CameraUpdate cameraUpdate, {required int mapId}) async { return moveCamera(cameraUpdate, mapId: mapId); } /// Applies the given `cameraUpdate` to the current viewport. @override - Future moveCamera( - CameraUpdate cameraUpdate, { - required int mapId, - }) async { + Future moveCamera(CameraUpdate cameraUpdate, {required int mapId}) async { return _map(mapId).moveCamera(cameraUpdate); } @@ -161,9 +131,7 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { /// pass full styles. @override Future setMapStyle(String? mapStyle, {required int mapId}) async { - _map( - mapId, - ).updateRawOptions({'styles': _mapStyles(mapStyle)}); + _map(mapId).updateRawOptions({'styles': _mapStyles(mapStyle)}); } /// Returns the bounds of the current viewport. @@ -174,19 +142,13 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { /// Returns the screen coordinate (in pixels) of a given `latLng`. @override - Future getScreenCoordinate( - LatLng latLng, { - required int mapId, - }) { + Future getScreenCoordinate(LatLng latLng, {required int mapId}) { return _map(mapId).getScreenCoordinate(latLng); } /// Returns the [LatLng] of a [ScreenCoordinate] of the viewport. @override - Future getLatLng( - ScreenCoordinate screenCoordinate, { - required int mapId, - }) { + Future getLatLng(ScreenCoordinate screenCoordinate, {required int mapId}) { return _map(mapId).getLatLng(screenCoordinate); } @@ -196,10 +158,7 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { /// * [hideMarkerInfoWindow] to hide the info window. /// * [isMarkerInfoWindowShown] to check if the info window is visible/hidden. @override - Future showMarkerInfoWindow( - MarkerId markerId, { - required int mapId, - }) async { + Future showMarkerInfoWindow(MarkerId markerId, {required int mapId}) async { _map(mapId).showInfoWindow(markerId); } @@ -209,10 +168,7 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { /// * [showMarkerInfoWindow] to show the info window. /// * [isMarkerInfoWindowShown] to check if the info window is shown. @override - Future hideMarkerInfoWindow( - MarkerId markerId, { - required int mapId, - }) async { + Future hideMarkerInfoWindow(MarkerId markerId, {required int mapId}) async { _map(mapId).hideInfoWindow(markerId); } @@ -222,10 +178,7 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { /// * [showMarkerInfoWindow] to show the info window. /// * [hideMarkerInfoWindow] to hide the info window. @override - Future isMarkerInfoWindowShown( - MarkerId markerId, { - required int mapId, - }) async { + Future isMarkerInfoWindowShown(MarkerId markerId, {required int mapId}) async { return _map(mapId).isInfoWindowShown(markerId); } @@ -387,10 +340,9 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { return _mapById[creationId]!.webview!; } - final StreamController> controller = - StreamController>.broadcast(); + final controller = StreamController>.broadcast(); - final GoogleMapsController mapController = GoogleMapsController( + final mapController = GoogleMapsController( initialCameraPosition: initialCameraPosition, mapId: creationId, streamController: controller, @@ -404,13 +356,8 @@ class GoogleMapsPlugin extends GoogleMapsFlutterPlatform { _mapById[creationId] = mapController; - mapController.events.whereType().first.then(( - MapReadyEvent event, - ) { - assert( - creationId == event.mapId, - 'Received MapReadyEvent for the wrong map', - ); + mapController.events.whereType().first.then((MapReadyEvent event) { + assert(creationId == event.mapId, 'Received MapReadyEvent for the wrong map'); // Notify the plugin now that there's a fully initialized controller. onPlatformViewCreated.call(event.mapId); }); diff --git a/packages/google_maps_flutter/lib/src/google_maps_js_bridge.dart b/packages/google_maps_flutter/lib/src/google_maps_js_bridge.dart index 5780ab702..c81d9ee6c 100644 --- a/packages/google_maps_flutter/lib/src/google_maps_js_bridge.dart +++ b/packages/google_maps_flutter/lib/src/google_maps_js_bridge.dart @@ -106,23 +106,22 @@ class GoogleMapsJsBridge { GoogleMapsJsBridge() : controller = WebViewController(); /// The JS-side channel name for each event type, registered in [load]. - static const Map _channelEventTypes = - { - 'BoundChanged': MapsJsEventType.boundsChanged, - 'Idle': MapsJsEventType.idle, - 'Tilesloaded': MapsJsEventType.tilesLoaded, - 'Click': MapsJsEventType.click, - 'LongPress': MapsJsEventType.longPress, - 'MarkerClick': MapsJsEventType.markerClick, - 'ClusterClick': MapsJsEventType.clusterClick, - 'MarkerDragStart': MapsJsEventType.markerDragStart, - 'MarkerDrag': MapsJsEventType.markerDrag, - 'MarkerDragEnd': MapsJsEventType.markerDragEnd, - 'PolylineClick': MapsJsEventType.polylineClick, - 'PolygonClick': MapsJsEventType.polygonClick, - 'CircleClick': MapsJsEventType.circleClick, - 'GroundOverlayClick': MapsJsEventType.groundOverlayClick, - }; + static const Map _channelEventTypes = { + 'BoundChanged': MapsJsEventType.boundsChanged, + 'Idle': MapsJsEventType.idle, + 'Tilesloaded': MapsJsEventType.tilesLoaded, + 'Click': MapsJsEventType.click, + 'LongPress': MapsJsEventType.longPress, + 'MarkerClick': MapsJsEventType.markerClick, + 'ClusterClick': MapsJsEventType.clusterClick, + 'MarkerDragStart': MapsJsEventType.markerDragStart, + 'MarkerDrag': MapsJsEventType.markerDrag, + 'MarkerDragEnd': MapsJsEventType.markerDragEnd, + 'PolylineClick': MapsJsEventType.polylineClick, + 'PolygonClick': MapsJsEventType.polygonClick, + 'CircleClick': MapsJsEventType.circleClick, + 'GroundOverlayClick': MapsJsEventType.groundOverlayClick, + }; /// Event types whose JS side posts an empty payload, so [MapsJsEvent] is /// created with a `null` [MapsJsEvent.message] instead of `''`. @@ -136,8 +135,7 @@ class GoogleMapsJsBridge { /// [WebViewWidget] that hosts this bridge's JS runtime. final WebViewController controller; - final StreamController _events = - StreamController.broadcast(); + final StreamController _events = StreamController.broadcast(); final Completer _pageFinished = Completer(); /// Broadcasts events received from the JS side. @@ -174,17 +172,14 @@ class GoogleMapsJsBridge { ) ..setJavaScriptMode(JavaScriptMode.unrestricted); - for (final MapEntry entry - in _channelEventTypes.entries) { + for (final MapEntry entry in _channelEventTypes.entries) { final MapsJsEventType type = entry.value; controller.addJavaScriptChannel( entry.key, onMessageReceived: (JavaScriptMessage message) { _emit(( type: type, - message: _payloadlessEventTypes.contains(type) - ? null - : message.message, + message: _payloadlessEventTypes.contains(type) ? null : message.message, )); }, ); @@ -198,7 +193,7 @@ class GoogleMapsJsBridge { /// Creates the top-level `map` JS variable using [optionsJs] (a JS object /// literal), plus its built-in map-level listeners. Future createMap(String optionsJs) async { - final String command = + final command = ''' map = new google.maps.Map(document.getElementById('map'), $optionsJs); map.addListener('bounds_changed', (event) => { BoundChanged.postMessage(''); }); @@ -237,10 +232,7 @@ class GoogleMapsJsBridge { /// Creates a JS object via `new `, assigns it to /// the JS-side variable [varName], and returns a [JsRef] handle to it. - Future createObject( - String varName, - String constructorExpression, - ) async { + Future createObject(String varName, String constructorExpression) async { await controller.runJavaScript('var $varName = $constructorExpression;'); return JsRef(varName); } @@ -263,53 +255,34 @@ class GoogleMapsJsBridge { /// Assigns `ref[property] = value` on the JS side. Future setProperty(JsRef ref, String property, Object? value) async { - await controller.runJavaScript( - "JSON.stringify($ref['$property'] = ${_serializeArg(value)})", - ); + await controller.runJavaScript("JSON.stringify($ref['$property'] = ${_serializeArg(value)})"); } /// Calls `ref.method(...args)` on the JS side, discarding the result. Future callMethod(JsRef ref, String method, List args) async { - final String serializedArgs = '[${args.map(_serializeArg).join(', ')}]'; - await controller.runJavaScript( - 'JSON.stringify($ref.$method.apply($ref, $serializedArgs))', - ); + final serializedArgs = '[${args.map(_serializeArg).join(', ')}]'; + await controller.runJavaScript('JSON.stringify($ref.$method.apply($ref, $serializedArgs))'); } /// Calls `ref.method(...args)` on the JS side and returns the JSON-encoded /// result. - Future callMethodReturningJson( - JsRef ref, - String method, - List args, - ) async { - final String serializedArgs = '[${args.map(_serializeArg).join(', ')}]'; + Future callMethodReturningJson(JsRef ref, String method, List args) async { + final serializedArgs = '[${args.map(_serializeArg).join(', ')}]'; return controller.runJavaScriptReturningResult( 'JSON.stringify($ref.$method.apply($ref, $serializedArgs))', ); } /// Calls `ref.method(...args)` on the JS side and returns the result. - Future callMethodReturning( - JsRef ref, - String method, - List args, - ) async { - final String serializedArgs = '[${args.map(_serializeArg).join(', ')}]'; - return controller.runJavaScriptReturningResult( - '$ref.$method.apply($ref, $serializedArgs)', - ); + Future callMethodReturning(JsRef ref, String method, List args) async { + final serializedArgs = '[${args.map(_serializeArg).join(', ')}]'; + return controller.runJavaScriptReturningResult('$ref.$method.apply($ref, $serializedArgs)'); } /// Registers `ref.addListener(eventName, ...)` on the JS side, so that /// [payloadJs] (a JS expression, evaluated with `event` bound to the /// listener's callback argument) is posted to [channel] whenever it fires. - Future addListener( - JsRef ref, - String eventName, - String channel, - String payloadJs, - ) async { + Future addListener(JsRef ref, String eventName, String channel, String payloadJs) async { await controller.runJavaScript( "$ref.addListener('$eventName', (event) => $channel.postMessage($payloadJs));", ); diff --git a/packages/google_maps_flutter/lib/src/ground_overlay.dart b/packages/google_maps_flutter/lib/src/ground_overlay.dart index 0414e909b..475e26f37 100644 --- a/packages/google_maps_flutter/lib/src/ground_overlay.dart +++ b/packages/google_maps_flutter/lib/src/ground_overlay.dart @@ -37,10 +37,7 @@ class GroundOverlayController { /// /// This cannot be called after [remove]. void update(util.GGroundOverlayOptions options) { - assert( - _groundOverlay != null, - 'Cannot `update` GroundOverlay after calling `remove`.', - ); + assert(_groundOverlay != null, 'Cannot `update` GroundOverlay after calling `remove`.'); _groundOverlay!.options = options; } diff --git a/packages/google_maps_flutter/lib/src/ground_overlays.dart b/packages/google_maps_flutter/lib/src/ground_overlays.dart index 2d89d16e7..caa93080e 100644 --- a/packages/google_maps_flutter/lib/src/ground_overlays.dart +++ b/packages/google_maps_flutter/lib/src/ground_overlays.dart @@ -15,13 +15,11 @@ class GroundOverlaysController extends GeometryController { required GoogleMapsJsBridge bridge, }) : _streamController = stream, _bridge = bridge, - _groundOverlayIdToController = - {}, + _groundOverlayIdToController = {}, _idToGroundOverlayId = {}; // A cache of [GroundOverlayController]s indexed by their [GroundOverlayId]. - final Map - _groundOverlayIdToController; + final Map _groundOverlayIdToController; final Map _idToGroundOverlayId; // The stream over which ground overlays broadcast events. @@ -42,17 +40,15 @@ class GroundOverlaysController extends GeometryController { return; } - final util.GGroundOverlayOptions? populationOptions = - _groundOverlayOptionsFromGroundOverlay(groundOverlay); + final util.GGroundOverlayOptions? populationOptions = _groundOverlayOptionsFromGroundOverlay( + groundOverlay, + ); if (populationOptions == null) { return; } - final util.GGroundOverlay gGroundOverlay = util.GGroundOverlay( - _bridge, - populationOptions, - ); - final GroundOverlayController controller = GroundOverlayController( + final gGroundOverlay = util.GGroundOverlay(_bridge, populationOptions); + final controller = GroundOverlayController( groundOverlay: gGroundOverlay, onTap: () { _onGroundOverlayTap(groundOverlay.groundOverlayId); @@ -71,8 +67,9 @@ class GroundOverlaysController extends GeometryController { void _changeGroundOverlay(GroundOverlay groundOverlay) { final GroundOverlayController? groundOverlayController = _groundOverlayIdToController[groundOverlay.groundOverlayId]; - final util.GGroundOverlayOptions? options = - _groundOverlayOptionsFromGroundOverlay(groundOverlay); + final util.GGroundOverlayOptions? options = _groundOverlayOptionsFromGroundOverlay( + groundOverlay, + ); if (groundOverlayController == null || options == null) { return; } @@ -80,8 +77,7 @@ class GroundOverlaysController extends GeometryController { // url, bounds, and clickable cannot be mutated in place. Recreate the // overlay when any of these change so updates from updateGroundOverlays // are not silently dropped. - final util.GGroundOverlayOptions? current = - groundOverlayController._groundOverlay?.options; + final util.GGroundOverlayOptions? current = groundOverlayController._groundOverlay?.options; if (current == null || current.url != options.url || current.bounds != options.bounds || diff --git a/packages/google_maps_flutter/lib/src/marker.dart b/packages/google_maps_flutter/lib/src/marker.dart index 6b258c1bc..f78fa8653 100644 --- a/packages/google_maps_flutter/lib/src/marker.dart +++ b/packages/google_maps_flutter/lib/src/marker.dart @@ -50,15 +50,10 @@ class MarkerController { LatLngCallback? dragEndEvent; Future _addMarkerEvent(GoogleMapsJsBridge bridge) async { - final JsRef ref = JsRef(_marker!.toString()); + final ref = JsRef(_marker!.toString()); final int id = _marker!.id; - final String dragPayload = 'JSON.stringify({id:$id, event:event})'; - await bridge.addListener( - ref, - 'click', - 'MarkerClick', - 'JSON.stringify($id)', - ); + final dragPayload = 'JSON.stringify({id:$id, event:event})'; + await bridge.addListener(ref, 'click', 'MarkerClick', 'JSON.stringify($id)'); await bridge.addListener(ref, 'dragstart', 'MarkerDragStart', dragPayload); await bridge.addListener(ref, 'drag', 'MarkerDrag', dragPayload); await bridge.addListener(ref, 'dragend', 'MarkerDragEnd', dragPayload); @@ -79,11 +74,7 @@ class MarkerController { /// Updates the options of the wrapped [GMarker] object. /// /// This cannot be called after [remove]. - void update( - Marker marker, - util.GMarkerOptions options, { - String? newInfoWindowContent, - }) { + void update(Marker marker, util.GMarkerOptions options, {String? newInfoWindowContent}) { assert(_marker != null, 'Cannot `update` Marker after calling `remove`.'); _marker!.options = options; if (_infoWindow != null && newInfoWindowContent != null) { diff --git a/packages/google_maps_flutter/lib/src/marker_clustering.dart b/packages/google_maps_flutter/lib/src/marker_clustering.dart index 81b1d96bb..2df839e34 100644 --- a/packages/google_maps_flutter/lib/src/marker_clustering.dart +++ b/packages/google_maps_flutter/lib/src/marker_clustering.dart @@ -21,8 +21,7 @@ class ClusterManagersController extends GeometryController { }) : _streamController = stream, _bridge = bridge, _idToClusterManagerId = {}, - _clusterManagerIdToMarkerClusterer = - {}; + _clusterManagerIdToMarkerClusterer = {}; // The stream over which cluster managers broadcast their events final StreamController> _streamController; @@ -30,13 +29,11 @@ class ClusterManagersController extends GeometryController { final GoogleMapsJsBridge _bridge; // A cache of [MarkerClusterer]s indexed by their [ClusterManagerId]. - final Map - _clusterManagerIdToMarkerClusterer; + final Map _clusterManagerIdToMarkerClusterer; final Map _idToClusterManagerId; /// A cache of [ClusterManagerId]s indexed by [GMarkerClusterer.id]. - Map get idToClusterManagerId => - _idToClusterManagerId; + Map get idToClusterManagerId => _idToClusterManagerId; /// Adds a set of [ClusterManager] objects to the cache. void addClusterManagers(Set clusterManagersToAdd) { @@ -44,29 +41,18 @@ class ClusterManagersController extends GeometryController { } void _addClusterManager(ClusterManager clusterManager) { - final String onClusterClickHandler = + final onClusterClickHandler = '(event, cluster, map) => ClusterClick.postMessage(makeClusterEvent("${clusterManager.clusterManagerId.value}", event, cluster))'; - final util.GMarkerClustererOptions options = util.GMarkerClustererOptions( - onClusterClick: onClusterClickHandler, - ); + final options = util.GMarkerClustererOptions(onClusterClick: onClusterClickHandler); - final util.GMarkerClusterer markerClusterer = util.GMarkerClusterer( - _bridge, - options, - ); + final markerClusterer = util.GMarkerClusterer(_bridge, options); - _clusterManagerIdToMarkerClusterer[clusterManager.clusterManagerId] = - markerClusterer; - _idToClusterManagerId[clusterManager.clusterManagerId.value] = - clusterManager.clusterManagerId; + _clusterManagerIdToMarkerClusterer[clusterManager.clusterManagerId] = markerClusterer; + _idToClusterManagerId[clusterManager.clusterManagerId.value] = clusterManager.clusterManagerId; // The platform interface requires this to stay synchronous, so the JS // call is fire-and-forget; only its errors need surfacing. - unawaited( - markerClusterer.onAdd().catchError( - (Object e) => debugPrint('JavaScript Error: $e'), - ), - ); + unawaited(markerClusterer.onAdd().catchError((Object e) => debugPrint('JavaScript Error: $e'))); } /// Removes a set of [ClusterManagerId]s from the cache. @@ -84,9 +70,7 @@ class ClusterManagersController extends GeometryController { .catchError((Object e) => debugPrint('JavaScript Error: $e')), ); unawaited( - markerClusterer.onRemove().catchError( - (Object e) => debugPrint('JavaScript Error: $e'), - ), + markerClusterer.onRemove().catchError((Object e) => debugPrint('JavaScript Error: $e')), ); } _clusterManagerIdToMarkerClusterer.remove(clusterManagerId); @@ -104,9 +88,7 @@ class ClusterManagersController extends GeometryController { .catchError((Object e) => debugPrint('JavaScript Error: $e')), ); unawaited( - markerClusterer.render().catchError( - (Object e) => debugPrint('JavaScript Error: $e'), - ), + markerClusterer.render().catchError((Object e) => debugPrint('JavaScript Error: $e')), ); } } @@ -125,9 +107,7 @@ class ClusterManagersController extends GeometryController { }), ); unawaited( - markerClusterer.render().catchError( - (Object e) => debugPrint('JavaScript Error: $e'), - ), + markerClusterer.render().catchError((Object e) => debugPrint('JavaScript Error: $e')), ); } } @@ -140,10 +120,7 @@ class ClusterManagersController extends GeometryController { _clusterManagerIdToMarkerClusterer[clusterManagerId]; if (markerClusterer != null) { return (await markerClusterer.clusters) - .map( - (Map cluster) => - _convertCluster(clusterManagerId, cluster), - ) + .map((Map cluster) => _convertCluster(clusterManagerId, cluster)) .toList(); } return []; @@ -155,12 +132,8 @@ class ClusterManagersController extends GeometryController { ClusterManagerId clusterManagerId, Map markerClustererCluster, ) { - if (markerClustererCluster['count'] as int > 0 && - markerClustererCluster['bounds'] != null) { - final Cluster cluster = _convertCluster( - clusterManagerId, - markerClustererCluster, - ); + if (markerClustererCluster['count'] as int > 0 && markerClustererCluster['bounds'] != null) { + final Cluster cluster = _convertCluster(clusterManagerId, markerClustererCluster); _streamController.add(ClusterTapEvent(mapId, cluster)); } } @@ -170,12 +143,12 @@ class ClusterManagersController extends GeometryController { ClusterManagerId clusterManagerId, Map markerClustererCluster, ) { - final LatLng position = LatLng( + final position = LatLng( (markerClustererCluster['position'] as dynamic)['lat'] as double, (markerClustererCluster['position'] as dynamic)['lng'] as double, ); - final LatLngBounds bounds = LatLngBounds( + final bounds = LatLngBounds( southwest: LatLng( (markerClustererCluster['bounds'] as dynamic)['south'] as double, (markerClustererCluster['bounds'] as dynamic)['west'] as double, @@ -186,18 +159,10 @@ class ClusterManagersController extends GeometryController { ), ); - final List markerIds = - (markerClustererCluster['markers']! as List) - .map( - (dynamic markerId) => MarkerId((markerId as int).toString()), - ) - .toList(); - - return Cluster( - clusterManagerId, - markerIds, - position: position, - bounds: bounds, - ); + final List markerIds = (markerClustererCluster['markers']! as List) + .map((dynamic markerId) => MarkerId((markerId as int).toString())) + .toList(); + + return Cluster(clusterManagerId, markerIds, position: position, bounds: bounds); } } diff --git a/packages/google_maps_flutter/lib/src/markers.dart b/packages/google_maps_flutter/lib/src/markers.dart index e09dbe2fd..70d7bea7f 100644 --- a/packages/google_maps_flutter/lib/src/markers.dart +++ b/packages/google_maps_flutter/lib/src/markers.dart @@ -41,8 +41,7 @@ class MarkersController extends GeometryController { return; } - final util.GInfoWindowOptions? infoWindowOptions = - _infoWindowOptionsFromMarker(marker); + final util.GInfoWindowOptions? infoWindowOptions = _infoWindowOptionsFromMarker(marker); util.GInfoWindow? infoWindow; if (infoWindowOptions != null) { @@ -53,13 +52,13 @@ class MarkersController extends GeometryController { marker, _markerIdToController[marker.markerId]?.marker, ); - final util.GMarker gMarker = util.GMarker(_bridge, populationOptions); + final gMarker = util.GMarker(_bridge, populationOptions); if (marker.clusterManagerId != null) { _clusterManagersController.addItem(marker.clusterManagerId!, gMarker); } - final MarkerController markerController = MarkerController( + final markerController = MarkerController( marker: gMarker, clusterManagerId: marker.clusterManagerId, infoWindow: infoWindow, @@ -89,22 +88,15 @@ class MarkersController extends GeometryController { } void _changeMarker(Marker marker) { - final MarkerController? markerController = - _markerIdToController[marker.markerId]; + final MarkerController? markerController = _markerIdToController[marker.markerId]; if (markerController != null) { final util.GMarkerOptions markerOptions = _markerOptionsFromMarker( marker, markerController.marker, ); - final util.GInfoWindowOptions? infoWindow = _infoWindowOptionsFromMarker( - marker, - ); - markerController.update( - marker, - markerOptions, - newInfoWindowContent: infoWindow?.content, - ); + final util.GInfoWindowOptions? infoWindow = _infoWindowOptionsFromMarker(marker); + markerController.update(marker, markerOptions, newInfoWindowContent: infoWindow?.content); } } @@ -177,10 +169,7 @@ class MarkersController extends GeometryController { void _hideAllMarkerInfoWindow() { _markerIdToController.values - .where( - (MarkerController? controller) => - controller?.infoWindowShown ?? false, - ) + .where((MarkerController? controller) => controller?.infoWindowShown ?? false) .forEach((MarkerController controller) { controller.hideInfoWindow(); }); diff --git a/packages/google_maps_flutter/lib/src/polygons.dart b/packages/google_maps_flutter/lib/src/polygons.dart index 5690f53c4..0efdbb735 100644 --- a/packages/google_maps_flutter/lib/src/polygons.dart +++ b/packages/google_maps_flutter/lib/src/polygons.dart @@ -37,11 +37,9 @@ class PolygonsController extends GeometryController { return; } - final util.GPolygonOptions populationOptions = _polygonOptionsFromPolygon( - polygon, - ); - final util.GPolygon gPolygon = util.GPolygon(_bridge, populationOptions); - final PolygonController controller = PolygonController( + final util.GPolygonOptions populationOptions = _polygonOptionsFromPolygon(polygon); + final gPolygon = util.GPolygon(_bridge, populationOptions); + final controller = PolygonController( polygon: gPolygon, consumeTapEvents: polygon.consumeTapEvents, onTap: () { @@ -59,8 +57,7 @@ class PolygonsController extends GeometryController { } void _changePolygon(Polygon polygon) { - final PolygonController? polygonController = - _polygonIdToController[polygon.polygonId]; + final PolygonController? polygonController = _polygonIdToController[polygon.polygonId]; polygonController?.update(_polygonOptionsFromPolygon(polygon)); } @@ -70,8 +67,7 @@ class PolygonsController extends GeometryController { } void _removePolygon(PolygonId polygonId) { - final PolygonController? polygonController = - _polygonIdToController[polygonId]; + final PolygonController? polygonController = _polygonIdToController[polygonId]; polygonController?.remove(); _polygonIdToController.remove(polygonId); } diff --git a/packages/google_maps_flutter/lib/src/polyline.dart b/packages/google_maps_flutter/lib/src/polyline.dart index 489a99fb1..df37cfefd 100644 --- a/packages/google_maps_flutter/lib/src/polyline.dart +++ b/packages/google_maps_flutter/lib/src/polyline.dart @@ -41,10 +41,7 @@ class PolylineController { /// /// This cannot be called after [remove]. void update(util.GPolylineOptions options) { - assert( - _polyline != null, - 'Cannot `update` Polyline after calling `remove`.', - ); + assert(_polyline != null, 'Cannot `update` Polyline after calling `remove`.'); _polyline!.options = options; } diff --git a/packages/google_maps_flutter/lib/src/polylines.dart b/packages/google_maps_flutter/lib/src/polylines.dart index 6d9cfe3b0..436e4c98b 100644 --- a/packages/google_maps_flutter/lib/src/polylines.dart +++ b/packages/google_maps_flutter/lib/src/polylines.dart @@ -37,11 +37,9 @@ class PolylinesController extends GeometryController { return; } - final util.GPolylineOptions polylineOptions = _polylineOptionsFromPolyline( - polyline, - ); - final util.GPolyline gPolyline = util.GPolyline(_bridge, polylineOptions); - final PolylineController controller = PolylineController( + final util.GPolylineOptions polylineOptions = _polylineOptionsFromPolyline(polyline); + final gPolyline = util.GPolyline(_bridge, polylineOptions); + final controller = PolylineController( polyline: gPolyline, consumeTapEvents: polyline.consumeTapEvents, onTap: () { @@ -59,8 +57,7 @@ class PolylinesController extends GeometryController { } void _changePolyline(Polyline polyline) { - final PolylineController? polylineController = - _polylineIdToController[polyline.polylineId]; + final PolylineController? polylineController = _polylineIdToController[polyline.polylineId]; polylineController?.update(_polylineOptionsFromPolyline(polyline)); } @@ -70,8 +67,7 @@ class PolylinesController extends GeometryController { } void _removePolyline(PolylineId polylineId) { - final PolylineController? polylineController = - _polylineIdToController[polylineId]; + final PolylineController? polylineController = _polylineIdToController[polylineId]; polylineController?.remove(); _polylineIdToController.remove(polylineId); } diff --git a/packages/google_maps_flutter/lib/src/util.dart b/packages/google_maps_flutter/lib/src/util.dart index c4177a847..2158c92c1 100644 --- a/packages/google_maps_flutter/lib/src/util.dart +++ b/packages/google_maps_flutter/lib/src/util.dart @@ -16,10 +16,7 @@ import 'google_maps_js_bridge.dart'; const LatLng nullLatLng = LatLng(0, 0); /// Default LatLngBounds. -final LatLngBounds nullLatLngBounds = LatLngBounds( - southwest: nullLatLng, - northeast: nullLatLng, -); +final LatLngBounds nullLatLngBounds = LatLngBounds(southwest: nullLatLng, northeast: nullLatLng); /// Default ScreenCoordinate. const ScreenCoordinate nullScreenCoordinate = ScreenCoordinate(x: 0, y: 0); @@ -141,7 +138,7 @@ class GInfoWindowOptions { @override String toString() { - final String pos = position != null + final pos = position != null ? '{lat:${position?.latitude}, lng:${position?.longitude}}' : 'null'; final String contentJs = content != null ? jsonEncode(content) : 'null'; @@ -199,9 +196,7 @@ class GInfoWindow { set pixelOffset(GSize? size) => _setPixelOffset(size); Future _setContent(Object? /*String?|Node?*/ content) async { - await _bridge.callMethod(JsRef(toString()), 'setContent', [ - content, - ]); + await _bridge.callMethod(JsRef(toString()), 'setContent', [content]); } Future _setPixelOffset(GSize? size) async { @@ -226,10 +221,7 @@ class GMarker { final GoogleMapsJsBridge _bridge; Future _createMarker(GMarkerOptions? opts) async { - final JsRef ref = await _bridge.createObject( - toString(), - 'new google.maps.Marker($opts)', - ); + final JsRef ref = await _bridge.createObject(toString(), 'new google.maps.Marker($opts)'); await _bridge.setProperty(ref, 'id', id); } @@ -296,9 +288,7 @@ class GMarker { } Future _setOptions(GMarkerOptions? options) async { - await _bridge.callMethod(JsRef(toString()), 'setOptions', [ - options, - ]); + await _bridge.callMethod(JsRef(toString()), 'setOptions', [options]); } Future _setVisible(bool? visible) async { @@ -306,9 +296,7 @@ class GMarker { } Future _setDraggable(bool? visible) async { - await _bridge.callMethod(JsRef(toString()), 'setDraggable', [ - visible, - ]); + await _bridge.callMethod(JsRef(toString()), 'setDraggable', [visible]); } Future _setIcon(Object? icon) async { @@ -321,9 +309,7 @@ class GMarker { Future _setPosition(LatLng? position) async { await _bridge.callMethod(JsRef(toString()), 'setPosition', [ - JsExpression( - 'new google.maps.LatLng(${position!.latitude},${position.longitude})', - ), + JsExpression('new google.maps.LatLng(${position!.latitude},${position.longitude})'), ]); } @@ -340,9 +326,7 @@ class GMarker { /// map. class GPolyline { /// GPolyline Constructor. - GPolyline(GoogleMapsJsBridge bridge, [GPolylineOptions? opts]) - : _bridge = bridge, - id = _gid++ { + GPolyline(GoogleMapsJsBridge bridge, [GPolylineOptions? opts]) : _bridge = bridge, id = _gid++ { _createPolyline(opts); } @@ -382,11 +366,7 @@ class GPolyline { } Future _setOptions(GPolylineOptions? options) async { - await _bridge.callMethod( - JsRef(toString()), - 'setOptions', - [options], - ); + await _bridge.callMethod(JsRef(toString()), 'setOptions', [options]); } } @@ -419,12 +399,10 @@ class GPolylineOptions { @override String toString() { - final StringBuffer paths = StringBuffer(); + final paths = StringBuffer(); for (final LatLng? position in path!) { if (position != null) { - paths.write( - 'new google.maps.LatLng(${position.latitude},${position.longitude}), ', - ); + paths.write('new google.maps.LatLng(${position.latitude},${position.longitude}), '); } } @@ -437,9 +415,7 @@ class GPolylineOptions { /// connected coordinates in an ordered sequence. class GPolygon { /// GPolygon Constructor. - GPolygon(GoogleMapsJsBridge bridge, [GPolygonOptions? opts]) - : _bridge = bridge, - id = _gid++ { + GPolygon(GoogleMapsJsBridge bridge, [GPolygonOptions? opts]) : _bridge = bridge, id = _gid++ { _createPolygon(opts); } @@ -479,11 +455,7 @@ class GPolygon { } Future _setOptions(GPolygonOptions? options) async { - await _bridge.callMethod( - JsRef(toString()), - 'setOptions', - [options], - ); + await _bridge.callMethod(JsRef(toString()), 'setOptions', [options]); } } @@ -522,14 +494,12 @@ class GPolygonOptions { @override String toString() { - final StringBuffer str = StringBuffer(); + final str = StringBuffer(); for (final List? latlng in paths!) { str.write('['); for (final LatLng? position in latlng!) { if (position != null) { - str.write( - 'new google.maps.LatLng(${position.latitude},${position.longitude}), ', - ); + str.write('new google.maps.LatLng(${position.latitude},${position.longitude}), '); } } str.write('], '); @@ -544,9 +514,7 @@ class GPolygonOptions { /// This class represents a circle using the passed GCircleOptions. class GCircle { /// GCircle Constructor. - GCircle(GoogleMapsJsBridge bridge, [GCircleOptions? opts]) - : _bridge = bridge, - id = _gid++ { + GCircle(GoogleMapsJsBridge bridge, [GCircleOptions? opts]) : _bridge = bridge, id = _gid++ { _createCircle(opts); } @@ -593,9 +561,7 @@ class GCircle { } Future _setOptions(GCircleOptions? options) async { - await _bridge.callMethod(JsRef(toString()), 'setOptions', [ - options, - ]); + await _bridge.callMethod(JsRef(toString()), 'setOptions', [options]); } } @@ -656,10 +622,7 @@ class GMarkerClusterer { late final Future _ready; Future _createMarkerClusterer(GMarkerClustererOptions? opts) async { - await _bridge.createObject( - toString(), - 'new markerClusterer.MarkerClusterer($opts)', - ); + await _bridge.createObject(toString(), 'new markerClusterer.MarkerClusterer($opts)'); } /// GCircle id. @@ -671,20 +634,16 @@ class GMarkerClusterer { /// Adds a marker to be clustered by the [GMarkerClusterer]. Future addMarker(GMarker marker, bool? noDraw) async { await _ready; - await _bridge.callMethod(_ref, 'addMarker', [ - JsRef(marker.toString()), - noDraw, - ]); + await _bridge.callMethod(_ref, 'addMarker', [JsRef(marker.toString()), noDraw]); } /// Removes a marker from the [GMarkerClusterer]. Future removeMarker(GMarker marker, bool? noDraw) async { await _ready; - final Object? result = await _bridge.callMethodReturning( - _ref, - 'removeMarker', - [JsRef(marker.toString()), noDraw], - ); + final Object? result = await _bridge.callMethodReturning(_ref, 'removeMarker', [ + JsRef(marker.toString()), + noDraw, + ]); return result! as bool; } @@ -697,12 +656,10 @@ class GMarkerClusterer { /// Returns the list of clusters. Future>> get clusters async { await _ready; - final String value = - await _bridge.runJavaScriptReturningResult( - 'JSON.stringify(${toString()}.clusters)', - ) + final value = + await _bridge.runJavaScriptReturningResult('JSON.stringify(${toString()}.clusters)') as String; - final List results = json.decode(value) as List; + final results = json.decode(value) as List; return results.cast>(); } @@ -751,7 +708,7 @@ class GMarkerClustererOptions { @override String toString() { - String options = '{map: map'; + var options = '{map: map'; if (markers != null) { options += ', markers: $markers'; } diff --git a/packages/google_sign_in/CHANGELOG.md b/packages/google_sign_in/CHANGELOG.md index ec89f7c0a..dcc8711c6 100644 --- a/packages/google_sign_in/CHANGELOG.md +++ b/packages/google_sign_in/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 0.2.2 * Add an `implements` entry to the pubspec to improve discoverability on pub.dev. diff --git a/packages/google_sign_in/example/lib/credentials.dart b/packages/google_sign_in/example/lib/credentials.dart index 2f8b51101..d7f0169ef 100644 --- a/packages/google_sign_in/example/lib/credentials.dart +++ b/packages/google_sign_in/example/lib/credentials.dart @@ -6,6 +6,5 @@ // on source respositories. // // Developers should fill their own credentials to run the app. -const String clientId = - '87599666314-cobrkfg77lk98a6c8l3o2ntn8d9g6s6l.apps.googleusercontent.com'; +const String clientId = '87599666314-cobrkfg77lk98a6c8l3o2ntn8d9g6s6l.apps.googleusercontent.com'; const String clientSecret = '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'; diff --git a/packages/google_sign_in/example/lib/main.dart b/packages/google_sign_in/example/lib/main.dart index 8488c6ec0..556d31d5a 100644 --- a/packages/google_sign_in/example/lib/main.dart +++ b/packages/google_sign_in/example/lib/main.dart @@ -26,9 +26,7 @@ String? serverClientId; /// The scopes required by this application. // #docregion CheckAuthorization -const List scopes = [ - 'https://www.googleapis.com/auth/contacts.readonly', -]; +const List scopes = ['https://www.googleapis.com/auth/contacts.readonly']; // #enddocregion CheckAuthorization void main() { @@ -68,9 +66,7 @@ class _SignInDemoState extends State { // #docregion Setup final GoogleSignIn signIn = GoogleSignIn.instance; unawaited( - signIn.initialize(clientId: clientId, serverClientId: serverClientId).then(( - _, - ) { + signIn.initialize(clientId: clientId, serverClientId: serverClientId).then((_) { signIn.authenticationEvents .listen(_handleAuthenticationEvent) .onError(_handleAuthenticationError); @@ -84,9 +80,7 @@ class _SignInDemoState extends State { // #enddocregion Setup } - Future _handleAuthenticationEvent( - GoogleSignInAuthenticationEvent event, - ) async { + Future _handleAuthenticationEvent(GoogleSignInAuthenticationEvent event) async { // #docregion CheckAuthorization final GoogleSignInAccount? user = // ... // #enddocregion CheckAuthorization @@ -97,8 +91,7 @@ class _SignInDemoState extends State { // Check for existing authorization. // #docregion CheckAuthorization - final GoogleSignInClientAuthorization? authorization = await user - ?.authorizationClient + final GoogleSignInClientAuthorization? authorization = await user?.authorizationClient .authorizationForScopes(scopes); // #enddocregion CheckAuthorization @@ -120,9 +113,7 @@ class _SignInDemoState extends State { _currentUser = null; _isAuthorized = false; _errorMessage = - e is GoogleSignInException - ? _errorMessageFromSignInException(e) - : 'Unknown error: $e'; + e is GoogleSignInException ? _errorMessageFromSignInException(e) : 'Unknown error: $e'; }); } @@ -131,8 +122,9 @@ class _SignInDemoState extends State { setState(() { _contactText = 'Loading contact info...'; }); - final Map? headers = await user.authorizationClient - .authorizationHeaders(scopes); + final Map? headers = await user.authorizationClient.authorizationHeaders( + scopes, + ); if (headers == null) { setState(() { _contactText = ''; @@ -165,8 +157,7 @@ class _SignInDemoState extends State { } return; } - final Map data = - json.decode(response.body) as Map; + final data = json.decode(response.body) as Map; final String? namedContact = _pickFirstNamedContact(data); setState(() { if (namedContact != null) { @@ -178,20 +169,18 @@ class _SignInDemoState extends State { } String? _pickFirstNamedContact(Map data) { - final List? connections = data['connections'] as List?; - final Map? contact = + final connections = data['connections'] as List?; + final contact = connections?.firstWhere( - (dynamic contact) => - (contact as Map)['names'] != null, + (dynamic contact) => (contact as Map)['names'] != null, orElse: () => null, ) as Map?; if (contact != null) { - final List names = contact['names'] as List; - final Map? name = + final names = contact['names'] as List; + final name = names.firstWhere( - (dynamic name) => - (name as Map)['displayName'] != null, + (dynamic name) => (name as Map)['displayName'] != null, orElse: () => null, ) as Map?; @@ -210,8 +199,7 @@ class _SignInDemoState extends State { Future _handleAuthorizeScopes(GoogleSignInAccount user) async { try { // #docregion RequestScopes - final GoogleSignInClientAuthorization authorization = await user - .authorizationClient + final GoogleSignInClientAuthorization authorization = await user.authorizationClient .authorizeScopes(scopes); // #enddocregion RequestScopes @@ -244,8 +232,7 @@ class _SignInDemoState extends State { Future _handleGetAuthCode(GoogleSignInAccount user) async { try { // #docregion RequestServerAuth - final GoogleSignInServerAuthorization? serverAuth = await user - .authorizationClient + final GoogleSignInServerAuthorization? serverAuth = await user.authorizationClient .authorizeServer(scopes); // #enddocregion RequestServerAuth @@ -292,10 +279,7 @@ class _SignInDemoState extends State { if (_isAuthorized) ...[ // The user has Authorized all required scopes. if (_contactText.isNotEmpty) Text(_contactText), - ElevatedButton( - child: const Text('REFRESH'), - onPressed: () => _handleGetContact(user), - ), + ElevatedButton(child: const Text('REFRESH'), onPressed: () => _handleGetContact(user)), if (_serverAuthCode.isEmpty) ElevatedButton( child: const Text('REQUEST SERVER CODE'), @@ -338,9 +322,7 @@ class _SignInDemoState extends State { web.renderButton() // #enddocregion ExplicitSignIn else - const Text( - 'This platform does not have a known authentication method', - ), + const Text('This platform does not have a known authentication method'), // #docregion ExplicitSignIn ], // #enddocregion ExplicitSignIn @@ -351,10 +333,7 @@ class _SignInDemoState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Google Sign In')), - body: ConstrainedBox( - constraints: const BoxConstraints.expand(), - child: _buildBody(), - ), + body: ConstrainedBox(constraints: const BoxConstraints.expand(), child: _buildBody()), ); } diff --git a/packages/google_sign_in/lib/google_sign_in_tizen.dart b/packages/google_sign_in/lib/google_sign_in_tizen.dart index 41137d83c..17ae250c4 100644 --- a/packages/google_sign_in/lib/google_sign_in_tizen.dart +++ b/packages/google_sign_in/lib/google_sign_in_tizen.dart @@ -14,11 +14,7 @@ import 'src/oauth2.dart'; export 'src/authorization_exception.dart'; -const List _authenticationScopes = [ - 'openid', - 'email', - 'profile', -]; +const List _authenticationScopes = ['openid', 'email', 'profile']; /// Holds authentication data after Google sign in for Tizen. class _GoogleSignInTokenDataTizen { @@ -48,17 +44,13 @@ class _GoogleSignInTokenDataTizen { /// Returns `true` if [accessToken] is expired and needs to be refreshed. bool get isExpired { - const Duration minimalTimeToExpire = Duration(minutes: 1); - return DateTime.now() - .add(minimalTimeToExpire) - .isAfter(accessTokenExpirationDate); + const minimalTimeToExpire = Duration(minutes: 1); + return DateTime.now().add(minimalTimeToExpire).isAfter(accessTokenExpirationDate); } /// Returns `true` if all [scopes] are granted by [accessToken]. bool grantsScopes(List scopes) { - return scopes - .map(_normalizeScope) - .every((String scope) => grantedScopes.contains(scope)); + return scopes.map(_normalizeScope).every((String scope) => grantedScopes.contains(scope)); } /// Returns a copy whose access token will be refreshed on next use. @@ -77,9 +69,7 @@ class _GoogleSignInTokenDataTizen { final Object? grantedScopesJson = json['granted_scopes']; return _GoogleSignInTokenDataTizen( accessToken: json['access_token']! as String, - accessTokenExpirationDate: DateTime.parse( - json['access_token_expiration_date']! as String, - ), + accessTokenExpirationDate: DateTime.parse(json['access_token_expiration_date']! as String), idToken: json['id_token']! as String, refreshToken: json['refresh_token'] as String?, grantedScopes: @@ -93,8 +83,7 @@ class _GoogleSignInTokenDataTizen { Map toJson() { return { 'access_token': accessToken, - 'access_token_expiration_date': - accessTokenExpirationDate.toIso8601String(), + 'access_token_expiration_date': accessTokenExpirationDate.toIso8601String(), 'id_token': idToken, 'granted_scopes': grantedScopes.toList(), if (refreshToken != null) 'refresh_token': refreshToken!, @@ -138,9 +127,7 @@ class _CachedTokenStorage { return null; } try { - _token = _GoogleSignInTokenDataTizen.fromJson( - jsonDecode(jsonString) as Map, - ); + _token = _GoogleSignInTokenDataTizen.fromJson(jsonDecode(jsonString) as Map); return _token; } catch (_) { await removeToken(); @@ -166,9 +153,7 @@ class GoogleSignInTizen extends GoogleSignInPlatform { final _CachedTokenStorage _storage = _CachedTokenStorage(); final DeviceAuthClient _authClient = DeviceAuthClient( - authorizationEndPoint: Uri.parse( - 'https://oauth2.googleapis.com/device/code', - ), + authorizationEndPoint: Uri.parse('https://oauth2.googleapis.com/device/code'), tokenEndPoint: Uri.parse('https://oauth2.googleapis.com/token'), revokeEndPoint: Uri.parse('https://oauth2.googleapis.com/revoke'), ); @@ -176,10 +161,7 @@ class GoogleSignInTizen extends GoogleSignInPlatform { /// Sets [clientId] and [clientSecret] to be used for GoogleSignIn authentication. /// /// This must be called before calling [GoogleSignIn.initialize]. - static void setCredentials({ - required String clientId, - required String clientSecret, - }) { + static void setCredentials({required String clientId, required String clientSecret}) { _credentials = _Credentials(clientId, clientSecret); } @@ -191,8 +173,7 @@ class GoogleSignInTizen extends GoogleSignInPlatform { /// /// If [MaterialApp] or [CupertinoApp] is used, it's convinient to /// assign this object to their `navigatorKey` parameter. - static GlobalKey get navigatorKey => - device_flow_widget.navigatorKey; + static GlobalKey get navigatorKey => device_flow_widget.navigatorKey; /// Sets the [GlobalKey] that identifies a [NavigatorState]. /// @@ -266,12 +247,8 @@ class GoogleSignInTizen extends GoogleSignInPlatform { bool supportsAuthenticate() => true; @override - Future authenticate( - AuthenticateParameters params, - ) async { - final _GoogleSignInTokenDataTizen token = await _signInWithDeviceFlow( - _authenticationScopes, - ); + Future authenticate(AuthenticateParameters params) async { + final _GoogleSignInTokenDataTizen token = await _signInWithDeviceFlow(_authenticationScopes); await _storage.saveToken(token); return AuthenticationResults( user: _userDataFromIdToken(token.idToken), @@ -291,9 +268,7 @@ class GoogleSignInTizen extends GoogleSignInPlatform { if (existingToken != null && _tokenMatchesRequestedUser(existingToken, request) && existingToken.grantsScopes(request.scopes)) { - return ClientAuthorizationTokenData( - accessToken: existingToken.accessToken, - ); + return ClientAuthorizationTokenData(accessToken: existingToken.accessToken); } if (!request.promptIfUnauthorized) { @@ -333,13 +308,9 @@ class GoogleSignInTizen extends GoogleSignInPlatform { } @override - Future clearAuthorizationToken( - ClearAuthorizationTokenParams params, - ) async { - final _GoogleSignInTokenDataTizen? existingToken = - await _storage.getToken(); - if (existingToken == null || - existingToken.accessToken != params.accessToken) { + Future clearAuthorizationToken(ClearAuthorizationTokenParams params) async { + final _GoogleSignInTokenDataTizen? existingToken = await _storage.getToken(); + if (existingToken == null || existingToken.accessToken != params.accessToken) { return; } await _storage.saveToken(existingToken.withInvalidatedAccessToken()); @@ -350,8 +321,7 @@ class GoogleSignInTizen extends GoogleSignInPlatform { @override Future disconnect(DisconnectParams params) async { - final _GoogleSignInTokenDataTizen? existingToken = - await _storage.getToken(); + final _GoogleSignInTokenDataTizen? existingToken = await _storage.getToken(); if (existingToken == null) { return; } @@ -368,8 +338,7 @@ class GoogleSignInTizen extends GoogleSignInPlatform { } Future<_GoogleSignInTokenDataTizen?> _getValidToken() async { - final _GoogleSignInTokenDataTizen? existingToken = - await _storage.getToken(); + final _GoogleSignInTokenDataTizen? existingToken = await _storage.getToken(); if (existingToken == null) { return null; } @@ -382,9 +351,7 @@ class GoogleSignInTizen extends GoogleSignInPlatform { } try { - final _GoogleSignInTokenDataTizen token = await _refreshToken( - existingToken, - ); + final _GoogleSignInTokenDataTizen token = await _refreshToken(existingToken); await _storage.saveToken(token); return token; } on AuthorizationException catch (error) { @@ -398,19 +365,19 @@ class GoogleSignInTizen extends GoogleSignInPlatform { } } - Future<_GoogleSignInTokenDataTizen> _signInWithDeviceFlow( - List scopes, - ) async { + Future<_GoogleSignInTokenDataTizen> _signInWithDeviceFlow(List scopes) async { _ensureSetCredentials(); _ensureNavigatorKeyAssigned(); - bool expired = false; - bool canceled = false; - bool widgetShown = false; + var expired = false; + var canceled = false; + var widgetShown = false; try { - final AuthorizationResponse authorizationResponse = await _authClient - .requestAuthorization(_credentials!.clientId, scopes); + final AuthorizationResponse authorizationResponse = await _authClient.requestAuthorization( + _credentials!.clientId, + scopes, + ); final Future tokenResponseFuture = _authClient.pollToken( clientId: _credentials!.clientId, @@ -497,9 +464,7 @@ class GoogleSignInTizen extends GoogleSignInPlatform { throw const FormatException('Invalid idToken.'); } final String normalizedPayload = base64Url.normalize(splitTokens[1]); - final String payloadString = utf8.decode( - base64Url.decode(normalizedPayload), - ); + final String payloadString = utf8.decode(base64Url.decode(normalizedPayload)); json = jsonDecode(payloadString) as Map; } catch (error) { throw GoogleSignInException( @@ -509,8 +474,8 @@ class GoogleSignInTizen extends GoogleSignInPlatform { ); } - final String? email = json['email'] as String?; - final String? id = json['sub'] as String?; + final email = json['email'] as String?; + final id = json['sub'] as String?; if (email == null || id == null) { throw const GoogleSignInException( code: GoogleSignInExceptionCode.providerConfigurationError, @@ -526,9 +491,7 @@ class GoogleSignInTizen extends GoogleSignInPlatform { ); } - Future<_GoogleSignInTokenDataTizen> _refreshToken( - _GoogleSignInTokenDataTizen token, - ) async { + Future<_GoogleSignInTokenDataTizen> _refreshToken(_GoogleSignInTokenDataTizen token) async { _ensureSetCredentials(); final TokenResponse tokenResponse = await _authClient.refreshToken( @@ -557,16 +520,11 @@ class GoogleSignInTizen extends GoogleSignInPlatform { } List _scopesForAuthentication(List scopes) { - return { - ..._authenticationScopes, - ...scopes.map(_normalizeScope), - }.toList(); + return {..._authenticationScopes, ...scopes.map(_normalizeScope)}.toList(); } } -GoogleSignInException _exceptionFromAuthorizationException( - AuthorizationException error, -) { +GoogleSignInException _exceptionFromAuthorizationException(AuthorizationException error) { final GoogleSignInExceptionCode code = switch (error.error) { 'access_denied' => GoogleSignInExceptionCode.canceled, 'invalid_client' => GoogleSignInExceptionCode.clientConfigurationError, @@ -576,10 +534,7 @@ GoogleSignInException _exceptionFromAuthorizationException( return GoogleSignInException( code: code, description: error.description ?? error.error, - details: { - 'error': error.error, - 'uri': error.uri?.toString(), - }, + details: {'error': error.error, 'uri': error.uri?.toString()}, ); } diff --git a/packages/google_sign_in/lib/src/authorization_exception.dart b/packages/google_sign_in/lib/src/authorization_exception.dart index d03a9f3d8..1fd23621e 100644 --- a/packages/google_sign_in/lib/src/authorization_exception.dart +++ b/packages/google_sign_in/lib/src/authorization_exception.dart @@ -21,7 +21,7 @@ class AuthorizationException implements Exception { @override String toString() { - String errorString = 'Authorization error ($error)'; + var errorString = 'Authorization error ($error)'; if (description != null) { errorString = '$errorString: $description'; } diff --git a/packages/google_sign_in/lib/src/device_flow_widget.dart b/packages/google_sign_in/lib/src/device_flow_widget.dart index c85a452ea..84b7ed631 100644 --- a/packages/google_sign_in/lib/src/device_flow_widget.dart +++ b/packages/google_sign_in/lib/src/device_flow_widget.dart @@ -40,8 +40,9 @@ void showDeviceFlowWidget({ final TextStyle bodyStyle = Theme.of( context, ).textTheme.bodyLarge!.copyWith(color: Colors.black); - final TextStyle titleStyle = Theme.of(context).textTheme.titleLarge! - .copyWith(color: Colors.black, fontWeight: FontWeight.bold); + final TextStyle titleStyle = Theme.of( + context, + ).textTheme.titleLarge!.copyWith(color: Colors.black, fontWeight: FontWeight.bold); return AlertDialog( scrollable: true, @@ -49,18 +50,11 @@ void showDeviceFlowWidget({ content: Column( mainAxisSize: MainAxisSize.min, children: [ - FittedBox( - child: Text( - 'From a PC, phone, or tablet go to:', - style: bodyStyle, - ), - ), + FittedBox(child: Text('From a PC, phone, or tablet go to:', style: bodyStyle)), const SizedBox(height: 5), FittedBox(child: Text('$verificationUrl', style: titleStyle)), const SizedBox(height: 15), - FittedBox( - child: Text('Or scan the following QR code:', style: bodyStyle), - ), + FittedBox(child: Text('Or scan the following QR code:', style: bodyStyle)), const SizedBox(height: 5), SvgPicture.asset( 'assets/images/qrcode.svg', @@ -69,9 +63,7 @@ void showDeviceFlowWidget({ height: 100, ), const SizedBox(height: 15), - FittedBox( - child: Text('Then enter the code below:', style: bodyStyle), - ), + FittedBox(child: Text('Then enter the code below:', style: bodyStyle)), const SizedBox(height: 5), FittedBox(child: Text(code, style: titleStyle)), const SizedBox(height: 15), @@ -101,11 +93,7 @@ void showDeviceFlowWidget({ } class _CountdownTimer extends StatefulWidget { - const _CountdownTimer( - this.duration, { - required this.style, - required this.onFinished, - }); + const _CountdownTimer(this.duration, {required this.style, required this.onFinished}); final Duration duration; final TextStyle style; @@ -139,10 +127,7 @@ class _CountdownTimerState extends State<_CountdownTimer> { @override Widget build(BuildContext context) { final String minutes = _remaining.inMinutes.toString().padLeft(2, '0'); - final String seconds = _remaining.inSeconds - .remainder(60) - .toString() - .padLeft(2, '0'); + final String seconds = _remaining.inSeconds.remainder(60).toString().padLeft(2, '0'); return FittedBox(child: Text('$minutes:$seconds', style: widget.style)); } diff --git a/packages/google_sign_in/lib/src/oauth2.dart b/packages/google_sign_in/lib/src/oauth2.dart index 4db7c1ada..e1f8e1f35 100644 --- a/packages/google_sign_in/lib/src/oauth2.dart +++ b/packages/google_sign_in/lib/src/oauth2.dart @@ -24,17 +24,13 @@ class AuthorizationResponse { /// Creates a [AuthorizationResponse] from a json object. static AuthorizationResponse fromJson(Map json) { final String? verificationUrl = - json['verification_url'] as String? ?? - json['verification_uri'] as String?; + json['verification_url'] as String? ?? json['verification_uri'] as String?; return AuthorizationResponse._( deviceCode: json['device_code']! as String, userCode: json['user_code']! as String, verificationUrl: Uri.parse(verificationUrl!), expiresIn: Duration(seconds: json['expires_in']! as int), - interval: - json['interval'] is int - ? Duration(seconds: json['interval']! as int) - : null, + interval: json['interval'] is int ? Duration(seconds: json['interval']! as int) : null, ); } @@ -76,10 +72,7 @@ class TokenResponse { tokenType: json['token_type']! as String, expiresIn: Duration(seconds: json['expires_in']! as int), refreshToken: json['refresh_token'] as String?, - scope: - json['scope'] is String - ? (json['scope']! as String).split(' ').toList() - : null, + scope: json['scope'] is String ? (json['scope']! as String).split(' ').toList() : null, idToken: json['id_token'] as String?, ); } @@ -148,19 +141,10 @@ class DeviceAuthClient { } /// Requests authroization grant from [authorizationEndPoint]. - Future requestAuthorization( - String clientId, - List scope, - ) async { - final Map body = { - 'client_id': clientId, - 'scope': scope.join(' '), - }; + Future requestAuthorization(String clientId, List scope) async { + final body = {'client_id': clientId, 'scope': scope.join(' ')}; - final http.Response response = await _httpClient.post( - authorizationEndPoint, - body: body, - ); + final http.Response response = await _httpClient.post(authorizationEndPoint, body: body); if (response.statusCode != 200) { _handleErrorResponse(response); @@ -177,25 +161,20 @@ class DeviceAuthClient { String clientSecret, String deviceCode, ) async { - final Map body = { + final body = { 'grant_type': 'http://oauth.net/grant_type/device/1.0', 'client_id': clientId, 'client_secret': clientSecret, 'code': deviceCode, }; - final http.Response response = await _httpClient.post( - tokenEndPoint, - body: body, - ); + final http.Response response = await _httpClient.post(tokenEndPoint, body: body); if (response.statusCode != 200) { _handleErrorResponse(response); } - return TokenResponse.fromJson( - convert.jsonDecode(response.body) as Map, - ); + return TokenResponse.fromJson(convert.jsonDecode(response.body) as Map); } /// Repeat sending token request to [tokenEndPoint] until user grants access. @@ -269,12 +248,9 @@ class DeviceAuthClient { /// Requests a revoke token request to [revokeEndPoint]. Future revokeToken(String token) async { - final Map body = {'token': token}; + final body = {'token': token}; - final http.Response response = await _httpClient.post( - revokeEndPoint, - body: body, - ); + final http.Response response = await _httpClient.post(revokeEndPoint, body: body); if (response.statusCode != 200) { _handleErrorResponse(response); } @@ -286,45 +262,33 @@ class DeviceAuthClient { required String clientSecret, required String refreshToken, }) async { - final Map body = { + final body = { 'client_id': clientId, 'client_secret': clientSecret, 'refresh_token': refreshToken, 'grant_type': 'refresh_token', }; - final http.Response response = await _httpClient.post( - tokenEndPoint, - body: body, - ); + final http.Response response = await _httpClient.post(tokenEndPoint, body: body); if (response.statusCode != 200) { _handleErrorResponse(response); } - return TokenResponse.fromJson( - convert.jsonDecode(response.body) as Map, - ); + return TokenResponse.fromJson(convert.jsonDecode(response.body) as Map); } void _handleErrorResponse(http.Response response) { // Google Token endpoint returns status code 428 for 'authroization_pending' // response which is not specified in the spec: https://datatracker.ietf.org/doc/html/rfc8628#section-3.5. - if (response.statusCode == 400 || - response.statusCode == 401 || - response.statusCode == 428) { - final Map json = - convert.jsonDecode(response.body) as Map; + if (response.statusCode == 400 || response.statusCode == 401 || response.statusCode == 428) { + final json = convert.jsonDecode(response.body) as Map; throw AuthorizationException( json['error']! as String, json['error_description']! as String?, - json['error_uri'] is String - ? Uri.parse(json['error_uri']! as String) - : null, + json['error_uri'] is String ? Uri.parse(json['error_uri']! as String) : null, ); } else { - throw HttpException( - 'Status code: ${response.statusCode}, ${response.reasonPhrase}.', - ); + throw HttpException('Status code: ${response.statusCode}, ${response.reasonPhrase}.'); } } } diff --git a/packages/image_picker/CHANGELOG.md b/packages/image_picker/CHANGELOG.md index 0a4ebeabd..57e907ef3 100644 --- a/packages/image_picker/CHANGELOG.md +++ b/packages/image_picker/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 2.3.2 * Update code format. diff --git a/packages/image_picker/example/lib/main.dart b/packages/image_picker/example/lib/main.dart index 9144231c0..dc8fdd6da 100644 --- a/packages/image_picker/example/lib/main.dart +++ b/packages/image_picker/example/lib/main.dart @@ -76,7 +76,7 @@ class _MyHomePageState extends State { // Mute the video so it auto-plays in web! // This is not needed if the call to .play is the result of user // interaction (clicking on a "play" button, for example). - const double volume = kIsWeb ? 0.0 : 1.0; + const volume = kIsWeb ? 0.0 : 1.0; await controller.setVolume(volume); await controller.initialize(); await controller.setLooping(true); @@ -135,7 +135,7 @@ class _MyHomePageState extends State { int? quality, ) async { try { - final List pickedFileList = []; + final pickedFileList = []; final XFile? media = await _picker.pickMedia( maxWidth: maxWidth, maxHeight: maxHeight, @@ -274,10 +274,10 @@ class _MyHomePageState extends State { } Widget _buildInlineVideoPlayer(int index) { - final VideoPlayerController controller = VideoPlayerController.file( + final controller = VideoPlayerController.file( File(_mediaFileList![index].path), ); - const double volume = kIsWeb ? 0.0 : 1.0; + const volume = kIsWeb ? 0.0 : 1.0; controller.setVolume(volume); controller.initialize(); controller.setLooping(true); @@ -466,7 +466,7 @@ class _MyHomePageState extends State { Text? _getRetrieveErrorWidget() { if (_retrieveDataError != null) { - final Text result = Text(_retrieveDataError!); + final result = Text(_retrieveDataError!); _retrieveDataError = null; return result; } @@ -527,9 +527,8 @@ class _MyHomePageState extends State { final double? height = maxHeightController.text.isNotEmpty ? double.parse(maxHeightController.text) : null; - final int? quality = qualityController.text.isNotEmpty - ? int.parse(qualityController.text) - : null; + final int? quality = + qualityController.text.isNotEmpty ? int.parse(qualityController.text) : null; onPick(width, height, quality); Navigator.of(context).pop(); }, @@ -541,8 +540,7 @@ class _MyHomePageState extends State { } } -typedef OnPickImageCallback = void Function( - double? maxWidth, double? maxHeight, int? quality); +typedef OnPickImageCallback = void Function(double? maxWidth, double? maxHeight, int? quality); class AspectRatioVideo extends StatefulWidget { const AspectRatioVideo(this.controller, {super.key}); diff --git a/packages/image_picker/lib/image_picker_tizen.dart b/packages/image_picker/lib/image_picker_tizen.dart index f361aec38..c24c88a0f 100644 --- a/packages/image_picker/lib/image_picker_tizen.dart +++ b/packages/image_picker/lib/image_picker_tizen.dart @@ -143,8 +143,7 @@ class ImagePickerTizen extends CameraDelegatingImagePickerPlatform { throw ArgumentError.value(maxHeight, 'maxHeight', 'cannot be negative'); } - return _channel - .invokeMethod?>('pickMultiImage', { + return _channel.invokeMethod?>('pickMultiImage', { 'maxWidth': maxWidth, 'maxHeight': maxHeight, 'imageQuality': imageQuality, @@ -156,18 +155,16 @@ class ImagePickerTizen extends CameraDelegatingImagePickerPlatform { Future> getMedia({required MediaOptions options}) async { final ImageOptions imageOptions = options.imageOptions; - final Map args = { + final args = { 'maxImageWidth': imageOptions.maxWidth, 'maxImageHeight': imageOptions.maxHeight, 'imageQuality': imageOptions.imageQuality, 'allowMultiple': options.allowMultiple, }; - final List? paths = - await _channel.invokeMethod?>('pickMedia', args).then( - (List? paths) => - paths?.map((dynamic path) => XFile(path as String)).toList(), - ); + final List? paths = await _channel.invokeMethod?>('pickMedia', args).then( + (List? paths) => paths?.map((dynamic path) => XFile(path as String)).toList(), + ); return paths ?? []; } diff --git a/packages/in_app_purchase/CHANGELOG.md b/packages/in_app_purchase/CHANGELOG.md index 2955aa8ba..549a0fc0b 100644 --- a/packages/in_app_purchase/CHANGELOG.md +++ b/packages/in_app_purchase/CHANGELOG.md @@ -6,6 +6,8 @@ * Load `libvconf` and `libcapi-system-info` by their major SONAME. * Remove unused private system info keys. * Resolve `unintended_html_in_doc_comment` lint. +* Omit obvious local variable types. +* Reformat with a line length of 100. ## 0.1.8 diff --git a/packages/in_app_purchase/example/lib/main.dart b/packages/in_app_purchase/example/lib/main.dart index 866f0a7d0..e64ee46fc 100644 --- a/packages/in_app_purchase/example/lib/main.dart +++ b/packages/in_app_purchase/example/lib/main.dart @@ -41,8 +41,7 @@ class _MyAppState extends State<_MyApp> { @override void initState() { - final Stream> purchaseUpdated = - _inAppPurchase.purchaseStream; + final Stream> purchaseUpdated = _inAppPurchase.purchaseStream; _subscription = purchaseUpdated.listen( (List purchaseDetailsList) { _listenToPurchaseUpdated(purchaseDetailsList); @@ -85,8 +84,9 @@ class _MyAppState extends State<_MyApp> { // The `identifiers` argument is not used on Tizen. // Use `InAppPurchaseTizenPlatformAddition.setRequestParameters` instead. - final ProductDetailsResponse productDetailResponse = await _inAppPurchase - .queryProductDetails({}); + final ProductDetailsResponse productDetailResponse = await _inAppPurchase.queryProductDetails( + {}, + ); if (productDetailResponse.error != null) { setState(() { _queryProductError = productDetailResponse.error!.message; @@ -130,7 +130,7 @@ class _MyAppState extends State<_MyApp> { @override Widget build(BuildContext context) { - final List stack = []; + final stack = []; if (_queryProductError == null) { stack.add( ListView( @@ -148,10 +148,7 @@ class _MyAppState extends State<_MyApp> { stack.add( const Stack( children: [ - Opacity( - opacity: 0.3, - child: ModalBarrier(dismissible: false, color: Colors.grey), - ), + Opacity(opacity: 0.3, child: ModalBarrier(dismissible: false, color: Colors.grey)), Center(child: CircularProgressIndicator()), ], ), @@ -173,15 +170,11 @@ class _MyAppState extends State<_MyApp> { final Widget storeHeader = ListTile( leading: Icon( _isAvailable ? Icons.check : Icons.block, - color: _isAvailable - ? Colors.green - : ThemeData.light().colorScheme.error, - ), - title: Text( - 'The store is ${_isAvailable ? 'available' : 'unavailable'}.', + color: _isAvailable ? Colors.green : ThemeData.light().colorScheme.error, ), + title: Text('The store is ${_isAvailable ? 'available' : 'unavailable'}.'), ); - final List children = [storeHeader]; + final children = [storeHeader]; if (!_isAvailable) { children.addAll([ @@ -203,17 +196,14 @@ class _MyAppState extends State<_MyApp> { Card _buildProductList() { if (_loading) { return const Card( - child: ListTile( - leading: CircularProgressIndicator(), - title: Text('Fetching products...'), - ), + child: ListTile(leading: CircularProgressIndicator(), title: Text('Fetching products...')), ); } if (!_isAvailable) { return const Card(); } - const ListTile productHeader = ListTile(title: Text('Products for Sale')); - final List productList = []; + const productHeader = ListTile(title: Text('Products for Sale')); + final productList = []; if (_notFoundIds.isNotEmpty) { productList.add( ListTile( @@ -239,13 +229,10 @@ class _MyAppState extends State<_MyApp> { foregroundColor: Colors.white, ), onPressed: () { - final PurchaseParam purchaseParam = PurchaseParam( - productDetails: productDetails, - ); + final purchaseParam = PurchaseParam(productDetails: productDetails); if (productDetails is SamsungCheckoutProductDetails) { - if (productDetails.itemDetails.itemType == - ItemType.consumable) { + if (productDetails.itemDetails.itemType == ItemType.consumable) { _inAppPurchase.buyConsumable( purchaseParam: purchaseParam, // ignore: avoid_redundant_argument_values @@ -262,11 +249,7 @@ class _MyAppState extends State<_MyApp> { }), ); - return Card( - child: Column( - children: [productHeader, const Divider()] + productList, - ), - ); + return Card(child: Column(children: [productHeader, const Divider()] + productList)); } Widget _buildRestoreButton() { @@ -326,10 +309,8 @@ class _MyAppState extends State<_MyApp> { // handle invalid purchase here if _verifyPurchase` failed. } - Future _listenToPurchaseUpdated( - List purchaseDetailsList, - ) async { - for (final PurchaseDetails purchaseDetails in purchaseDetailsList) { + Future _listenToPurchaseUpdated(List purchaseDetailsList) async { + for (final purchaseDetails in purchaseDetailsList) { if (purchaseDetails.status == PurchaseStatus.pending) { showPendingUI(); } else { diff --git a/packages/in_app_purchase/lib/src/billing_manager.dart b/packages/in_app_purchase/lib/src/billing_manager.dart index 0da84cb6d..ffe0d5c2c 100644 --- a/packages/in_app_purchase/lib/src/billing_manager.dart +++ b/packages/in_app_purchase/lib/src/billing_manager.dart @@ -53,9 +53,7 @@ class BillingManager { /// Calls /// [`BillingManager-getProductsList`](https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/billing-api.html#BillingManager-getProductsList) /// to retrieves the list of products registered on the Billing (DPI) server. - Future requestProducts( - List requestparameters, - ) async { + Future requestProducts(List requestparameters) async { final String countryCode = await _hostApi.getCountryCode(); final String checkValue = base64.encode( Hmac( @@ -63,7 +61,7 @@ class BillingManager { utf8.encode(_requestParameters.securityKey ?? ''), ).convert(utf8.encode((_requestParameters.appId) + countryCode)).bytes, ); - final ProductMessage product = ProductMessage( + final product = ProductMessage( appId: _requestParameters.appId, countryCode: countryCode, pageSize: _requestParameters.pageSize, @@ -76,9 +74,7 @@ class BillingManager { /// Calls /// [`BillingManager-getUserPurchaseList`](https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/billing-api.html#BillingManager-getUserPurchaseList) /// to retrieves the user's purchase list. - Future requestPurchases({ - String? applicationUserName, - }) async { + Future requestPurchases({String? applicationUserName}) async { final String customId = await _hostApi.getCustomId(); final String countryCode = await _hostApi.getCountryCode(); final String checkValue = base64.encode( @@ -95,7 +91,7 @@ class BillingManager { .bytes, ); - final PurchaseMessage purchase = PurchaseMessage( + final purchase = PurchaseMessage( appId: _requestParameters.appId, customId: customId, countryCode: countryCode, @@ -117,7 +113,7 @@ class BillingManager { required String orderCurrencyId, }) async { final String customId = await _hostApi.getCustomId(); - final OrderDetails orderDetails = OrderDetails( + final orderDetails = OrderDetails( orderItemId: orderItemId, orderTitle: orderTitle, orderTotal: orderTotal, @@ -125,10 +121,7 @@ class BillingManager { orderCustomId: customId, ); - final BuyInfoMessage buyInfo = BuyInfoMessage( - appId: _requestParameters.appId, - payDetials: orderDetails, - ); + final buyInfo = BuyInfoMessage(appId: _requestParameters.appId, payDetials: orderDetails); return _hostApi.buyItem(buyInfo); } @@ -137,12 +130,10 @@ class BillingManager { /// [`BillingManager-verifyInvoice`](https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/billing-api.html#BillingManager-verifyInvoice) /// to enables implementing the Samsung Checkout Client module within the application. /// Checks whether a purchase, corresponding to a specific "InvoiceID", was successful. - Future verifyInvoice({ - required String invoiceId, - }) async { + Future verifyInvoice({required String invoiceId}) async { final String customId = await _hostApi.getCustomId(); final String countryCode = await _hostApi.getCountryCode(); - final InvoiceMessage invoice = InvoiceMessage( + final invoice = InvoiceMessage( invoiceId: invoiceId, appId: _requestParameters.appId, customId: customId, @@ -386,31 +377,22 @@ class SamsungCheckoutPurchaseDetails extends PurchaseDetails { }); /// Generate a [SamsungCheckoutPurchaseDetails] object based on [PurchaseDetails] object. - factory SamsungCheckoutPurchaseDetails.fromPurchase( - InvoiceDetails invoiceDetails, - ) { - final SamsungCheckoutPurchaseDetails purchaseDetails = - SamsungCheckoutPurchaseDetails( - purchaseID: invoiceDetails.invoiceId, - productID: invoiceDetails.itemId, - verificationData: PurchaseVerificationData( - localVerificationData: invoiceDetails.invoiceId, - serverVerificationData: invoiceDetails.invoiceId, - source: kIAPSource, - ), - transactionDate: invoiceDetails.orderTime, - status: const PurchaseStateConverter().toPurchaseStatus( - invoiceDetails.cancelStatus, - ), - invoiceDetails: invoiceDetails, - ); + factory SamsungCheckoutPurchaseDetails.fromPurchase(InvoiceDetails invoiceDetails) { + final purchaseDetails = SamsungCheckoutPurchaseDetails( + purchaseID: invoiceDetails.invoiceId, + productID: invoiceDetails.itemId, + verificationData: PurchaseVerificationData( + localVerificationData: invoiceDetails.invoiceId, + serverVerificationData: invoiceDetails.invoiceId, + source: kIAPSource, + ), + transactionDate: invoiceDetails.orderTime, + status: const PurchaseStateConverter().toPurchaseStatus(invoiceDetails.cancelStatus), + invoiceDetails: invoiceDetails, + ); if (purchaseDetails.status == PurchaseStatus.error) { - purchaseDetails.error = IAPError( - source: kIAPSource, - code: kPurchaseErrorCode, - message: '', - ); + purchaseDetails.error = IAPError(source: kIAPSource, code: kPurchaseErrorCode, message: ''); } return purchaseDetails; diff --git a/packages/in_app_purchase/lib/src/in_app_purchase_tizen_platform.dart b/packages/in_app_purchase/lib/src/in_app_purchase_tizen_platform.dart index 596f83d09..7d94dc1af 100644 --- a/packages/in_app_purchase/lib/src/in_app_purchase_tizen_platform.dart +++ b/packages/in_app_purchase/lib/src/in_app_purchase_tizen_platform.dart @@ -29,22 +29,18 @@ class InAppPurchaseTizenPlatform extends InAppPurchasePlatform { static void register() { // Register the [InAppPurchaseTizenPlatformAddition] containing // Samsung Checkout-specific functionality. - InAppPurchasePlatformAddition.instance = InAppPurchaseTizenPlatformAddition( - billingManager, - ); + InAppPurchasePlatformAddition.instance = InAppPurchaseTizenPlatformAddition(billingManager); // Register the platform-specific implementation of the idiomatic // InAppPurchase API. InAppPurchasePlatform.instance = InAppPurchaseTizenPlatform(); } - static final StreamController> - _purchaseUpdatedController = + static final StreamController> _purchaseUpdatedController = StreamController>.broadcast(); @override - late final Stream> purchaseStream = - _purchaseUpdatedController.stream; + late final Stream> purchaseStream = _purchaseUpdatedController.stream; /// The [BillingManager] that's abstracted by Samsung Checkout. /// @@ -68,15 +64,15 @@ class InAppPurchaseTizenPlatform extends InAppPurchasePlatform { /// Converts `Map?` to the list of [ItemDetails]. List _getItemDetails(ProductsListApiResult response) { - final List itemDetails = []; + final itemDetails = []; for (final Map? detail in response.itemDetails) { - final int seq = detail!['Seq']! as int; - final String itemId = detail['ItemID']! as String; - final String itemTitle = detail['ItemTitle']! as String; - final String itemDesc = detail['ItemDesc']! as String; - final int itemType = detail['ItemType']! as int; - final num price = detail['Price']! as num; - final String currencyId = detail['CurrencyID']! as String; + final seq = detail!['Seq']! as int; + final itemId = detail['ItemID']! as String; + final itemTitle = detail['ItemTitle']! as String; + final itemDesc = detail['ItemDesc']! as String; + final itemType = detail['ItemType']! as int; + final price = detail['Price']! as num; + final currencyId = detail['CurrencyID']! as String; itemDetails.add( ItemDetails( @@ -95,9 +91,7 @@ class InAppPurchaseTizenPlatform extends InAppPurchasePlatform { /// Performs a network query for the details of products available. @override - Future queryProductDetails( - Set identifiers, - ) async { + Future queryProductDetails(Set identifiers) async { ProductsListApiResult response; PlatformException? exception; try { @@ -113,9 +107,8 @@ class InAppPurchaseTizenPlatform extends InAppPurchasePlatform { ); } - List productDetailsList = - []; - final List invalidMessage = []; + var productDetailsList = []; + final invalidMessage = []; if (response.cpStatus == '100000') { productDetailsList = _getItemDetails(response) @@ -128,42 +121,39 @@ class InAppPurchaseTizenPlatform extends InAppPurchasePlatform { invalidMessage.add(response.encode().toString()); } - final ProductDetailsResponse productDetailsResponse = - ProductDetailsResponse( - productDetails: productDetailsList, - notFoundIDs: invalidMessage, - error: exception == null - ? null - : IAPError( - source: kIAPSource, - code: exception.code, - message: exception.message ?? '', - details: exception.details, - ), - ); + final productDetailsResponse = ProductDetailsResponse( + productDetails: productDetailsList, + notFoundIDs: invalidMessage, + error: exception == null + ? null + : IAPError( + source: kIAPSource, + code: exception.code, + message: exception.message ?? '', + details: exception.details, + ), + ); return productDetailsResponse; } /// Converts `Map?` to the list of [InvoiceDetails]. - List _getInvoiceDetails( - GetUserPurchaseListAPIResult response, - ) { - final List invoiceDetails = []; + List _getInvoiceDetails(GetUserPurchaseListAPIResult response) { + final invoiceDetails = []; for (final Map? detail in response.invoiceDetails) { - final int seq = detail!['Seq']! as int; - final String invoiceId = detail['InvoiceID']! as String; - final String itemId = detail['ItemID']! as String; - final String itemTitle = detail['ItemTitle']! as String; - final int itemType = detail['ItemType']! as int; - final String orderTime = detail['OrderTime']! as String; - final int? period = detail['Period'] as int?; - final num price = detail['Price']! as num; - final String orderCurrencyId = detail['OrderCurrencyID']! as String; - final bool cancelStatus = detail['CancelStatus']! as bool; - final bool appliedStatus = detail['AppliedStatus']! as bool; - final String? appliedTime = detail['AppliedTime'] as String?; - final String? limitEndTime = detail['LimitEndTime'] as String?; - final String? remainTime = detail['RemainTime'] as String?; + final seq = detail!['Seq']! as int; + final invoiceId = detail['InvoiceID']! as String; + final itemId = detail['ItemID']! as String; + final itemTitle = detail['ItemTitle']! as String; + final itemType = detail['ItemType']! as int; + final orderTime = detail['OrderTime']! as String; + final period = detail['Period'] as int?; + final price = detail['Price']! as num; + final orderCurrencyId = detail['OrderCurrencyID']! as String; + final cancelStatus = detail['CancelStatus']! as bool; + final appliedStatus = detail['AppliedStatus']! as bool; + final appliedTime = detail['AppliedTime'] as String?; + final limitEndTime = detail['LimitEndTime'] as String?; + final remainTime = detail['RemainTime'] as String?; invoiceDetails.add( InvoiceDetails( @@ -204,8 +194,7 @@ class InAppPurchaseTizenPlatform extends InAppPurchasePlatform { } }) .map((InvoiceDetails purchaseWrapper) { - final SamsungCheckoutPurchaseDetails purchaseDetails = - SamsungCheckoutPurchaseDetails.fromPurchase(purchaseWrapper); + final purchaseDetails = SamsungCheckoutPurchaseDetails.fromPurchase(purchaseWrapper); purchaseDetails.status = PurchaseStatus.restored; return purchaseDetails; @@ -224,32 +213,25 @@ class InAppPurchaseTizenPlatform extends InAppPurchasePlatform { ); if (billingResultWrapper.payResult == 'SUCCESS') { - final String invoiceId = - billingResultWrapper.payDetails['InvoiceID'] ?? ''; + final String invoiceId = billingResultWrapper.payDetails['InvoiceID'] ?? ''; unawaited( billingManager .requestPurchases() .then((GetUserPurchaseListAPIResult responses) { - for (int i = 0; i < responses.invoiceDetails.length; i++) { + for (var i = 0; i < responses.invoiceDetails.length; i++) { if (_getInvoiceDetails(responses)[i].invoiceId == invoiceId) { - final List purchases = []; + final purchases = []; purchases.add( PurchaseDetails( purchaseID: _getInvoiceDetails(responses)[i].invoiceId, productID: _getInvoiceDetails(responses)[i].itemId, verificationData: PurchaseVerificationData( - localVerificationData: _getInvoiceDetails( - responses, - )[i].invoiceId, - serverVerificationData: _getInvoiceDetails( - responses, - )[i].invoiceId, + localVerificationData: _getInvoiceDetails(responses)[i].invoiceId, + serverVerificationData: _getInvoiceDetails(responses)[i].invoiceId, source: kIAPSource, ), - transactionDate: _getInvoiceDetails( - responses, - )[i].orderTime, + transactionDate: _getInvoiceDetails(responses)[i].orderTime, status: const PurchaseStateConverter().toPurchaseStatus( _getInvoiceDetails(responses)[i].cancelStatus, ), @@ -272,10 +254,7 @@ class InAppPurchaseTizenPlatform extends InAppPurchasePlatform { } @override - Future buyConsumable({ - required PurchaseParam purchaseParam, - bool autoConsume = true, - }) { + Future buyConsumable({required PurchaseParam purchaseParam, bool autoConsume = true}) { assert(autoConsume, 'On Tizen, we should always auto consume'); return buyNonConsumable(purchaseParam: purchaseParam); } diff --git a/packages/in_app_purchase/lib/src/in_app_purchase_tizen_platform_addition.dart b/packages/in_app_purchase/lib/src/in_app_purchase_tizen_platform_addition.dart index 4937672f2..7d5046967 100644 --- a/packages/in_app_purchase/lib/src/in_app_purchase_tizen_platform_addition.dart +++ b/packages/in_app_purchase/lib/src/in_app_purchase_tizen_platform_addition.dart @@ -36,7 +36,7 @@ class InAppPurchaseTizenPlatformAddition extends InAppPurchasePlatformAddition { required int pageNum, String? securityKey, }) { - final RequestParameters requestParameters = RequestParameters(); + final requestParameters = RequestParameters(); requestParameters.appId = appId; requestParameters.pageSize = pageSize; requestParameters.pageNum = pageNum; @@ -45,9 +45,7 @@ class InAppPurchaseTizenPlatformAddition extends InAppPurchasePlatformAddition { } /// Check whether a purchase, corresponding to the requested "InvoiceID", was successful. - Future verifyPurchase({ - required PurchaseDetails purchaseDetails, - }) async { + Future verifyPurchase({required PurchaseDetails purchaseDetails}) async { VerifyInvoiceAPIResult verifyPurchaseResult; try { verifyPurchaseResult = await _billingManager.verifyInvoice( diff --git a/packages/in_app_purchase/lib/src/messages.g.dart b/packages/in_app_purchase/lib/src/messages.g.dart index 50bca378e..65a263b7a 100644 --- a/packages/in_app_purchase/lib/src/messages.g.dart +++ b/packages/in_app_purchase/lib/src/messages.g.dart @@ -58,8 +58,7 @@ class ProductsListApiResult { cpResult: result[1] as String?, totalCount: result[2]! as int, checkValue: result[3]! as String, - itemDetails: (result[4] as List?)! - .cast?>(), + itemDetails: (result[4] as List?)!.cast?>(), ); } } @@ -96,13 +95,7 @@ class GetUserPurchaseListAPIResult { List?> invoiceDetails; Object encode() { - return [ - cpStatus, - cpResult, - totalCount, - checkValue, - invoiceDetails, - ]; + return [cpStatus, cpResult, totalCount, checkValue, invoiceDetails]; } static GetUserPurchaseListAPIResult decode(Object result) { @@ -112,8 +105,7 @@ class GetUserPurchaseListAPIResult { cpResult: result[1] as String?, totalCount: result[2]! as int, checkValue: result[3]! as String, - invoiceDetails: (result[4] as List?)! - .cast?>(), + invoiceDetails: (result[4] as List?)!.cast?>(), ); } } @@ -187,11 +179,7 @@ class VerifyInvoiceAPIResult { /// Defines a dictionary for data returned by the IsServiceAvailable API. /// This only can be used in [BillingManager.isAvailable]. class ServiceAvailableAPIResult { - ServiceAvailableAPIResult({ - required this.status, - required this.result, - required this.serviceYn, - }); + ServiceAvailableAPIResult({required this.status, required this.result, required this.serviceYn}); /// The result code of connecting to billing server. /// Returns "100000" on success and other codes on failure. @@ -322,13 +310,7 @@ class OrderDetails { String orderCustomId; Object encode() { - return [ - orderItemId, - orderTitle, - orderTotal, - orderCurrencyId, - orderCustomId, - ]; + return [orderItemId, orderTitle, orderTotal, orderCurrencyId, orderCustomId]; } static OrderDetails decode(Object result) { @@ -358,10 +340,7 @@ class BuyInfoMessage { static BuyInfoMessage decode(Object result) { result as List; - return BuyInfoMessage( - appId: result[0]! as String, - payDetials: result[1]! as OrderDetails, - ); + return BuyInfoMessage(appId: result[0]! as String, payDetials: result[1]! as OrderDetails); } } @@ -475,13 +454,11 @@ class InAppPurchaseApi { /// Constructor for [InAppPurchaseApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. - InAppPurchaseApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + InAppPurchaseApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -492,12 +469,11 @@ class InAppPurchaseApi { Future getProductsList(ProductMessage product) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_tizen.InAppPurchaseApi.getProductsList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([product]) as List?; if (pigeonVar_replyList == null) { @@ -519,17 +495,14 @@ class InAppPurchaseApi { } /// Retrieves the user's purchase list. - Future getUserPurchaseList( - PurchaseMessage purchase, - ) async { + Future getUserPurchaseList(PurchaseMessage purchase) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_tizen.InAppPurchaseApi.getUserPurchaseList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([purchase]) as List?; if (pigeonVar_replyList == null) { @@ -555,12 +528,11 @@ class InAppPurchaseApi { Future buyItem(BuyInfoMessage buyInfo) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_tizen.InAppPurchaseApi.buyItem$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([buyInfo]) as List?; if (pigeonVar_replyList == null) { @@ -585,12 +557,11 @@ class InAppPurchaseApi { Future verifyInvoice(InvoiceMessage invoice) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_tizen.InAppPurchaseApi.verifyInvoice$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final List? pigeonVar_replyList = await pigeonVar_channel.send([invoice]) as List?; if (pigeonVar_replyList == null) { @@ -615,14 +586,12 @@ class InAppPurchaseApi { Future isServiceAvailable() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_tizen.InAppPurchaseApi.isServiceAvailable$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = - await pigeonVar_channel.send(null) as List?; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -644,14 +613,12 @@ class InAppPurchaseApi { Future getCustomId() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_tizen.InAppPurchaseApi.getCustomId$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = - await pigeonVar_channel.send(null) as List?; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -673,14 +640,12 @@ class InAppPurchaseApi { Future getCountryCode() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.in_app_purchase_tizen.InAppPurchaseApi.getCountryCode$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = - await pigeonVar_channel.send(null) as List?; + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final List? pigeonVar_replyList = await pigeonVar_channel.send(null) as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/integration_test/CHANGELOG.md b/packages/integration_test/CHANGELOG.md index c94ac14d2..0eaf93421 100644 --- a/packages/integration_test/CHANGELOG.md +++ b/packages/integration_test/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 2.0.4 * Update the repository URL to use the `main` branch. diff --git a/packages/integration_test/example/integration_test/example_test.dart b/packages/integration_test/example/integration_test/example_test.dart index a9591a3c5..13d729eb2 100644 --- a/packages/integration_test/example/integration_test/example_test.dart +++ b/packages/integration_test/example/integration_test/example_test.dart @@ -34,8 +34,7 @@ void main() { expect( find.byWidgetPredicate( (Widget widget) => - widget is Text && - widget.data!.startsWith('Platform: ${Platform.operatingSystem}'), + widget is Text && widget.data!.startsWith('Platform: ${Platform.operatingSystem}'), ), findsOneWidget, ); diff --git a/packages/messageport/CHANGELOG.md b/packages/messageport/CHANGELOG.md index e6582e31b..5ca9f2704 100644 --- a/packages/messageport/CHANGELOG.md +++ b/packages/messageport/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 0.3.3 * Update the repository URL to use the `main` branch. diff --git a/packages/messageport/example/integration_test/messageport_test.dart b/packages/messageport/example/integration_test/messageport_test.dart index 51c1ef698..b452762d6 100644 --- a/packages/messageport/example/integration_test/messageport_test.dart +++ b/packages/messageport/example/integration_test/messageport_test.dart @@ -73,7 +73,7 @@ void main() { test('Send simple message', () async { final LocalPort localPort = await LocalPort.create(kTestPort); - final Completer completer = Completer(); + final completer = Completer(); localPort.register((dynamic message, [RemotePort? remotePort]) { expect(remotePort, isNull); completer.complete(message); @@ -90,7 +90,7 @@ void main() { test('Send message with local port', () async { final LocalPort localPort = await LocalPort.create(kTestPort); - final Completer> completer = Completer>(); + final completer = Completer>(); localPort.register((dynamic message, [RemotePort? remotePort]) { if (!completer.isCompleted) { completer.complete([message, remotePort]); @@ -101,8 +101,8 @@ void main() { await port.sendWithLocalPort('Test message 2', localPort); final List value = await completer.future; - final String message = value[0] as String; - final RemotePort? remotePort = value[1] as RemotePort?; + final message = value[0] as String; + final remotePort = value[1] as RemotePort?; expect(message, equals('Test message 2')); expect(remotePort?.remoteAppId, equals(kTestAppId)); expect(remotePort?.portName, equals(kTestPort)); @@ -131,8 +131,7 @@ void main() { localPort.register((dynamic message, [RemotePort? remotePort]) {}); expect( - () => - localPort.register((dynamic message, [RemotePort? remotePort]) {}), + () => localPort.register((dynamic message, [RemotePort? remotePort]) {}), throwsException, ); }, timeout: const Timeout(Duration(seconds: 5))); @@ -178,7 +177,7 @@ void main() { Future checkForMessage(T message) async { await remotePort.send(message); - final T receivedMessage = await completer.future as T; + final receivedMessage = await completer.future as T; expect(receivedMessage, equals(message)); } @@ -187,42 +186,42 @@ void main() { }, timeout: const Timeout(Duration(seconds: 5))); test('bool', () async { - const bool value = true; + const value = true; await checkForMessage(value); }, timeout: const Timeout(Duration(seconds: 5))); test('int', () async { - const int value = 834; + const value = 834; await checkForMessage(value); }, timeout: const Timeout(Duration(seconds: 5))); test('double', () async { - const double value = 12.847; + const value = 12.847; await checkForMessage(value); }, timeout: const Timeout(Duration(seconds: 5))); test('string', () async { - const String value = 'Short string message'; + const value = 'Short string message'; await checkForMessage(value); }, timeout: const Timeout(Duration(seconds: 5))); test('list', () async { - final List value = [1, 5, 8, 12, 0, 2]; + final value = [1, 5, 8, 12, 0, 2]; await checkForMessage>(value); }, timeout: const Timeout(Duration(seconds: 5))); test('map', () async { - final Map value = {'a': 5, 'b': 12}; + final value = {'a': 5, 'b': 12}; await checkForMessage>(value); }, timeout: const Timeout(Duration(seconds: 5))); test('empty string', () async { - const String value = ''; + const value = ''; await checkForMessage(value); }, timeout: const Timeout(Duration(seconds: 5))); test('nested collection', () async { - final Map value = { + final value = { 'numbers': [1, 2, 3], 'nested': {'key': 'value'}, }; diff --git a/packages/messageport/example/lib/main.dart b/packages/messageport/example/lib/main.dart index 84f11fecc..9acda5877 100644 --- a/packages/messageport/example/lib/main.dart +++ b/packages/messageport/example/lib/main.dart @@ -158,7 +158,7 @@ class _MyAppState extends State { final List _logs = []; void _log(String log) { - final String date = '${DateTime.now().hour.toString().padLeft(2, '0')}:' + final date = '${DateTime.now().hour.toString().padLeft(2, '0')}:' '${DateTime.now().minute.toString().padLeft(2, '0')}:' '${DateTime.now().second.toString().padLeft(2, '0')}.' '${DateTime.now().millisecond.toString().padLeft(3, '0')}'; diff --git a/packages/messageport/lib/messageport_tizen.dart b/packages/messageport/lib/messageport_tizen.dart index a6f3b173a..93fd6feb3 100644 --- a/packages/messageport/lib/messageport_tizen.dart +++ b/packages/messageport/lib/messageport_tizen.dart @@ -11,8 +11,7 @@ MessagePortManager _manager = MessagePortManager(); /// Called when a message is received on message port. /// /// This is used by [LocalPort.register]. -typedef OnMessageReceived = void Function(dynamic message, - [RemotePort? remotePort]); +typedef OnMessageReceived = void Function(dynamic message, [RemotePort? remotePort]); /// Local message port for receiving messages. class LocalPort { @@ -52,9 +51,9 @@ class LocalPort { final Map map = event; final dynamic message = map['message']; if (map.containsKey('remotePort')) { - final String remoteAppId = map['remoteAppId'] as String; - final String remotePort = map['remotePort'] as String; - final bool trusted = map['trusted'] as bool; + final remoteAppId = map['remoteAppId'] as String; + final remotePort = map['remotePort'] as String; + final trusted = map['trusted'] as bool; onMessage(message, RemotePort._(remoteAppId, remotePort, trusted)); } else { onMessage(message); diff --git a/packages/messageport/lib/src/messageport_manager.dart b/packages/messageport/lib/src/messageport_manager.dart index ef49e72d2..bcb4985e3 100644 --- a/packages/messageport/lib/src/messageport_manager.dart +++ b/packages/messageport/lib/src/messageport_manager.dart @@ -16,11 +16,10 @@ class MessagePortManager { MessagePortManager(); final Map> _localPorts = >{}; - final Map> _trustedLocalPorts = - >{}; + final Map> _trustedLocalPorts = >{}; Future createLocalPort(String portName, bool trusted) async { - final Map args = {}; + final args = {}; args['portName'] = portName; args['trusted'] = trusted; return _channel.invokeMethod('createLocal', args); @@ -31,7 +30,7 @@ class MessagePortManager { String portName, bool trusted, ) async { - final Map args = {}; + final args = {}; args['remoteAppId'] = remoteAppId; args['portName'] = portName; args['trusted'] = trusted; @@ -43,7 +42,7 @@ class MessagePortManager { } Future send(RemotePort remotePort, dynamic message) async { - final Map args = {}; + final args = {}; args['trusted'] = remotePort.trusted; args['remoteAppId'] = remotePort.remoteAppId; args['portName'] = remotePort.portName; @@ -56,7 +55,7 @@ class MessagePortManager { LocalPort localPort, dynamic message, ) async { - final Map args = {}; + final args = {}; args['trusted'] = remotePort.trusted; args['remoteAppId'] = remotePort.remoteAppId; args['portName'] = remotePort.portName; @@ -69,16 +68,15 @@ class MessagePortManager { Stream registerLocalPort(LocalPort localPort) { if (localPort.trusted) { if (!_trustedLocalPorts.containsKey(localPort.portName)) { - final EventChannel eventChannel = EventChannel( + final eventChannel = EventChannel( 'tizen/messageport/${localPort.portName}_trusted', ); - _trustedLocalPorts[localPort.portName] = - eventChannel.receiveBroadcastStream(); + _trustedLocalPorts[localPort.portName] = eventChannel.receiveBroadcastStream(); } return _trustedLocalPorts[localPort.portName]!; } if (!_localPorts.containsKey(localPort.portName)) { - final EventChannel eventChannel = EventChannel( + final eventChannel = EventChannel( 'tizen/messageport/${localPort.portName}', ); _localPorts[localPort.portName] = eventChannel.receiveBroadcastStream(); diff --git a/packages/path_provider/CHANGELOG.md b/packages/path_provider/CHANGELOG.md index 03e40cdc0..93672142f 100644 --- a/packages/path_provider/CHANGELOG.md +++ b/packages/path_provider/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 2.3.3 * Update path_provider to 2.1.6. diff --git a/packages/path_provider/example/integration_test/path_provider_test.dart b/packages/path_provider/example/integration_test/path_provider_test.dart index 86682d7e0..7c355f741 100644 --- a/packages/path_provider/example/integration_test/path_provider_test.dart +++ b/packages/path_provider/example/integration_test/path_provider_test.dart @@ -78,7 +78,7 @@ void main() { } }); - final List allDirs = [ + final allDirs = [ null, StorageDirectory.music, StorageDirectory.podcasts, @@ -89,14 +89,13 @@ void main() { StorageDirectory.movies, ]; - for (final StorageDirectory? type in allDirs) { + for (final type in allDirs) { test('getExternalStorageDirectories (type: $type)', () async { if (Platform.isIOS) { final Future?> result = getExternalStorageDirectories(); await expectLater(result, throwsA(isInstanceOf())); } else if (Platform.isAndroid) { - final List? directories = - await getExternalStorageDirectories(type: type); + final List? directories = await getExternalStorageDirectories(type: type); expect(directories, isNotNull); for (final Directory result in directories!) { _verifySampleFile(result, '$type'); @@ -113,7 +112,7 @@ void _verifySampleFile(Directory? directory, String name) { if (directory == null) { return; } - final File file = File('${directory.path}/$name'); + final file = File('${directory.path}/$name'); if (file.existsSync()) { file.deleteSync(); @@ -125,10 +124,7 @@ void _verifySampleFile(Directory? directory, String name) { // This check intentionally avoids using Directory.listSync on Android due to // https://github.com/dart-lang/sdk/issues/54287. if (Platform.isAndroid) { - expect( - Process.runSync('ls', [directory.path]).stdout, - contains(name), - ); + expect(Process.runSync('ls', [directory.path]).stdout, contains(name)); } else { expect(directory.listSync(), isNotEmpty); } diff --git a/packages/path_provider/example/lib/main.dart b/packages/path_provider/example/lib/main.dart index 89e9410df..ab58ab01c 100644 --- a/packages/path_provider/example/lib/main.dart +++ b/packages/path_provider/example/lib/main.dart @@ -51,11 +51,8 @@ class _MyHomePageState extends State { }); } - Widget _buildDirectory( - BuildContext context, - AsyncSnapshot snapshot, - ) { - Text text = const Text(''); + Widget _buildDirectory(BuildContext context, AsyncSnapshot snapshot) { + var text = const Text(''); if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { text = Text('Error: ${snapshot.error}'); @@ -68,18 +65,13 @@ class _MyHomePageState extends State { return Padding(padding: const EdgeInsets.all(16.0), child: text); } - Widget _buildDirectories( - BuildContext context, - AsyncSnapshot?> snapshot, - ) { - Text text = const Text(''); + Widget _buildDirectories(BuildContext context, AsyncSnapshot?> snapshot) { + var text = const Text(''); if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { text = Text('Error: ${snapshot.error}'); } else if (snapshot.hasData) { - final String combined = snapshot.data! - .map((Directory d) => d.path) - .join(', '); + final String combined = snapshot.data!.map((Directory d) => d.path).join(', '); text = Text('paths: $combined'); } else { text = const Text('path unavailable'); @@ -152,10 +144,7 @@ class _MyHomePageState extends State { child: const Text('Get Temporary Directory'), ), ), - FutureBuilder( - future: _tempDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _tempDirectory, builder: _buildDirectory), ], ), Column( @@ -167,10 +156,7 @@ class _MyHomePageState extends State { child: const Text('Get Application Documents Directory'), ), ), - FutureBuilder( - future: _appDocumentsDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _appDocumentsDirectory, builder: _buildDirectory), ], ), Column( @@ -182,10 +168,7 @@ class _MyHomePageState extends State { child: const Text('Get Application Support Directory'), ), ), - FutureBuilder( - future: _appSupportDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _appSupportDirectory, builder: _buildDirectory), ], ), Column( @@ -193,9 +176,7 @@ class _MyHomePageState extends State { Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( - onPressed: Platform.isAndroid - ? null - : _requestAppLibraryDirectory, + onPressed: Platform.isAndroid ? null : _requestAppLibraryDirectory, child: Text( Platform.isAndroid ? 'Application Library Directory unavailable' @@ -203,10 +184,7 @@ class _MyHomePageState extends State { ), ), ), - FutureBuilder( - future: _appLibraryDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _appLibraryDirectory, builder: _buildDirectory), ], ), Column( @@ -218,10 +196,7 @@ class _MyHomePageState extends State { child: const Text('Get Application Cache Directory'), ), ), - FutureBuilder( - future: _appCacheDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _appCacheDirectory, builder: _buildDirectory), ], ), Column( @@ -229,9 +204,7 @@ class _MyHomePageState extends State { Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( - onPressed: !Platform.isAndroid - ? null - : _requestExternalStorageDirectory, + onPressed: !Platform.isAndroid ? null : _requestExternalStorageDirectory, child: Text( !Platform.isAndroid ? 'External storage is unavailable' @@ -253,9 +226,7 @@ class _MyHomePageState extends State { onPressed: !Platform.isAndroid ? null : () { - _requestExternalStorageDirectories( - StorageDirectory.music, - ); + _requestExternalStorageDirectories(StorageDirectory.music); }, child: Text( !Platform.isAndroid @@ -275,9 +246,7 @@ class _MyHomePageState extends State { Padding( padding: const EdgeInsets.all(16.0), child: ElevatedButton( - onPressed: !Platform.isAndroid - ? null - : _requestExternalCacheDirectories, + onPressed: !Platform.isAndroid ? null : _requestExternalCacheDirectories, child: Text( !Platform.isAndroid ? 'External directories are unavailable' @@ -306,10 +275,7 @@ class _MyHomePageState extends State { ), ), ), - FutureBuilder( - future: _downloadsDirectory, - builder: _buildDirectory, - ), + FutureBuilder(future: _downloadsDirectory, builder: _buildDirectory), ], ), ], diff --git a/packages/path_provider/lib/path_provider_tizen.dart b/packages/path_provider/lib/path_provider_tizen.dart index b4fd8d8bd..50562771a 100644 --- a/packages/path_provider/lib/path_provider_tizen.dart +++ b/packages/path_provider/lib/path_provider_tizen.dart @@ -20,8 +20,7 @@ class PathProviderPlugin extends PathProviderPlatform { Future getTemporaryPath() async => appCommon.getCachePath(); @override - Future getApplicationDocumentsPath() async => - appCommon.getDataPath(); + Future getApplicationDocumentsPath() async => appCommon.getDataPath(); @override Future getApplicationCachePath() async => appCommon.getCachePath(); @@ -30,8 +29,7 @@ class PathProviderPlugin extends PathProviderPlatform { Future getApplicationSupportPath() async => appCommon.getDataPath(); @override - Future getExternalStoragePath() async => - appCommon.getExternalDataPath(); + Future getExternalStoragePath() async => appCommon.getExternalDataPath(); @override Future?> getExternalCachePaths() async { @@ -42,18 +40,14 @@ class PathProviderPlugin extends PathProviderPlatform { @override Future getDownloadsPath() async { try { - return await storage.getDirectory( - storage_directory_e.STORAGE_DIRECTORY_DOWNLOADS, - ); + return await storage.getDirectory(storage_directory_e.STORAGE_DIRECTORY_DOWNLOADS); } catch (_) { return null; } } @override - Future?> getExternalStoragePaths({ - StorageDirectory? type, - }) async { + Future?> getExternalStoragePaths({StorageDirectory? type}) async { int dirType; switch (type) { case StorageDirectory.music: diff --git a/packages/shared_preferences/CHANGELOG.md b/packages/shared_preferences/CHANGELOG.md index 67cd1856d..3e1b5b98e 100644 --- a/packages/shared_preferences/CHANGELOG.md +++ b/packages/shared_preferences/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 2.3.5 * Add an `implements` entry to the pubspec to improve discoverability on pub.dev. diff --git a/packages/shared_preferences/example/integration_test/shared_preferences_test.dart b/packages/shared_preferences/example/integration_test/shared_preferences_test.dart index 56ed219a7..eb13d19cc 100644 --- a/packages/shared_preferences/example/integration_test/shared_preferences_test.dart +++ b/packages/shared_preferences/example/integration_test/shared_preferences_test.dart @@ -23,11 +23,11 @@ const String migrationCompletedKey = 'migrationCompleted'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); - const String testString2 = 'goodbye world'; - const bool testBool2 = false; - const int testInt2 = 1337; - const double testDouble2 = 2.71828; - const List testList2 = ['baz', 'qux']; + const testString2 = 'goodbye world'; + const testBool2 = false; + const testInt2 = 1337; + const testDouble2 = 2.71828; + const testList2 = ['baz', 'qux']; group('shared_preferences', () { late SharedPreferences preferences; @@ -64,7 +64,7 @@ void main() { }); test('removing', () async { - const String key = 'testKey'; + const key = 'testKey'; await preferences.setString(key, testString); await preferences.remove(key); expect(preferences.get('testKey'), isNull); @@ -85,9 +85,9 @@ void main() { }); test('simultaneous writes', () async { - final List> writes = >[]; - const int writeCount = 100; - for (int i = 1; i <= writeCount; i++) { + final writes = >[]; + const writeCount = 100; + for (var i = 1; i <= writeCount; i++) { writes.add(preferences.setInt('int', i)); } final List result = await Future.wait(writes, eagerError: true); @@ -142,12 +142,12 @@ void main() { }); test('allowList only gets allowed items', () async { - const String allowedString = 'stringKey'; - const String allowedBool = 'boolKey'; - const String notAllowedDouble = 'doubleKey'; - const String resultString = 'resultString'; + const allowedString = 'stringKey'; + const allowedBool = 'boolKey'; + const notAllowedDouble = 'doubleKey'; + const resultString = 'resultString'; - const Set allowList = {allowedString, allowedBool}; + const allowList = {allowedString, allowedBool}; SharedPreferences.resetStatic(); SharedPreferences.setPrefix('', allowList: allowList); @@ -172,21 +172,21 @@ void main() { }); group('shared_preferences_async', () { - const String stringKey = 'testString'; - const String boolKey = 'testBool'; - const String intKey = 'testInt'; - const String doubleKey = 'testDouble'; - const String listKey = 'testList'; - - const String testString = 'hello world'; - const bool testBool = true; - const int testInt = 42; - const double testDouble = 3.14159; - const List testList = ['foo', 'bar']; + const stringKey = 'testString'; + const boolKey = 'testBool'; + const intKey = 'testInt'; + const doubleKey = 'testDouble'; + const listKey = 'testList'; + + const testString = 'hello world'; + const testBool = true; + const testInt = 42; + const testDouble = 3.14159; + const testList = ['foo', 'bar']; group('Async', () { Future getPreferences() async { - final SharedPreferencesAsync preferences = SharedPreferencesAsync(); + final preferences = SharedPreferencesAsync(); await preferences.clear(); return preferences; } @@ -315,7 +315,7 @@ void main() { test('containsKey', () async { final SharedPreferencesAsync preferences = await getPreferences(); - const String key = 'testKey'; + const key = 'testKey'; expect(false, await preferences.containsKey(key)); @@ -419,11 +419,9 @@ void main() { }); group('withCache', () { - Future<(SharedPreferencesWithCache, Map)> - getPreferences() async { - final Map cache = {}; - final SharedPreferencesWithCache preferences = - await SharedPreferencesWithCache.create( + Future<(SharedPreferencesWithCache, Map)> getPreferences() async { + final cache = {}; + final SharedPreferencesWithCache preferences = await SharedPreferencesWithCache.create( cache: cache, cacheOptions: const SharedPreferencesWithCacheOptions(), ); @@ -432,40 +430,35 @@ void main() { } test('set and get String', () async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setString(stringKey, testString); expect(preferences.getString(stringKey), testString); }); test('set and get bool', () async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setBool(boolKey, testBool); expect(preferences.getBool(boolKey), testBool); }); test('set and get int', () async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setInt(intKey, testInt); expect(preferences.getInt(intKey), testInt); }); test('set and get double', () async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setDouble(doubleKey, testDouble); expect(preferences.getDouble(doubleKey), testDouble); }); test('set and get StringList', () async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setStringList(listKey, testList); expect(preferences.getStringList(listKey), testList); @@ -488,9 +481,8 @@ void main() { }); test('containsKey', () async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); - const String key = 'testKey'; + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); + const key = 'testKey'; expect(false, preferences.containsKey(key)); @@ -499,8 +491,7 @@ void main() { }); test('getKeys', () async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await Future.wait(>[ preferences.setString(stringKey, testString), preferences.setBool(boolKey, testBool), @@ -520,8 +511,7 @@ void main() { }); test('clear', () async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await Future.wait(>[ preferences.setString(stringKey, testString), preferences.setBool(boolKey, testBool), @@ -539,11 +529,9 @@ void main() { }); group('withCache with filter', () { - Future<(SharedPreferencesWithCache, Map)> - getPreferences() async { - final Map cache = {}; - final SharedPreferencesWithCache preferences = - await SharedPreferencesWithCache.create( + Future<(SharedPreferencesWithCache, Map)> getPreferences() async { + final cache = {}; + final SharedPreferencesWithCache preferences = await SharedPreferencesWithCache.create( cache: cache, cacheOptions: const SharedPreferencesWithCacheOptions( allowList: { @@ -562,9 +550,8 @@ void main() { test( 'throws ArgumentError if key is not included in filter', () async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); - const String key = 'testKey'; + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); + const key = 'testKey'; expect( () async => preferences.setString(key, 'test'), @@ -574,40 +561,35 @@ void main() { ); test('set and get String', () async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setString(stringKey, testString); expect(preferences.getString(stringKey), testString); }); test('set and get bool', () async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setBool(boolKey, testBool); expect(preferences.getBool(boolKey), testBool); }); test('set and get int', () async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setInt(intKey, testInt); expect(preferences.getInt(intKey), testInt); }); test('set and get double', () async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setDouble(doubleKey, testDouble); expect(preferences.getDouble(doubleKey), testDouble); }); test('set and get StringList', () async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await preferences.setStringList(listKey, testList); expect(preferences.getStringList(listKey), testList); @@ -618,7 +600,7 @@ void main() { SharedPreferencesWithCache preferences, Map cache, ) = await getPreferences(); - final List listObject = ['one', 'two']; + final listObject = ['one', 'two']; cache[listKey] = listObject; expect(preferences.getStringList(listKey), listObject); }); @@ -640,8 +622,7 @@ void main() { }); test('containsKey', () async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); expect(false, preferences.containsKey(stringKey)); @@ -650,8 +631,7 @@ void main() { }); test('getKeys', () async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await Future.wait(>[ preferences.setString(stringKey, testString), preferences.setBool(boolKey, testBool), @@ -671,8 +651,7 @@ void main() { }); test('clear', () async { - final (SharedPreferencesWithCache preferences, _) = - await getPreferences(); + final (SharedPreferencesWithCache preferences, _) = await getPreferences(); await Future.wait(>[ preferences.setString(stringKey, testString), preferences.setBool(boolKey, testBool), @@ -709,7 +688,7 @@ void main() { group('SharedPreferences with setPrefix and allowList', () { runAllGroups(() { - final Set allowList = { + final allowList = { 'prefix.$boolKey', 'prefix.$intKey', 'prefix.$doubleKey', @@ -745,8 +724,7 @@ void runTests( String? stringValue = testString, bool keysAndNamesCollide = false, }) { - const SharedPreferencesOptions sharedPreferencesAsyncOptions = - SharedPreferencesOptions(); + const sharedPreferencesAsyncOptions = SharedPreferencesOptions(); setUp(() async { // Configure and populate the source legacy shared preferences. @@ -774,7 +752,7 @@ void runTests( migrationCompletedKey: migrationCompletedKey, ); - final SharedPreferencesAsync asyncPreferences = SharedPreferencesAsync(); + final asyncPreferences = SharedPreferencesAsync(); expect(await asyncPreferences.getBool(boolKey), testBool); expect(await asyncPreferences.getInt(intKey), testInt); @@ -791,7 +769,7 @@ void runTests( migrationCompletedKey: migrationCompletedKey, ); - final SharedPreferencesAsync asyncPreferences = SharedPreferencesAsync(); + final asyncPreferences = SharedPreferencesAsync(); expect(await asyncPreferences.getBool(migrationCompletedKey), true); }); @@ -799,15 +777,14 @@ void runTests( test( 're-running migration tool does not overwrite data', () async { - final SharedPreferences preferences = - await SharedPreferences.getInstance(); + final SharedPreferences preferences = await SharedPreferences.getInstance(); await migrateLegacySharedPreferencesToSharedPreferencesAsyncIfNecessary( legacySharedPreferencesInstance: preferences, sharedPreferencesAsyncOptions: sharedPreferencesAsyncOptions, migrationCompletedKey: migrationCompletedKey, ); - final SharedPreferencesAsync asyncPreferences = SharedPreferencesAsync(); + final asyncPreferences = SharedPreferencesAsync(); await preferences.setInt(intKey, -0); await migrateLegacySharedPreferencesToSharedPreferencesAsyncIfNecessary( legacySharedPreferencesInstance: preferences, diff --git a/packages/shared_preferences/example/lib/main.dart b/packages/shared_preferences/example/lib/main.dart index f723ea842..2c9ceff5f 100644 --- a/packages/shared_preferences/example/lib/main.dart +++ b/packages/shared_preferences/example/lib/main.dart @@ -36,8 +36,7 @@ class SharedPreferencesDemo extends StatefulWidget { } class SharedPreferencesDemoState extends State { - final Future _prefs = - SharedPreferencesWithCache.create( + final Future _prefs = SharedPreferencesWithCache.create( cacheOptions: const SharedPreferencesWithCacheOptions( // This cache will only accept the key 'counter'. allowList: {'counter'}, @@ -64,7 +63,7 @@ class SharedPreferencesDemoState extends State { /// Gets external button presses that could occur in another instance, thread, /// or via some native system. Future _getExternalCounter() async { - final SharedPreferencesAsync prefs = SharedPreferencesAsync(); + final prefs = SharedPreferencesAsync(); final int externalCounter = (await prefs.getInt('externalCounter')) ?? 0; setState(() { _externalCounter = externalCounter; @@ -73,8 +72,7 @@ class SharedPreferencesDemoState extends State { Future _migratePreferences() async { // #docregion migrate - const SharedPreferencesOptions sharedPreferencesOptions = - SharedPreferencesOptions(); + const sharedPreferencesOptions = SharedPreferencesOptions(); final SharedPreferences prefs = await SharedPreferences.getInstance(); await migrateLegacySharedPreferencesToSharedPreferencesAsyncIfNecessary( legacySharedPreferencesInstance: prefs, diff --git a/packages/shared_preferences/lib/src/shared_preferences_async_tizen.dart b/packages/shared_preferences/lib/src/shared_preferences_async_tizen.dart index ea2ef5e54..0b96baa3f 100644 --- a/packages/shared_preferences/lib/src/shared_preferences_async_tizen.dart +++ b/packages/shared_preferences/lib/src/shared_preferences_async_tizen.dart @@ -65,9 +65,7 @@ base class SharedPreferencesAsyncTizen extends SharedPreferencesAsyncPlatform { } String _joinStringList(List list) { - return list.isEmpty - ? _separator - : _separator + list.join(_separator) + _separator; + return list.isEmpty ? _separator : _separator + list.join(_separator) + _separator; } @override @@ -188,7 +186,7 @@ base class SharedPreferencesAsyncTizen extends SharedPreferencesAsyncPlatform { ) async { final PreferencesFilters filter = parameters.filter; - List keyList = []; + var keyList = []; await getKeys( GetPreferencesParameters(filter: parameters.filter), options, @@ -196,7 +194,7 @@ base class SharedPreferencesAsyncTizen extends SharedPreferencesAsyncPlatform { keyList = keys.toList(); }); - for (final String key in keyList) { + for (final key in keyList) { if (filter.allowList == null || filter.allowList!.contains(key)) { if (!(await _remove(key))) { return; @@ -207,8 +205,7 @@ base class SharedPreferencesAsyncTizen extends SharedPreferencesAsyncPlatform { Future _remove(String key) async { return using((Arena arena) { - final bool ret = - tizen.preference_remove(key.toNativeChar(allocator: arena)) == 0; + final ret = tizen.preference_remove(key.toNativeChar(allocator: arena)) == 0; return ret; }); } @@ -218,8 +215,7 @@ base class SharedPreferencesAsyncTizen extends SharedPreferencesAsyncPlatform { static bool _getKeysCallback(Pointer pKey, Pointer data) { final String key = pKey.toDartString(); - if (_keysFilters.allowList == null || - _keysFilters.allowList!.contains(key)) { + if (_keysFilters.allowList == null || _keysFilters.allowList!.contains(key)) { _keys!.add(key); } return true; @@ -248,8 +244,7 @@ base class SharedPreferencesAsyncTizen extends SharedPreferencesAsyncPlatform { static bool _getPreferenceCallback(Pointer pKey, Pointer data) { final String key = pKey.toDartString(); - if (_preferencesFilters.allowList == null || - _preferencesFilters.allowList!.contains(key)) { + if (_preferencesFilters.allowList == null || _preferencesFilters.allowList!.contains(key)) { using((Arena arena) { final Pointer pBool = arena(); if (tizen.preference_get_boolean(pKey, pBool) == 0) { diff --git a/packages/shared_preferences/lib/src/shared_preferences_tizen.dart b/packages/shared_preferences/lib/src/shared_preferences_tizen.dart index 2ff4189e6..68ab9e3b6 100644 --- a/packages/shared_preferences/lib/src/shared_preferences_tizen.dart +++ b/packages/shared_preferences/lib/src/shared_preferences_tizen.dart @@ -104,9 +104,9 @@ class SharedPreferencesPlugin extends SharedPreferencesStorePlatform { @override Future clearWithParameters(ClearParameters parameters) async { final PreferencesFilter filter = parameters.filter; - final List keys = List.of(_preferences.keys); + final keys = List.of(_preferences.keys); - for (final String key in keys) { + for (final key in keys) { if (key.startsWith(filter.prefix) && (filter.allowList == null || filter.allowList!.contains(key))) { if (!(await remove(key))) { @@ -136,12 +136,12 @@ class SharedPreferencesPlugin extends SharedPreferencesStorePlatform { GetAllParameters parameters, ) async { final PreferencesFilter filter = parameters.filter; - final Map withPrefix = Map.from( + final withPrefix = Map.from( _preferences, ); withPrefix.removeWhere( - (String key, _) => !(key.startsWith(filter.prefix) && - (filter.allowList?.contains(key) ?? true)), + (String key, _) => + !(key.startsWith(filter.prefix) && (filter.allowList?.contains(key) ?? true)), ); return withPrefix; } @@ -149,8 +149,7 @@ class SharedPreferencesPlugin extends SharedPreferencesStorePlatform { @override Future remove(String key) async { return using((Arena arena) { - final bool ret = - tizen.preference_remove(key.toNativeChar(allocator: arena)) == 0; + final ret = tizen.preference_remove(key.toNativeChar(allocator: arena)) == 0; if (ret) { _preferences.remove(key); } @@ -193,8 +192,6 @@ class SharedPreferencesPlugin extends SharedPreferencesStorePlatform { } String _joinStringList(List list) { - return list.isEmpty - ? _separator - : _separator + list.join(_separator) + _separator; + return list.isEmpty ? _separator : _separator + list.join(_separator) + _separator; } } diff --git a/packages/tizen_app_control/CHANGELOG.md b/packages/tizen_app_control/CHANGELOG.md index 7402c21f9..19634512d 100644 --- a/packages/tizen_app_control/CHANGELOG.md +++ b/packages/tizen_app_control/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 0.2.4 * Update the repository URL to use the `main` branch. diff --git a/packages/tizen_app_control/example/integration_test/tizen_app_control_test.dart b/packages/tizen_app_control/example/integration_test/tizen_app_control_test.dart index 30b33b934..b5b069730 100644 --- a/packages/tizen_app_control/example/integration_test/tizen_app_control_test.dart +++ b/packages/tizen_app_control/example/integration_test/tizen_app_control_test.dart @@ -24,7 +24,7 @@ void main() { }, timeout: kTimeout); test('Can find matching applications', () async { - final AppControl request = AppControl( + final request = AppControl( operation: 'http://tizen.org/appcontrol/operation/view', uri: 'file:///opt/usr/globalapps/$kAppId/shared/res/ic_launcher.png', mime: 'image/*', @@ -35,7 +35,7 @@ void main() { test('Can send and receive request', () async { // Send a request to this app (the test runner itself). - final AppControl request = AppControl( + final request = AppControl( appId: kAppId, operation: 'operation_1', ); @@ -53,7 +53,7 @@ void main() { }, timeout: kTimeout); test('Can send and receive request with uri and mime', () async { - final AppControl request = AppControl( + final request = AppControl( appId: kAppId, operation: 'operation_3', uri: 'myapp://test/path', @@ -67,7 +67,7 @@ void main() { }, timeout: kTimeout); test('Omit invalid extra data', () async { - final AppControl request = AppControl( + final request = AppControl( appId: kAppId, extraData: { 'STRING_DATA': 'string', @@ -87,13 +87,12 @@ void main() { // This time, the request is sent to the service app instead of the test // runner, because the platform doesn't allow sending a reply back when // caller = callee. - final AppControl request = AppControl( + final request = AppControl( appId: kServiceAppId, operation: 'operation_2', ); await request.sendLaunchRequest( - replyCallback: - (AppControl request, AppControl reply, AppControlReplyResult result) { + replyCallback: (AppControl request, AppControl reply, AppControlReplyResult result) { expect(result, AppControlReplyResult.canceled); expect(reply.extraData['STRING_DATA'], 'string'); }, @@ -101,13 +100,13 @@ void main() { }, timeout: kTimeout); test('Cannot find target applications', () async { - final AppControl request1 = AppControl(appId: 'unknown_app'); + final request1 = AppControl(appId: 'unknown_app'); expect( request1.sendLaunchRequest, throwsA(isInstanceOf()), ); - final AppControl request2 = AppControl(operation: 'unknown_operation'); + final request2 = AppControl(operation: 'unknown_operation'); expect( request2.sendLaunchRequest, throwsA(isInstanceOf()), @@ -121,7 +120,7 @@ void serviceMain() { AppControl.onAppControl.listen((ReceivedAppControl request) async { if (request.shouldReply) { - final AppControl reply = AppControl( + final reply = AppControl( extraData: {'STRING_DATA': 'string'}, ); await request.reply(reply, AppControlReplyResult.canceled); diff --git a/packages/tizen_app_control/example/lib/main.dart b/packages/tizen_app_control/example/lib/main.dart index 98ce939de..9d5e4688c 100644 --- a/packages/tizen_app_control/example/lib/main.dart +++ b/packages/tizen_app_control/example/lib/main.dart @@ -29,7 +29,7 @@ void serviceMain() { final StreamSubscription appControlListener = AppControl.onAppControl.listen((ReceivedAppControl request) async { if (request.shouldReply) { - final AppControl reply = AppControl(); + final reply = AppControl(); await request.reply(reply, AppControlReplyResult.succeeded); } }); @@ -61,8 +61,7 @@ class MyApp extends StatefulWidget { } class _MyAppState extends State { - final GlobalKey _messengerKey = - GlobalKey(); + final GlobalKey _messengerKey = GlobalKey(); LocalPort? _localPort; int _messagesCount = 0; bool _isServiceStarted = false; @@ -90,8 +89,8 @@ class _MyAppState extends State { } Future _launchYoutube() async { - const String videoId = 'N7J4hdrvsZA'; - final AppControl request = AppControl( + const videoId = 'N7J4hdrvsZA'; + final request = AppControl( appId: 'com.samsung.tv.cobalt-yt', operation: 'http://tizen.org/appcontrol/operation/default', extraData: { @@ -103,7 +102,7 @@ class _MyAppState extends State { } Future _sendSms() async { - final AppControl request = AppControl( + final request = AppControl( operation: 'http://tizen.org/appcontrol/operation/share_text', uri: 'sms:', launchMode: LaunchMode.group, @@ -122,7 +121,7 @@ class _MyAppState extends State { } Future _pickImage() async { - final AppControl request = AppControl( + final request = AppControl( operation: 'http://tizen.org/appcontrol/operation/pick', mime: 'image/*', launchMode: LaunchMode.group, @@ -140,14 +139,12 @@ class _MyAppState extends State { AppControl reply, AppControlReplyResult result, ) { - const String kAppControlDataSelected = - 'http://tizen.org/appcontrol/data/selected'; + const kAppControlDataSelected = 'http://tizen.org/appcontrol/data/selected'; String? imagePath; if (result == AppControlReplyResult.succeeded && reply.extraData.containsKey(kAppControlDataSelected)) { final List imagePaths = - (reply.extraData[kAppControlDataSelected] as List) - .cast(); + (reply.extraData[kAppControlDataSelected] as List).cast(); imagePath = imagePaths[0]; } _messengerKey.currentState!.showSnackBar( @@ -158,7 +155,7 @@ class _MyAppState extends State { } Future _launchService() async { - final AppControl request = AppControl(appId: _kServiceAppId); + final request = AppControl(appId: _kServiceAppId); await request.sendLaunchRequest( replyCallback: ( AppControl request, @@ -179,7 +176,7 @@ class _MyAppState extends State { } Future _terminateService() async { - final AppRunningContext context = AppRunningContext(appId: _kServiceAppId); + final context = AppRunningContext(appId: _kServiceAppId); context.terminate(background: true); setState(() { _isServiceStarted = false; diff --git a/packages/tizen_app_control/lib/src/app_control.dart b/packages/tizen_app_control/lib/src/app_control.dart index 8524792a8..f2331e668 100644 --- a/packages/tizen_app_control/lib/src/app_control.dart +++ b/packages/tizen_app_control/lib/src/app_control.dart @@ -82,8 +82,7 @@ class AppControl { mime = map['mime'] as String?, category = map['category'] as String?, launchMode = LaunchMode.values.byName(map['launchMode'] as String), - extraData = (map['extraData'] as Map) - .cast() { + extraData = (map['extraData'] as Map).cast() { if (!nativeAttachAppControl(_id, this)) { throw Exception('Could not find an instance of AppControl with ID $_id.'); } @@ -138,18 +137,17 @@ class AppControl { ); /// A stream of incoming application controls. - static final Stream onAppControl = - _eventChannel.receiveBroadcastStream().map( - (dynamic event) => ReceivedAppControl._fromMap( - (event as Map).cast(), - ), - ); + static final Stream onAppControl = _eventChannel.receiveBroadcastStream().map( + (dynamic event) => ReceivedAppControl._fromMap( + (event as Map).cast(), + ), + ); /// Returns a list of installed applications that can handle this request. Future> getMatchedAppIds() async { await _setAppControlData(); - final Map args = {'id': _id}; + final args = {'id': _id}; final dynamic response = await _methodChannel.invokeMethod( 'getMatchedAppIds', args, @@ -175,7 +173,7 @@ class AppControl { }) async { await _setAppControlData(); - final Map args = { + final args = { 'id': _id, 'waitForReply': replyCallback != null, }; @@ -192,9 +190,8 @@ class AppControl { responseMap['result'] as String, ); final Map replyMap = - (responseMap['reply'] as Map) - .cast(); - final AppControl reply = AppControl._fromMap(replyMap); + (responseMap['reply'] as Map).cast(); + final reply = AppControl._fromMap(replyMap); await replyCallback(this, reply, result); } } @@ -211,12 +208,12 @@ class AppControl { Future sendTerminateRequest() async { await _setAppControlData(); - final Map args = {'id': _id}; + final args = {'id': _id}; await _methodChannel.invokeMethod('sendTerminateRequest', args); } Future _setAppControlData() async { - final Map args = { + final args = { 'id': _id, 'appId': appId, 'operation': operation, @@ -239,12 +236,12 @@ class AppControl { static Future setAutoRestart(AppControl appControl) async { await appControl._setAppControlData(); - final Map args = {'id': appControl._id}; + final args = {'id': appControl._id}; final int? handleAddress = await _methodChannel.invokeMethod( 'getHandle', args, ); - final Pointer handle = Pointer.fromAddress(handleAddress!); + final handle = Pointer.fromAddress(handleAddress!); final int ret = appControlSetAutoRestart(handle); if (ret != 0) { @@ -289,7 +286,7 @@ class ReceivedAppControl extends AppControl { Future reply(AppControl reply, AppControlReplyResult result) async { await reply._setAppControlData(); - final Map args = { + final args = { 'id': _id, 'replyId': reply._id, 'result': result.name, diff --git a/packages/tizen_app_control/lib/src/ffi.dart b/packages/tizen_app_control/lib/src/ffi.dart index 78170e106..721d94099 100644 --- a/packages/tizen_app_control/lib/src/ffi.dart +++ b/packages/tizen_app_control/lib/src/ffi.dart @@ -16,7 +16,7 @@ typedef _AttachAppControlNative = Bool Function(Int32, Handle); typedef AttachAppControl = bool Function(int, Object); final DynamicLibrary _processLib = () { - final DynamicLibrary processLib = DynamicLibrary.process(); + final processLib = DynamicLibrary.process(); final _InitializeDartApi initFunction = processLib.lookupFunction<_InitializeDartApiNative, _InitializeDartApi>( 'NativeInitializeDartApi', diff --git a/packages/tizen_app_manager/CHANGELOG.md b/packages/tizen_app_manager/CHANGELOG.md index bf8a84064..a3d694b72 100644 --- a/packages/tizen_app_manager/CHANGELOG.md +++ b/packages/tizen_app_manager/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 0.2.6 * Update the repository URL to use the `main` branch. diff --git a/packages/tizen_app_manager/example/integration_test/tizen_app_manager_test.dart b/packages/tizen_app_manager/example/integration_test/tizen_app_manager_test.dart index 4e33c3a65..0de364a5c 100644 --- a/packages/tizen_app_manager/example/integration_test/tizen_app_manager_test.dart +++ b/packages/tizen_app_manager/example/integration_test/tizen_app_manager_test.dart @@ -27,7 +27,7 @@ void main() { await tester.pumpWidget(const MyApp()); final String appId = await AppManager.currentAppId; - final AppRunningContext context = AppRunningContext(appId: appId); + final context = AppRunningContext(appId: appId); // TODO(seungsoo47): The `AppRunningContext.appState` API always returns the // appropriate value. However, we decided to comment out this testcase @@ -64,8 +64,7 @@ void main() { ); }); - testWidgets('throws ArgumentError for empty appId', - (WidgetTester _) async { + testWidgets('throws ArgumentError for empty appId', (WidgetTester _) async { await expectLater(AppManager.isRunning(''), throwsArgumentError); }); }); @@ -79,8 +78,7 @@ void main() { expect(appInfo.sharedResourcePath, isNotEmpty); }); - testWidgets('throws ArgumentError for empty appId', - (WidgetTester _) async { + testWidgets('throws ArgumentError for empty appId', (WidgetTester _) async { await expectLater(AppManager.getAppInfo(''), throwsArgumentError); }); }); @@ -89,7 +87,7 @@ void main() { group('AppRunningContext', () { testWidgets('packageId matches current app', (WidgetTester _) async { final String appId = await AppManager.currentAppId; - final AppRunningContext context = AppRunningContext(appId: appId); + final context = AppRunningContext(appId: appId); expect(context.packageId, 'org.tizen.tizen_app_manager_example'); }); diff --git a/packages/tizen_app_manager/example/lib/main.dart b/packages/tizen_app_manager/example/lib/main.dart index 0a7f9f620..14e9504cf 100644 --- a/packages/tizen_app_manager/example/lib/main.dart +++ b/packages/tizen_app_manager/example/lib/main.dart @@ -98,7 +98,7 @@ class _CurrentAppScreenState extends State<_CurrentAppScreen> { builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.hasData) { final AppInfo appInfo = snapshot.data!; - final AppRunningContext appContext = AppRunningContext( + final appContext = AppRunningContext( appId: appInfo.appId, ); return ListView( @@ -131,8 +131,7 @@ class _AppListScreen extends StatefulWidget { State<_AppListScreen> createState() => _AppListScreenState(); } -class _AppListScreenState extends State<_AppListScreen> - with AutomaticKeepAliveClientMixin { +class _AppListScreenState extends State<_AppListScreen> with AutomaticKeepAliveClientMixin { @override bool get wantKeepAlive => true; @@ -151,7 +150,7 @@ class _AppListScreenState extends State<_AppListScreen> final AppInfo appInfo = apps[index]; Widget appIcon = const Icon(Icons.error_outline); if (appInfo.iconPath != null) { - final File iconFile = File(appInfo.iconPath!); + final iconFile = File(appInfo.iconPath!); if (iconFile.existsSync()) { appIcon = Image.file(iconFile); } @@ -196,8 +195,7 @@ class _AppEventsScreen extends StatefulWidget { State<_AppEventsScreen> createState() => _AppEventsScreenState(); } -class _AppEventsScreenState extends State<_AppEventsScreen> - with AutomaticKeepAliveClientMixin { +class _AppEventsScreenState extends State<_AppEventsScreen> with AutomaticKeepAliveClientMixin { late final StreamSubscription? _launchSubscription; late final StreamSubscription? _terminateSubscription; final List<_AppEvent> _appEvents = <_AppEvent>[]; @@ -241,7 +239,7 @@ class _AppEventsScreenState extends State<_AppEventsScreen> } Future _getDeviceInfo() async { - final DeviceInfoPluginTizen deviceInfo = DeviceInfoPluginTizen(); + final deviceInfo = DeviceInfoPluginTizen(); final TizenDeviceInfo tizenInfo = await deviceInfo.tizenInfo; setState(() { if (tizenInfo.profile == 'tv') { diff --git a/packages/tizen_app_manager/lib/src/app_manager.dart b/packages/tizen_app_manager/lib/src/app_manager.dart index 1d673a3b6..da60fdae0 100644 --- a/packages/tizen_app_manager/lib/src/app_manager.dart +++ b/packages/tizen_app_manager/lib/src/app_manager.dart @@ -60,8 +60,8 @@ class AppManager { throw ArgumentError('Must not be empty', 'appId'); } - final Map? app = await _channel - .invokeMapMethod('getAppInfo', { + final Map? app = + await _channel.invokeMapMethod('getAppInfo', { 'appId': appId, }); return AppInfo.fromMap(app!); @@ -69,10 +69,10 @@ class AppManager { /// Gets the information of all apps installed on a device. static Future> getInstalledApps() async { - final List>? apps = await _channel - .invokeListMethod>('getInstalledApps'); + final List>? apps = + await _channel.invokeListMethod>('getInstalledApps'); - final List list = []; + final list = []; for (final Map app in apps!) { list.add(AppInfo.fromMap(app.cast())); } @@ -199,8 +199,8 @@ class AppRunningContext { /// Creates an instance of [AppRunningContext] with map. static AppRunningContext fromMap(Map map) { - final String appId = map['appId'] as String; - final int handle = map['handle'] as int; + final appId = map['appId'] as String; + final handle = map['handle'] as int; return AppRunningContext(appId: appId, handleAddress: handle); } diff --git a/packages/tizen_audio_manager/CHANGELOG.md b/packages/tizen_audio_manager/CHANGELOG.md index 3ad48efaf..251ce60a6 100644 --- a/packages/tizen_audio_manager/CHANGELOG.md +++ b/packages/tizen_audio_manager/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 0.1.2 * Update the repository URL to use the `main` branch. diff --git a/packages/tizen_audio_manager/example/integration_test/audio_manager_test.dart b/packages/tizen_audio_manager/example/integration_test/audio_manager_test.dart index 42d179d1f..854dbc55a 100644 --- a/packages/tizen_audio_manager/example/integration_test/audio_manager_test.dart +++ b/packages/tizen_audio_manager/example/integration_test/audio_manager_test.dart @@ -208,39 +208,31 @@ void main() { }); test('currentPlaybackType returns a valid AudioVolumeType', () async { - final AudioVolumeType type = - await AudioManager.volumeController.currentPlaybackType; + final AudioVolumeType type = await AudioManager.volumeController.currentPlaybackType; expect(AudioVolumeType.values, contains(type)); }); test('onChanged emits VolumeChangedEvent when volume is changed', () async { - final int originalLevel = - await AudioManager.volumeController.getLevel(AudioVolumeType.system); - final int maxLevel = - await AudioManager.volumeController.getMaxLevel(AudioVolumeType.system); - final int targetLevel = originalLevel == maxLevel ? 0 : maxLevel; - - final Completer completer = - Completer(); - final StreamSubscription subscription = AudioManager - .volumeController.onChanged - .listen((VolumeChangedEvent event) { + final int originalLevel = await AudioManager.volumeController.getLevel(AudioVolumeType.system); + final int maxLevel = await AudioManager.volumeController.getMaxLevel(AudioVolumeType.system); + final targetLevel = originalLevel == maxLevel ? 0 : maxLevel; + + final completer = Completer(); + final StreamSubscription subscription = + AudioManager.volumeController.onChanged.listen((VolumeChangedEvent event) { if (event.type == AudioVolumeType.system && !completer.isCompleted) { completer.complete(event); } }); try { - await AudioManager.volumeController - .setLevel(AudioVolumeType.system, targetLevel); - final VolumeChangedEvent event = - await completer.future.timeout(const Duration(seconds: 5)); + await AudioManager.volumeController.setLevel(AudioVolumeType.system, targetLevel); + final VolumeChangedEvent event = await completer.future.timeout(const Duration(seconds: 5)); expect(event.type, equals(AudioVolumeType.system)); expect(event.level, equals(targetLevel)); } finally { - await AudioManager.volumeController - .setLevel(AudioVolumeType.system, originalLevel); + await AudioManager.volumeController.setLevel(AudioVolumeType.system, originalLevel); await subscription.cancel(); } }); diff --git a/packages/tizen_audio_manager/example/lib/main.dart b/packages/tizen_audio_manager/example/lib/main.dart index 631daec9d..f2dc66a7e 100644 --- a/packages/tizen_audio_manager/example/lib/main.dart +++ b/packages/tizen_audio_manager/example/lib/main.dart @@ -41,16 +41,15 @@ class _VolumeControlScreenState extends State { Timer? _timer; VolumeChangedEvent? _volumeChangedEvent; StreamSubscription? _subscription; - final List> _dropdownButtonItems = - AudioVolumeType.values - .where((AudioVolumeType e) => e != AudioVolumeType.none) - .map( - (AudioVolumeType e) => DropdownMenuItem( - value: e, - child: Text(e.name), - ), - ) - .toList(); + final List> _dropdownButtonItems = AudioVolumeType.values + .where((AudioVolumeType e) => e != AudioVolumeType.none) + .map( + (AudioVolumeType e) => DropdownMenuItem( + value: e, + child: Text(e.name), + ), + ) + .toList(); @override void initState() { @@ -58,8 +57,7 @@ class _VolumeControlScreenState extends State { _onAudioTypeChanged(_selectedType); _timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) async { - final AudioVolumeType type = - await AudioManager.volumeController.currentPlaybackType; + final AudioVolumeType type = await AudioManager.volumeController.currentPlaybackType; if (type != _currentPlaybackType) { setState(() { diff --git a/packages/tizen_audio_manager/lib/tizen_audio_manager.dart b/packages/tizen_audio_manager/lib/tizen_audio_manager.dart index 0930958fd..e33699592 100644 --- a/packages/tizen_audio_manager/lib/tizen_audio_manager.dart +++ b/packages/tizen_audio_manager/lib/tizen_audio_manager.dart @@ -120,12 +120,11 @@ class AudioVolume { } /// A stream of events occurring when the volume level is changed. - Stream onChanged = - AudioManager._eventChannel.receiveBroadcastStream().map( - (dynamic msg) => VolumeChangedEvent.fromMap( - (msg as Map).cast(), - ), - ); + Stream onChanged = AudioManager._eventChannel.receiveBroadcastStream().map( + (dynamic msg) => VolumeChangedEvent.fromMap( + (msg as Map).cast(), + ), + ); } /// Represents an event emitted on volume change. @@ -140,8 +139,7 @@ class VolumeChangedEvent { final AudioVolumeType type; /// Creates an event from a map. - static VolumeChangedEvent fromMap(Map map) => - VolumeChangedEvent( + static VolumeChangedEvent fromMap(Map map) => VolumeChangedEvent( level: map['level'] as int? ?? 0, type: _stringToAudioVolumeType(map['type'] as String? ?? 'none'), ); diff --git a/packages/tizen_bundle/CHANGELOG.md b/packages/tizen_bundle/CHANGELOG.md index 8a8c31980..e54979309 100644 --- a/packages/tizen_bundle/CHANGELOG.md +++ b/packages/tizen_bundle/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 0.1.5 * Fix `operator []` and `remove()` to not throw on non-String keys. diff --git a/packages/tizen_bundle/example/integration_test/tizen_bundle_test.dart b/packages/tizen_bundle/example/integration_test/tizen_bundle_test.dart index 5b4de2481..023004737 100644 --- a/packages/tizen_bundle/example/integration_test/tizen_bundle_test.dart +++ b/packages/tizen_bundle/example/integration_test/tizen_bundle_test.dart @@ -14,22 +14,22 @@ void main() { // --------------------------------------------------------------------------- group('Bundle() default constructor', () { test('creates an empty bundle with length 0', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); expect(bundle.length, 0); }); test('isEmpty returns true for a newly created bundle', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); expect(bundle.isEmpty, true); }); test('isNotEmpty returns false for a newly created bundle', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); expect(bundle.isNotEmpty, false); }); test('keys returns empty iterable for an empty bundle', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); expect(bundle.keys, isEmpty); }); }); @@ -39,14 +39,13 @@ void main() { // --------------------------------------------------------------------------- group('Bundle.fromMap', () { test('creates an empty bundle from an empty map', () async { - final Bundle bundle = Bundle.fromMap({}); + final bundle = Bundle.fromMap({}); expect(bundle.length, 0); expect(bundle.isEmpty, true); }); - test('creates a bundle with String, List, and Uint8List entries', - () async { - final Bundle bundle = Bundle.fromMap({ + test('creates a bundle with String, List, and Uint8List entries', () async { + final bundle = Bundle.fromMap({ 'stringKey': 'stringValue', 'stringsKey': ['value1', 'value2'], 'bytesKey': Uint8List.fromList([0x03]), @@ -65,10 +64,10 @@ void main() { test( 'mutating the original after copy does not affect the copy', () async { - final Bundle original = Bundle(); + final original = Bundle(); original['key'] = 'originalValue'; - final Bundle copy = Bundle.fromBundle(original); + final copy = Bundle.fromBundle(original); original['key'] = 'mutatedValue'; // copy should still hold the value at the time of duplication @@ -76,13 +75,11 @@ void main() { }, ); - test( - 'copy has independent entries — adding to copy does not affect original', - () async { - final Bundle original = Bundle(); + test('copy has independent entries — adding to copy does not affect original', () async { + final original = Bundle(); original['key'] = 'value'; - final Bundle copy = Bundle.fromBundle(original); + final copy = Bundle.fromBundle(original); copy['newKey'] = 'newValue'; expect(original.containsKey('newKey'), false); @@ -94,28 +91,28 @@ void main() { // --------------------------------------------------------------------------- group('Bundle.decode', () { test('round-trips a List value through encode/decode', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['stringsKey'] = ['alpha', 'beta', 'gamma']; final String encoded = bundle.encode(); - final Bundle decoded = Bundle.decode(encoded); + final decoded = Bundle.decode(encoded); expect(decoded['stringsKey'], ['alpha', 'beta', 'gamma']); }); test('round-trips a Uint8List value through encode/decode', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['bytesKey'] = Uint8List.fromList([0x00, 0x7f, 0xff]); final String encoded = bundle.encode(); - final Bundle decoded = Bundle.decode(encoded); + final decoded = Bundle.decode(encoded); expect(decoded['bytesKey'], Uint8List.fromList([0x00, 0x7f, 0xff])); }); test('round-trips multiple keys of mixed types', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['s'] = 'hello'; bundle['ss'] = ['x', 'y']; bundle['b'] = Uint8List.fromList([1, 2, 3]); final String encoded = bundle.encode(); - final Bundle decoded = Bundle.decode(encoded); + final decoded = Bundle.decode(encoded); expect(decoded.length, 3); expect(decoded['s'], 'hello'); expect(decoded['ss'], ['x', 'y']); @@ -128,29 +125,28 @@ void main() { // --------------------------------------------------------------------------- group('operator[] (get)', () { test('returns null for a missing key', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); expect(bundle['nonExistentKey'], isNull); }); test('returns null when the key is not a String', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['someKey'] = 'someValue'; // operator[] takes an Object?, so it must accept any key. - for (final Object? key in [null, 42, true]) { + for (final key in [null, 42, true]) { expect(bundle[key], isNull); } }); test('returns the correct value after key is overwritten', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['key'] = 'first'; bundle['key'] = 'second'; expect(bundle['key'], 'second'); }); - test('same read-only call twice returns identical results (idempotency)', - () async { - final Bundle bundle = Bundle(); + test('same read-only call twice returns identical results (idempotency)', () async { + final bundle = Bundle(); bundle['key'] = 'value'; expect(bundle['key'], bundle['key']); }); @@ -161,7 +157,7 @@ void main() { // --------------------------------------------------------------------------- group('operator[]= (set)', () { test('throws ArgumentError for an unsupported value type', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); expect( () => bundle['key'] = 42, throwsA(isA()), @@ -169,30 +165,29 @@ void main() { }); test('stores an empty string value', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['emptyString'] = ''; expect(bundle['emptyString'], ''); }); test('stores a single-element List', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['single'] = ['only']; expect(bundle['single'], ['only']); }); test('stores an empty Uint8List', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['emptyBytes'] = Uint8List(0); - final Uint8List result = bundle['emptyBytes']! as Uint8List; + final result = bundle['emptyBytes']! as Uint8List; expect(result.length, 0); }); test('preserves full byte range 0x00–0xff in Uint8List', () async { - final Bundle bundle = Bundle(); - final Uint8List allBytes = - Uint8List.fromList(List.generate(256, (int i) => i)); + final bundle = Bundle(); + final allBytes = Uint8List.fromList(List.generate(256, (int i) => i)); bundle['allBytes'] = allBytes; - final Uint8List result = bundle['allBytes']! as Uint8List; + final result = bundle['allBytes']! as Uint8List; expect(result, allBytes); }); }); @@ -202,22 +197,22 @@ void main() { // --------------------------------------------------------------------------- group('remove()', () { test('removing a key that is not a String is a no-op', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['key'] = 'value'; // remove() takes an Object?, so it must accept any key. - for (final Object? key in [null, 42, true]) { + for (final key in [null, 42, true]) { expect(() => bundle.remove(key), returnsNormally); } expect(bundle.length, 1); }); test('removing a non-existent key is a no-op', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); expect(() => bundle.remove('doesNotExist'), returnsNormally); }); test('add then remove then verify gone (state transition)', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['key'] = 'value'; expect(bundle.containsKey('key'), true); bundle.remove('key'); @@ -231,14 +226,14 @@ void main() { // --------------------------------------------------------------------------- group('clear()', () { test('clear() on an already-empty bundle is idempotent', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle.clear(); expect(bundle.length, 0); expect(bundle.isEmpty, true); }); test('clear() removes all entries including mixed types', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['s'] = 'hello'; bundle['ss'] = ['a', 'b']; bundle['b'] = Uint8List.fromList([1]); @@ -253,7 +248,7 @@ void main() { // --------------------------------------------------------------------------- group('length, isEmpty, isNotEmpty', () { test('length reflects current entry count correctly', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); expect(bundle.length, 0); bundle['k1'] = 'v1'; expect(bundle.length, 1); @@ -264,14 +259,14 @@ void main() { }); test('isNotEmpty becomes true after adding an entry', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); expect(bundle.isNotEmpty, false); bundle['key'] = 'value'; expect(bundle.isNotEmpty, true); }); test('isEmpty becomes true after removing the last entry', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['key'] = 'value'; expect(bundle.isEmpty, false); bundle.remove('key'); @@ -284,22 +279,22 @@ void main() { // --------------------------------------------------------------------------- group('inherited MapMixin members', () { test('containsKey returns true for existing key', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['key'] = 'value'; expect(bundle.containsKey('key'), true); }); test('containsKey returns false for missing key', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); expect(bundle.containsKey('missing'), false); }); test('keys of different bundles are independent', () async { - final Bundle bundle1 = Bundle(); + final bundle1 = Bundle(); bundle1['a'] = 'v1'; final Iterable keys1 = bundle1.keys; - final Bundle bundle2 = Bundle(); + final bundle2 = Bundle(); bundle2['b'] = 'v2'; bundle2.keys; @@ -307,7 +302,7 @@ void main() { }); test('keys and values return all stored entries', () async { - final Bundle bundle = Bundle.fromMap({ + final bundle = Bundle.fromMap({ 'key1': 'value1', 'key2': 'value2', 'key3': 'value3', @@ -320,19 +315,19 @@ void main() { }); test('containsValue returns true for existing string value', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['key'] = 'needle'; expect(bundle.containsValue('needle'), true); }); test('containsValue returns false for absent value', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['key'] = 'value'; expect(bundle.containsValue('absent'), false); }); test('entries exposes key-value pairs correctly', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['k'] = 'v'; final MapEntry entry = bundle.entries.single; expect(entry.key, 'k'); @@ -340,10 +335,10 @@ void main() { }); test('forEach iterates over all entries', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['a'] = '1'; bundle['b'] = '2'; - final Map collected = {}; + final collected = {}; bundle.forEach((String key, Object value) { collected[key] = value; }); @@ -353,7 +348,7 @@ void main() { }); test('addAll adds all entries from a map', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle.addAll({ 'x': 'valueX', 'y': 'valueY', @@ -364,7 +359,7 @@ void main() { }); test('putIfAbsent inserts only when key is absent', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['existing'] = 'original'; final Object result = bundle.putIfAbsent('existing', () => 'new'); diff --git a/packages/tizen_bundle/lib/tizen_bundle.dart b/packages/tizen_bundle/lib/tizen_bundle.dart index a72ae44a1..2e952df3c 100644 --- a/packages/tizen_bundle/lib/tizen_bundle.dart +++ b/packages/tizen_bundle/lib/tizen_bundle.dart @@ -40,14 +40,13 @@ class Bundle extends MapMixin { /// Creates a [Bundle] from the given [map]. factory Bundle.fromMap(Map map) { - final Bundle bundle = Bundle(); + final bundle = Bundle(); map.forEach((String key, Object value) => bundle[key] = value); return bundle; } late final Pointer _handle; - static final Finalizer> _finalizer = - Finalizer>( + static final Finalizer> _finalizer = Finalizer>( (Pointer bundle) => tizen.bundle_free(bundle), ); @@ -65,7 +64,7 @@ class Bundle extends MapMixin { /// The keys of this. @override Iterable get keys { - final List keys = []; + final keys = []; _currentKeys = keys; tizen.bundle_foreach( _handle, @@ -200,9 +199,8 @@ class Bundle extends MapMixin { void _addStrings(String key, List values) { using((Arena arena) { - final List> stringList = values - .map((String str) => str.toNativeChar(allocator: arena)) - .toList(); + final List> stringList = + values.map((String str) => str.toNativeChar(allocator: arena)).toList(); final Pointer> stringArray = arena>( stringList.length, ); @@ -235,8 +233,8 @@ class Bundle extends MapMixin { _throwException(ret); } - final List strings = []; - for (int index = 0; index < length.value; ++index) { + final strings = []; + for (var index = 0; index < length.value; ++index) { strings.add(stringArray[index].toDartString()); } return strings; @@ -246,7 +244,7 @@ class Bundle extends MapMixin { void _addBytes(String key, Uint8List bytes) { using((Arena arena) { final Pointer bytesArray = arena(bytes.length); - for (int index = 0; index < bytes.length; ++index) { + for (var index = 0; index < bytes.length; ++index) { bytesArray[index] = bytes[index] & 0xff; } @@ -276,8 +274,8 @@ class Bundle extends MapMixin { _throwException(ret); } - final Uint8List byteList = Uint8List(size.value); - for (int index = 0; index < size.value; ++index) { + final byteList = Uint8List(size.value); + for (var index = 0; index < size.value; ++index) { byteList[index] = bytes.value[index]; } return byteList; diff --git a/packages/tizen_log/CHANGELOG.md b/packages/tizen_log/CHANGELOG.md index 5a509b215..b21c90c9a 100644 --- a/packages/tizen_log/CHANGELOG.md +++ b/packages/tizen_log/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 0.1.3 * Update the repository URL to use the `main` branch. diff --git a/packages/tizen_log/example/integration_test/tizen_log_test.dart b/packages/tizen_log/example/integration_test/tizen_log_test.dart index 0bdd8eaa2..e59714123 100644 --- a/packages/tizen_log/example/integration_test/tizen_log_test.dart +++ b/packages/tizen_log/example/integration_test/tizen_log_test.dart @@ -9,7 +9,7 @@ import 'package:tizen_log/tizen_log.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); - const String tag = 'TizenLogTest'; + const tag = 'TizenLogTest'; group('Log', () { test('verbose does not throw', () async { diff --git a/packages/tizen_log/lib/tizen_log.dart b/packages/tizen_log/lib/tizen_log.dart index 49107a083..c054aee3b 100644 --- a/packages/tizen_log/lib/tizen_log.dart +++ b/packages/tizen_log/lib/tizen_log.dart @@ -6,10 +6,8 @@ import 'dart:ffi'; import 'package:ffi/ffi.dart'; -typedef _DlogPrintNative = Void Function( - Int32, Pointer, Pointer, Pointer); -typedef _DlogPrint = void Function( - int, Pointer, Pointer, Pointer); +typedef _DlogPrintNative = Void Function(Int32, Pointer, Pointer, Pointer); +typedef _DlogPrint = void Function(int, Pointer, Pointer, Pointer); /// Provides the ability to use Tizen's logging service, dlog. /// @@ -24,9 +22,8 @@ class Log { static final DynamicLibrary _library = DynamicLibrary.open('libdlog.so.0'); - static final _DlogPrint _dlogPrint = _library - .lookup>('dlog_print') - .asFunction(); + static final _DlogPrint _dlogPrint = + _library.lookup>('dlog_print').asFunction(); static final RegExp _stackTraceRegExp = RegExp( r'^#(\d+)\s+(.+)\((.+\.dart):(\d+)(:\d+)?\)$', @@ -182,7 +179,7 @@ class Log { final Iterable matches = _stackTraceRegExp.allMatches( StackTrace.current.toString(), ); - for (final RegExpMatch match in matches) { + for (final match in matches) { final List groups = match.groups([1, 2, 3, 4]); if (!groups.any((String? group) => group == null)) { final int frameIndex = int.parse(groups[0]!); diff --git a/packages/tizen_notification/CHANGELOG.md b/packages/tizen_notification/CHANGELOG.md index e64db2a4f..16774a2de 100644 --- a/packages/tizen_notification/CHANGELOG.md +++ b/packages/tizen_notification/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 0.2.2 * Update integration tests. diff --git a/packages/tizen_notification/example/integration_test/tizen_notification_test.dart b/packages/tizen_notification/example/integration_test/tizen_notification_test.dart index 2d92dd533..1d1bfb815 100644 --- a/packages/tizen_notification/example/integration_test/tizen_notification_test.dart +++ b/packages/tizen_notification/example/integration_test/tizen_notification_test.dart @@ -45,7 +45,7 @@ void main() { test( 'show notification with TizenNotificationDetails does not throw', () async { - final TizenNotificationDetails details = TizenNotificationDetails( + final details = TizenNotificationDetails( properties: NotificationProperty.disableAutoDelete, style: NotificationStyle.tray, ); diff --git a/packages/tizen_notification/example/lib/main.dart b/packages/tizen_notification/example/lib/main.dart index 51c5fb5b4..ae8c48379 100644 --- a/packages/tizen_notification/example/lib/main.dart +++ b/packages/tizen_notification/example/lib/main.dart @@ -14,12 +14,11 @@ void main() { class MyApp extends StatelessWidget { MyApp({super.key}); - final TizenNotificationPlugin _tizenNotificationPlugin = - TizenNotificationPlugin(); + final TizenNotificationPlugin _tizenNotificationPlugin = TizenNotificationPlugin(); final int _notificationId = 1; Future _showNotification() async { - final TizenNotificationDetails details = TizenNotificationDetails( + final details = TizenNotificationDetails( icons: NotificationIcons(icon: 'test.png'), sound: NotificationSound(type: SoundType.builtIn), vibration: NotificationVibration(type: VibrationType.builtIn), diff --git a/packages/tizen_notification/lib/tizen_notification.dart b/packages/tizen_notification/lib/tizen_notification.dart index 75d9b8e1b..727f0a907 100644 --- a/packages/tizen_notification/lib/tizen_notification.dart +++ b/packages/tizen_notification/lib/tizen_notification.dart @@ -22,8 +22,7 @@ class TizenNotificationPlugin { String body = '', TizenNotificationDetails? notificationDetails, }) { - final Map details = - notificationDetails?.toMap() ?? {}; + final Map details = notificationDetails?.toMap() ?? {}; details['id'] = id.toString(); details['title'] = title; details['body'] = body; @@ -31,8 +30,7 @@ class TizenNotificationPlugin { // Set disableAppLaunch automatically if appControl is unset. if (notificationDetails?.appControl == null) { final int properties = (details['properties'] as int?) ?? 0; - details['properties'] = - properties | NotificationProperty.disableAppLaunch; + details['properties'] = properties | NotificationProperty.disableAppLaunch; } return _channel.invokeMethod('show', details); diff --git a/packages/tizen_package_manager/CHANGELOG.md b/packages/tizen_package_manager/CHANGELOG.md index effcd8add..db61e9f96 100644 --- a/packages/tizen_package_manager/CHANGELOG.md +++ b/packages/tizen_package_manager/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 0.4.4 * Update integration tests. diff --git a/packages/tizen_package_manager/example/integration_test/tizen_package_manager_test.dart b/packages/tizen_package_manager/example/integration_test/tizen_package_manager_test.dart index 3c8fa0e67..f2aa2e980 100644 --- a/packages/tizen_package_manager/example/integration_test/tizen_package_manager_test.dart +++ b/packages/tizen_package_manager/example/integration_test/tizen_package_manager_test.dart @@ -41,16 +41,14 @@ void main() { group('PackageInfo fields', () { test('iconPath is null or a non-empty string', () async { - final PackageInfo info = - await PackageManager.getPackageInfo(currentPackageId); + final PackageInfo info = await PackageManager.getPackageInfo(currentPackageId); expect(info.iconPath, anyOf(isNull, isNotEmpty)); }); }); group('PackageSizeInfo fields', () { test('all size fields are non-negative', () async { - final PackageSizeInfo info = - await PackageManager.getPackageSizeInfo(currentPackageId); + final PackageSizeInfo info = await PackageManager.getPackageSizeInfo(currentPackageId); expect(info.dataSize, greaterThanOrEqualTo(0)); expect(info.cacheSize, greaterThanOrEqualTo(0)); expect(info.appSize, greaterThanOrEqualTo(0)); @@ -64,7 +62,7 @@ void main() { test('each PackageInfo item has valid field values', () async { final List infos = await PackageManager.getPackagesInfo(); expect(infos, isNotEmpty); - for (final PackageInfo info in infos) { + for (final info in infos) { // Field types are already guaranteed by PackageInfo.fromMap (it casts // each field), so only the value-level expectations are asserted here. expect(info.packageId, isNotEmpty); diff --git a/packages/tizen_package_manager/example/lib/main.dart b/packages/tizen_package_manager/example/lib/main.dart index 727b08fd4..954c0f9b9 100644 --- a/packages/tizen_package_manager/example/lib/main.dart +++ b/packages/tizen_package_manager/example/lib/main.dart @@ -86,8 +86,8 @@ class _CurrentPackageScreenState extends State<_CurrentPackageScreen> { ]), builder: (BuildContext context, AsyncSnapshot> snapshot) { if (snapshot.hasData) { - final PackageInfo packageInfo = snapshot.data![0] as PackageInfo; - final PackageSizeInfo sizeInfo = snapshot.data![1] as PackageSizeInfo; + final packageInfo = snapshot.data![0] as PackageInfo; + final sizeInfo = snapshot.data![1] as PackageSizeInfo; return ListView( children: [ _infoTile('Package ID', packageInfo.packageId), @@ -100,18 +100,15 @@ class _CurrentPackageScreenState extends State<_CurrentPackageScreen> { _infoTile('Removable', packageInfo.isRemovable.toString()), const Divider(), const ListTile( - title: Text('Package Size Information', - style: TextStyle(fontWeight: FontWeight.bold)), + title: + Text('Package Size Information', style: TextStyle(fontWeight: FontWeight.bold)), ), _infoTile('Data Size', '${sizeInfo.dataSize} bytes'), _infoTile('Cache Size', '${sizeInfo.cacheSize} bytes'), _infoTile('App Size', '${sizeInfo.appSize} bytes'), - _infoTile( - 'External Data Size', '${sizeInfo.externalDataSize} bytes'), - _infoTile( - 'External Cache Size', '${sizeInfo.externalCacheSize} bytes'), - _infoTile( - 'External App Size', '${sizeInfo.externalAppSize} bytes'), + _infoTile('External Data Size', '${sizeInfo.externalDataSize} bytes'), + _infoTile('External Cache Size', '${sizeInfo.externalCacheSize} bytes'), + _infoTile('External App Size', '${sizeInfo.externalAppSize} bytes'), ], ); } else if (snapshot.hasError) { @@ -131,24 +128,19 @@ class _PackageListScreen extends StatefulWidget { State<_PackageListScreen> createState() => _PackageListScreenState(); } -class _PackageListScreenState extends State<_PackageListScreen> - with AutomaticKeepAliveClientMixin { +class _PackageListScreenState extends State<_PackageListScreen> with AutomaticKeepAliveClientMixin { @override bool get wantKeepAlive => true; - Future> _getAllPackagesSizeInfo( - List packages) async { - final Map sizeInfoMap = - {}; + Future> _getAllPackagesSizeInfo(List packages) async { + final sizeInfoMap = {}; - for (final PackageInfo package in packages) { + for (final package in packages) { try { - final PackageSizeInfo sizeInfo = - await PackageManager.getPackageSizeInfo(package.packageId); + final PackageSizeInfo sizeInfo = await PackageManager.getPackageSizeInfo(package.packageId); sizeInfoMap[package.packageId] = sizeInfo; } catch (e) { - debugPrint( - 'Failed to get size info for package ${package.packageId}: $e'); + debugPrint('Failed to get size info for package ${package.packageId}: $e'); } } @@ -174,14 +166,12 @@ class _PackageListScreenState extends State<_PackageListScreen> AsyncSnapshot> sizeSnapshot, ) { if (sizeSnapshot.hasData) { - final Map sizeInfoMap = - sizeSnapshot.data!; + final Map sizeInfoMap = sizeSnapshot.data!; return ListView.builder( itemCount: packages.length, itemBuilder: (BuildContext context, int index) { final PackageInfo package = packages[index]; - final PackageSizeInfo? sizeInfo = - sizeInfoMap[package.packageId]; + final PackageSizeInfo? sizeInfo = sizeInfoMap[package.packageId]; return ListTile( title: Text(package.label), diff --git a/packages/tizen_package_manager/lib/tizen_package_manager.dart b/packages/tizen_package_manager/lib/tizen_package_manager.dart index 067e70f5a..e1a472aba 100644 --- a/packages/tizen_package_manager/lib/tizen_package_manager.dart +++ b/packages/tizen_package_manager/lib/tizen_package_manager.dart @@ -96,8 +96,8 @@ class PackageManager { throw ArgumentError('Must not be empty', 'packageId'); } - final Map? package = await _channel - .invokeMapMethod('getPackage', { + final Map? package = + await _channel.invokeMapMethod('getPackage', { 'packageId': packageId, }); return PackageInfo.fromMap(package!); @@ -108,7 +108,7 @@ class PackageManager { final List>? packages = await _channel.invokeListMethod>('getPackages'); - final List list = []; + final list = []; for (final Map package in packages!) { list.add(PackageInfo.fromMap(package.cast())); } @@ -121,8 +121,7 @@ class PackageManager { throw ArgumentError('Must not be empty', 'packageId'); } - final Map? sizeInfo = - await _channel.invokeMapMethod( + final Map? sizeInfo = await _channel.invokeMapMethod( 'getPackageSizeInfo', {'packageId': packageId}, ); diff --git a/packages/tizen_rpc_port/CHANGELOG.md b/packages/tizen_rpc_port/CHANGELOG.md index 2d5430320..a6c1d17c0 100644 --- a/packages/tizen_rpc_port/CHANGELOG.md +++ b/packages/tizen_rpc_port/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 0.1.8 * Update analysis_options.yaml for Flutter 3.47.0. diff --git a/packages/tizen_rpc_port/example/client/integration_test/tizen_rpc_port_test.dart b/packages/tizen_rpc_port/example/client/integration_test/tizen_rpc_port_test.dart index d9d956dfa..7a7db66ce 100644 --- a/packages/tizen_rpc_port/example/client/integration_test/tizen_rpc_port_test.dart +++ b/packages/tizen_rpc_port/example/client/integration_test/tizen_rpc_port_test.dart @@ -44,7 +44,7 @@ void main() { // --------------------------------------------------------------------------- test('Parcel test', () async { - final Parcel parcel = Parcel(); + final parcel = Parcel(); parcel.writeBool(false); parcel.writeInt32(123); parcel.writeString('Hello'); @@ -65,25 +65,25 @@ void main() { group('Parcel', () { group('writeInt16 / readInt16', () { test('round-trips positive value', () async { - final Parcel parcel = Parcel(); + final parcel = Parcel(); parcel.writeInt16(32767); expect(parcel.readInt16(), 32767); }); test('round-trips negative value', () async { - final Parcel parcel = Parcel(); + final parcel = Parcel(); parcel.writeInt16(-1); expect(parcel.readInt16(), -1); }); test('round-trips minimum value', () async { - final Parcel parcel = Parcel(); + final parcel = Parcel(); parcel.writeInt16(-32768); expect(parcel.readInt16(), -32768); }); test('masks value to 16 bits', () async { - final Parcel parcel = Parcel(); + final parcel = Parcel(); // 0x10042 & 0xffff == 0x0042 == 66 parcel.writeInt16(0x10042); expect(parcel.readInt16(), 66); @@ -92,22 +92,22 @@ void main() { group('writeInt64 / readInt64', () { test('round-trips large positive value', () async { - final Parcel parcel = Parcel(); - const int value = 9007199254740992; // 2^53 + final parcel = Parcel(); + const value = 9007199254740992; // 2^53 parcel.writeInt64(value); expect(parcel.readInt64(), value); }); test('round-trips maximum value', () async { - final Parcel parcel = Parcel(); - const int value = 9223372036854775807; // int64 max + final parcel = Parcel(); + const value = 9223372036854775807; // int64 max parcel.writeInt64(value); expect(parcel.readInt64(), value); }); test('round-trips minimum value', () async { - final Parcel parcel = Parcel(); - const int value = -9223372036854775808; // int64 min + final parcel = Parcel(); + const value = -9223372036854775808; // int64 min parcel.writeInt64(value); expect(parcel.readInt64(), value); }); @@ -115,26 +115,26 @@ void main() { group('writeByte / readByte', () { test('round-trips a value', () async { - final Parcel parcel = Parcel(); + final parcel = Parcel(); parcel.writeByte(0xab); expect(parcel.readByte(), 0xab); }); test('round-trips maximum unsigned value', () async { - final Parcel parcel = Parcel(); + final parcel = Parcel(); parcel.writeByte(255); expect(parcel.readByte(), 255); }); test('reads a negative input back as an unsigned byte', () async { - final Parcel parcel = Parcel(); + final parcel = Parcel(); // -1 is written as 0xff and must read back as the unsigned byte 255. parcel.writeByte(-1); expect(parcel.readByte(), 255); }); test('masks value to 8 bits', () async { - final Parcel parcel = Parcel(); + final parcel = Parcel(); // 0x142 & 0xff == 0x42 == 66 parcel.writeByte(0x142); expect(parcel.readByte(), 66); @@ -143,7 +143,7 @@ void main() { group('writeArrayCount / readArrayCount', () { test('round-trips a count', () async { - final Parcel parcel = Parcel(); + final parcel = Parcel(); parcel.writeArrayCount(42); expect(parcel.readArrayCount(), 42); }); @@ -151,8 +151,8 @@ void main() { group('write / read (burst byte array)', () { test('round-trips byte array', () async { - final Parcel parcel = Parcel(); - final Uint8List bytes = Uint8List.fromList([ + final parcel = Parcel(); + final bytes = Uint8List.fromList([ 0x00, 0x01, 0x7f, @@ -167,13 +167,13 @@ void main() { group('Parcel.fromRaw', () { test('reconstructed parcel reads back original values', () async { - final Parcel original = Parcel(); + final original = Parcel(); original.writeInt32(99); original.writeString('raw'); original.writeBool(true); final Uint8List raw = original.asRaw(); - final Parcel restored = Parcel.fromRaw(raw); + final restored = Parcel.fromRaw(raw); expect(restored.readInt32(), 99); expect(restored.readString(), 'raw'); @@ -183,11 +183,11 @@ void main() { group('writeBundle / readBundle', () { test('round-trips a Bundle with string entries', () async { - final Bundle bundle = Bundle(); + final bundle = Bundle(); bundle['key1'] = 'value1'; bundle['key2'] = 'value2'; - final Parcel parcel = Parcel(); + final parcel = Parcel(); parcel.writeBundle(bundle); final Bundle restored = parcel.readBundle(); @@ -196,7 +196,7 @@ void main() { }); test('round-trips an empty Bundle', () async { - final Parcel parcel = Parcel(); + final parcel = Parcel(); parcel.writeBundle(Bundle()); final Bundle restored = parcel.readBundle(); expect(restored.length, 0); @@ -205,32 +205,32 @@ void main() { group('header', () { test('tag can be set and retrieved', () async { - final Parcel parcel = Parcel(); + final parcel = Parcel(); final ParcelHeader header = parcel.header; header.tag = '1.2.3'; expect(parcel.header.tag, '1.2.3'); }); test('sequenceNumber can be set and retrieved', () async { - final Parcel parcel = Parcel(); + final parcel = Parcel(); final ParcelHeader header = parcel.header; header.sequenceNumber = 7; expect(parcel.header.sequenceNumber, 7); }); test('tag defaults to empty string', () async { - final Parcel parcel = Parcel(); + final parcel = Parcel(); expect(parcel.header.tag, isEmpty); }); }); group('Parcelable', () { test('custom Parcelable serializes and deserializes correctly', () async { - final Parcel parcel = Parcel(); - final _Point original = _Point(x: 10, y: 20); + final parcel = Parcel(); + final original = _Point(x: 10, y: 20); original.serialize(parcel); - final _Point restored = _Point(); + final restored = _Point(); restored.deserialize(parcel); expect(restored.x, 10); expect(restored.y, 20); @@ -257,12 +257,12 @@ void main() { group('ProxyBase', () { test('isConnected is false before connecting', () async { - final _TestProxy proxy = _TestProxy(); + final proxy = _TestProxy(); expect(proxy.isConnected, isFalse); }); test('appid and portName are set from constructor', () async { - final _TestProxy proxy = _TestProxy(); + final proxy = _TestProxy(); expect(proxy.appid, 'org.tizen.nonexistent_app_for_rpc_test'); expect(proxy.portName, 'TestPort'); }); @@ -274,7 +274,7 @@ void main() { group('Tizen 10.0+ Parcel APIs', () { test('reader getter/setter', () async { - final Parcel parcel = Parcel(); + final parcel = Parcel(); try { parcel.reader = 10; expect(parcel.reader, 10); @@ -284,7 +284,7 @@ void main() { }); test('dataSize getter/setter', () async { - final Parcel parcel = Parcel(); + final parcel = Parcel(); try { parcel.dataSize = 20; expect(parcel.dataSize, 20); @@ -294,7 +294,7 @@ void main() { }); test('reserve', () async { - final Parcel parcel = Parcel(); + final parcel = Parcel(); try { parcel.reserve(100); } on UnsupportedError catch (e) { diff --git a/packages/tizen_rpc_port/example/client/lib/message_client.dart b/packages/tizen_rpc_port/example/client/lib/message_client.dart index af665625e..9f762ba68 100644 --- a/packages/tizen_rpc_port/example/client/lib/message_client.dart +++ b/packages/tizen_rpc_port/example/client/lib/message_client.dart @@ -110,7 +110,7 @@ class Message extends ProxyBase { } final Port port = getPort(PortType.main); - final Parcel parcel = Parcel(); + final parcel = Parcel(); final ParcelHeader header = parcel.header; header.tag = _tidlVersion; parcel.writeInt32(_MethodId.register.id); @@ -118,7 +118,7 @@ class Message extends ProxyBase { parcel.writeString(name); { - final _NotifyCallback delegate = _NotifyCallback(callback); + final delegate = _NotifyCallback(callback); delegate.serialize(parcel); _delegates.add(delegate); } @@ -151,7 +151,7 @@ class Message extends ProxyBase { } final Port port = getPort(PortType.main); - final Parcel parcel = Parcel(); + final parcel = Parcel(); final ParcelHeader header = parcel.header; header.tag = _tidlVersion; parcel.writeInt32(_MethodId.unregister.id); @@ -165,7 +165,7 @@ class Message extends ProxyBase { } final Port port = getPort(PortType.main); - final Parcel parcel = Parcel(); + final parcel = Parcel(); final ParcelHeader header = parcel.header; header.tag = _tidlVersion; parcel.writeInt32(_MethodId.send.id); diff --git a/packages/tizen_rpc_port/example/server/integration_test/tizen_rpc_port_test.dart b/packages/tizen_rpc_port/example/server/integration_test/tizen_rpc_port_test.dart index 2abd8d475..1c799b5a1 100644 --- a/packages/tizen_rpc_port/example/server/integration_test/tizen_rpc_port_test.dart +++ b/packages/tizen_rpc_port/example/server/integration_test/tizen_rpc_port_test.dart @@ -40,18 +40,18 @@ void main() { group('StubBase', () { test('portName is set from constructor', () async { - final _TestStub stub = _TestStub(); + final stub = _TestStub(); expect(stub.portName, 'TestStubPort'); }); test('setTrusted can be called without listen', () async { - final _TestStub stub = _TestStub(); + final stub = _TestStub(); stub.setTrusted(true); stub.setTrusted(false); }); test('addPrivilege can be called without listen', () async { - final _TestStub stub = _TestStub(); + final stub = _TestStub(); stub.addPrivilege('http://tizen.org/privilege/datasharing'); }); }); @@ -62,17 +62,15 @@ void main() { group('Message', () { test('portName is Message', () async { - final Message server = Message( - serviceBuilder: (String sender, String instance) => - _NoopService(sender, instance), + final server = Message( + serviceBuilder: (String sender, String instance) => _NoopService(sender, instance), ); expect(server.portName, 'Message'); }); test('services list is initially empty', () async { - final Message server = Message( - serviceBuilder: (String sender, String instance) => - _NoopService(sender, instance), + final server = Message( + serviceBuilder: (String sender, String instance) => _NoopService(sender, instance), ); expect(server.services, isEmpty); }); diff --git a/packages/tizen_rpc_port/example/server/lib/main.dart b/packages/tizen_rpc_port/example/server/lib/main.dart index d5e171bce..785bfb5a7 100644 --- a/packages/tizen_rpc_port/example/server/lib/main.dart +++ b/packages/tizen_rpc_port/example/server/lib/main.dart @@ -64,8 +64,7 @@ class MyApp extends StatefulWidget { class _MyAppState extends State { final Message _server = Message( - serviceBuilder: (String sender, String instance) => - EchoService(sender, instance), + serviceBuilder: (String sender, String instance) => EchoService(sender, instance), ); @override diff --git a/packages/tizen_rpc_port/example/server/lib/message_server.dart b/packages/tizen_rpc_port/example/server/lib/message_server.dart index 20e94241b..a3721e8a7 100644 --- a/packages/tizen_rpc_port/example/server/lib/message_server.dart +++ b/packages/tizen_rpc_port/example/server/lib/message_server.dart @@ -89,7 +89,7 @@ class NotifyCallback extends _Delegate { throw Exception('Can be invoked only once'); } - final Parcel parcel = Parcel(); + final parcel = Parcel(); parcel.writeInt32(_MethodId.callback.id); serialize(parcel); @@ -150,12 +150,12 @@ class Message extends StubBase { Parcel parcel, ) async { final String name = parcel.readString(); - final NotifyCallback callback = NotifyCallback(service._port, service); + final callback = NotifyCallback(service._port, service); callback.deserialize(parcel); final int ret = await service.onRegister(name, callback); - final Parcel result = Parcel(); + final result = Parcel(); final ParcelHeader header = parcel.header; final ParcelHeader resultHeader = result.header; resultHeader.tag = _tidlVersion; @@ -184,7 +184,7 @@ class Message extends StubBase { final int ret = await service.onSend(message); - final Parcel result = Parcel(); + final result = Parcel(); final ParcelHeader header = parcel.header; final ParcelHeader resultHeader = result.header; resultHeader.tag = _tidlVersion; diff --git a/packages/tizen_rpc_port/lib/src/parcel.dart b/packages/tizen_rpc_port/lib/src/parcel.dart index 7c73cf864..6d960ec0b 100644 --- a/packages/tizen_rpc_port/lib/src/parcel.dart +++ b/packages/tizen_rpc_port/lib/src/parcel.dart @@ -127,7 +127,7 @@ class Parcel { Parcel.fromRaw(Uint8List rawData) { _handle = using((Arena arena) { final Pointer pRaw = arena(rawData.length); - for (int i = 0; i < rawData.length; ++i) { + for (var i = 0; i < rawData.length; ++i) { pRaw[i] = rawData[i] & _byteMax; } @@ -453,7 +453,7 @@ class Parcel { void write(Uint8List bytes) { using((Arena arena) { final Pointer pBuffer = arena(bytes.length); - for (int i = 0; i < bytes.length; ++i) { + for (var i = 0; i < bytes.length; ++i) { pBuffer[i] = bytes[i]; } final int ret = tizen.rpc_port_parcel_burst_write( @@ -488,8 +488,7 @@ class Parcel { /// Gets the reader position of this parcel. int get reader { _ensureFunctionsLoaded(); - final int Function(rpc_port_parcel_h, Pointer)? func = - _rpcPortParcelGetReader; + final int Function(rpc_port_parcel_h, Pointer)? func = _rpcPortParcelGetReader; if (func == null) { throw UnsupportedError( 'The reader property is not supported on this version of Tizen.', @@ -530,8 +529,7 @@ class Parcel { /// Gets the data size of this parcel. int get dataSize { _ensureFunctionsLoaded(); - final int Function(rpc_port_parcel_h, Pointer)? func = - _rpcPortParcelGetDataSize; + final int Function(rpc_port_parcel_h, Pointer)? func = _rpcPortParcelGetDataSize; if (func == null) { throw UnsupportedError( 'The dataSize property is not supported on this version of Tizen.', @@ -554,8 +552,7 @@ class Parcel { set dataSize(int value) { RangeError.checkNotNegative(value, 'value'); _ensureFunctionsLoaded(); - final int Function(rpc_port_parcel_h, int)? func = - _rpcPortParcelSetDataSize; + final int Function(rpc_port_parcel_h, int)? func = _rpcPortParcelSetDataSize; if (func == null) { throw UnsupportedError( 'The dataSize property is not supported on this version of Tizen.', @@ -624,8 +621,7 @@ void _ensureFunctionsLoaded() { } try { _rpcPortParcelGetReader = lib - .lookup< - NativeFunction)>>( + .lookup)>>( 'rpc_port_parcel_get_reader', ) .asFunction(); @@ -639,8 +635,7 @@ void _ensureFunctionsLoaded() { } catch (_) {} try { _rpcPortParcelGetDataSize = lib - .lookup< - NativeFunction)>>( + .lookup)>>( 'rpc_port_parcel_get_data_size', ) .asFunction(); diff --git a/packages/tizen_rpc_port/lib/src/port.dart b/packages/tizen_rpc_port/lib/src/port.dart index 5e9743a34..dc1b7c6bf 100644 --- a/packages/tizen_rpc_port/lib/src/port.dart +++ b/packages/tizen_rpc_port/lib/src/port.dart @@ -33,7 +33,7 @@ class Port { paths.length, ); - for (int i = 0; i < paths.length; ++i) { + for (var i = 0; i < paths.length; ++i) { pPaths[i] = paths[i].toNativeChar(); } diff --git a/packages/tizen_rpc_port/lib/src/proxy_base.dart b/packages/tizen_rpc_port/lib/src/proxy_base.dart index 8d80d104b..3b9174785 100644 --- a/packages/tizen_rpc_port/lib/src/proxy_base.dart +++ b/packages/tizen_rpc_port/lib/src/proxy_base.dart @@ -95,7 +95,7 @@ abstract class ProxyBase { 'portName': portName, }); - final EventChannel eventChannel = EventChannel( + final eventChannel = EventChannel( 'tizen/rpc_port_proxy/$portName/${_handle.address}', ); @@ -107,13 +107,12 @@ abstract class ProxyBase { _activeConnections.add(_handle.address); _streamSubscription = _stream!.listen((dynamic data) async { - final Map map = - (data as Map).cast(); - final int handle = map['handle'] as int; + final Map map = (data as Map).cast(); + final handle = map['handle'] as int; if (handle != _handle.address) { return; } - final String event = map['event'] as String; + final event = map['event'] as String; if (event == 'connected') { _isConnected = true; _onDisconnected = onDisconnected; @@ -129,7 +128,7 @@ abstract class ProxyBase { } } else if (event == 'rejected') { _isConnected = false; - final String error = map['error'] as String; + final error = map['error'] as String; await _onRejectedEvent(error); await _streamSubscription?.cancel(); _streamSubscription = null; @@ -138,8 +137,8 @@ abstract class ProxyBase { _stream = null; } } else if (event == 'received') { - final Uint8List rawData = map['rawData'] as Uint8List; - final Parcel parcel = Parcel.fromRaw(rawData); + final rawData = map['rawData'] as Uint8List; + final parcel = Parcel.fromRaw(rawData); await onReceivedEvent(parcel); } else { debugPrint('Unknown event: $event'); diff --git a/packages/tizen_rpc_port/lib/src/stub_base.dart b/packages/tizen_rpc_port/lib/src/stub_base.dart index 987ef918d..44eec4043 100644 --- a/packages/tizen_rpc_port/lib/src/stub_base.dart +++ b/packages/tizen_rpc_port/lib/src/stub_base.dart @@ -87,22 +87,21 @@ abstract class StubBase { {'handle': _handle.address}, ); _streamSubscription = stream.listen((dynamic data) async { - final Map map = - (data as Map).cast(); - final int handle = map['handle'] as int; + final Map map = (data as Map).cast(); + final handle = map['handle'] as int; if (handle != _handle.address) { return; } - final String event = map['event'] as String; - final String sender = map['sender'] as String; - final String instance = map['instance'] as String; + final event = map['event'] as String; + final sender = map['sender'] as String; + final instance = map['instance'] as String; if (event == 'connected') { await onConnectedEvent(sender, instance); } else if (event == 'disconnected') { await onDisconnectedEvent(sender, instance); } else if (event == 'received') { - final Uint8List rawData = map['rawData'] as Uint8List; - final Parcel parcel = Parcel.fromRaw(rawData); + final rawData = map['rawData'] as Uint8List; + final parcel = Parcel.fromRaw(rawData); await onReceivedEvent(sender, instance, parcel); } else { debugPrint('Unknown event: $event'); diff --git a/packages/tizen_window_manager/CHANGELOG.md b/packages/tizen_window_manager/CHANGELOG.md index 6d1a7f779..89406998d 100644 --- a/packages/tizen_window_manager/CHANGELOG.md +++ b/packages/tizen_window_manager/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 0.2.0 * Use the window method channel of the embedder. diff --git a/packages/tizen_window_manager/example/lib/main.dart b/packages/tizen_window_manager/example/lib/main.dart index 4ffd3f0df..4fd488f2c 100644 --- a/packages/tizen_window_manager/example/lib/main.dart +++ b/packages/tizen_window_manager/example/lib/main.dart @@ -27,15 +27,13 @@ class _MyAppState extends State { Timer? _windowTimer; void _activateWindow() { - final AppLifecycleState currentLifecycleState = - WidgetsBinding.instance.lifecycleState!; + final AppLifecycleState currentLifecycleState = WidgetsBinding.instance.lifecycleState!; if (currentLifecycleState != AppLifecycleState.resumed) { _windowTimer?.cancel(); _windowTimer = Timer.periodic(const Duration(milliseconds: 500), ( Timer timer, ) { - final AppLifecycleState? currentState = - WidgetsBinding.instance.lifecycleState; + final AppLifecycleState? currentState = WidgetsBinding.instance.lifecycleState; if (currentState == AppLifecycleState.resumed) { timer.cancel(); _windowTimer = null; @@ -47,8 +45,7 @@ class _MyAppState extends State { } }); } else { - debugPrint( - 'AppLifecycleState is resumed, no need to start periodic calls'); + debugPrint('AppLifecycleState is resumed, no need to start periodic calls'); } } @@ -127,8 +124,7 @@ class _MyAppState extends State { const SizedBox(height: 10), ElevatedButton( onPressed: _lowerWindowAndActivateWindow, - child: const Text( - 'Call lower window and call activate window 3 seconds later.'), + child: const Text('Call lower window and call activate window 3 seconds later.'), ), const SizedBox(height: 10), const Text( @@ -180,8 +176,7 @@ class _MyAppState extends State { height: 16, child: CircularProgressIndicator( strokeWidth: 2, - valueColor: - AlwaysStoppedAnimation(Colors.white), + valueColor: AlwaysStoppedAnimation(Colors.white), ), ) : const Text('Get Window Geometry'), diff --git a/packages/tizen_window_manager/lib/tizen_window_manager.dart b/packages/tizen_window_manager/lib/tizen_window_manager.dart index f25f1e875..ffe079b69 100644 --- a/packages/tizen_window_manager/lib/tizen_window_manager.dart +++ b/packages/tizen_window_manager/lib/tizen_window_manager.dart @@ -37,7 +37,6 @@ class WindowManager { if (result is Map) { return Map.from(result); } - throw Exception( - 'Unexpected result type from getGeometry: ${result.runtimeType}'); + throw Exception('Unexpected result type from getGeometry: ${result.runtimeType}'); } } diff --git a/packages/url_launcher/CHANGELOG.md b/packages/url_launcher/CHANGELOG.md index 7b72c888a..412558e7c 100644 --- a/packages/url_launcher/CHANGELOG.md +++ b/packages/url_launcher/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 2.1.7 * Add an `implements` entry to the pubspec to improve discoverability on pub.dev. diff --git a/packages/url_launcher/example/lib/main.dart b/packages/url_launcher/example/lib/main.dart index 1fc1460b2..6c4199f71 100644 --- a/packages/url_launcher/example/lib/main.dart +++ b/packages/url_launcher/example/lib/main.dart @@ -130,7 +130,7 @@ class _MyHomePageState extends State { } Future _makePhoneCall(String phoneNumber) async { - final Uri launchUri = Uri(scheme: 'tel', path: phoneNumber); + final launchUri = Uri(scheme: 'tel', path: phoneNumber); await launchUrl(launchUri); } @@ -138,7 +138,7 @@ class _MyHomePageState extends State { Widget build(BuildContext context) { // onPressed calls using this URL are not gated on a 'canLaunch' check // because the assumption is that every device can launch a web URL. - final Uri toLaunch = Uri( + final toLaunch = Uri( scheme: 'https', host: 'www.cylog.org', path: 'headers/', diff --git a/packages/video_player/CHANGELOG.md b/packages/video_player/CHANGELOG.md index fc311ac33..50c75bbbb 100644 --- a/packages/video_player/CHANGELOG.md +++ b/packages/video_player/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 2.5.15 * Update video_player to 2.14.0. diff --git a/packages/video_player/example/integration_test/video_player_test.dart b/packages/video_player/example/integration_test/video_player_test.dart index 08ac81cbc..e28e8318f 100644 --- a/packages/video_player/example/integration_test/video_player_test.dart +++ b/packages/video_player/example/integration_test/video_player_test.dart @@ -17,9 +17,7 @@ import 'package:video_player/video_player.dart'; const Duration _playDuration = Duration(seconds: 1); // Use WebM for web to allow CI to use Chromium. -const String _videoAssetKey = kIsWeb - ? 'assets/Butterfly-209.webm' - : 'assets/Butterfly-209.mp4'; +const String _videoAssetKey = kIsWeb ? 'assets/Butterfly-209.webm' : 'assets/Butterfly-209.mp4'; // Returns the URL to load an asset from this example app as a network source. // @@ -58,21 +56,15 @@ void main() { }); test('live stream duration != 0', () async { - final VideoPlayerController - networkController = VideoPlayerController.networkUrl( - Uri.parse( - 'https://flutter.github.io/assets-for-api-docs/assets/videos/hls/bee.m3u8', - ), + final networkController = VideoPlayerController.networkUrl( + Uri.parse('https://flutter.github.io/assets-for-api-docs/assets/videos/hls/bee.m3u8'), ); await networkController.initialize(); expect(networkController.value.isInitialized, true); // Live streams should have either a positive duration or C.TIME_UNSET if the duration is unknown // See https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/Player.html#getDuration-- - expect( - networkController.value.duration, - (Duration duration) => duration != Duration.zero, - ); + expect(networkController.value.duration, (Duration duration) => duration != Duration.zero); }, skip: kIsWeb); testWidgets('can be played', (WidgetTester tester) async { @@ -85,10 +77,7 @@ void main() { await tester.pumpAndSettle(_playDuration); expect(controller.value.isPlaying, true); - expect( - controller.value.position, - (Duration position) => position > Duration.zero, - ); + expect(controller.value.position, (Duration position) => position > Duration.zero); }); test('can seek', () async { @@ -137,9 +126,7 @@ void main() { // TODO(stuartmorgan): Remove once // https://github.com/flutter/flutter/issues/141145 is fixed. if ((!kIsWeb && Platform.isAndroid) && controller.value.isPlaying) { - markTestSkipped( - 'Skipping due to https://github.com/flutter/flutter/issues/141145', - ); + markTestSkipped('Skipping due to https://github.com/flutter/flutter/issues/141145'); return; } expect(controller.value.isPlaying, false); @@ -164,9 +151,7 @@ void main() { // Mute to allow playing without DOM interaction on Web. // See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes await controller.setVolume(0); - await controller.seekTo( - controller.value.duration - const Duration(milliseconds: 10), - ); + await controller.seekTo(controller.value.duration - const Duration(milliseconds: 10)); await controller.play(); await tester.pumpAndSettle(_playDuration); // Android emulators in our CI have frequent flake where the video @@ -180,9 +165,7 @@ void main() { // NOTE(jsuya): In Tizen, isPlaying returns true after the play() // call,so subsequent tests cannot be performed. if ((!kIsWeb && Platform.isAndroid) && controller.value.isPlaying) { - markTestSkipped( - 'Skipping due to https://github.com/flutter/flutter/issues/141145', - ); + markTestSkipped('Skipping due to https://github.com/flutter/flutter/issues/141145'); return; } expect(controller.value.isPlaying, false); @@ -191,10 +174,7 @@ void main() { await controller.play(); await tester.pumpAndSettle(_playDuration); - expect( - controller.value.position, - lessThanOrEqualTo(controller.value.duration), - ); + expect(controller.value.position, lessThanOrEqualTo(controller.value.duration)); }, // NOTE(jsuya): In Tizen, isPlaying returns true after the play() call. skip: true, @@ -203,7 +183,7 @@ void main() { testWidgets( 'test video player view with local asset', (WidgetTester tester) async { - final Completer loaded = Completer(); + final loaded = Completer(); Future started() async { await controller.initialize(); await controller.play(); @@ -218,17 +198,16 @@ void main() { child: Center( child: FutureBuilder( future: started(), - builder: - (BuildContext context, AsyncSnapshot snapshot) { - if (snapshot.data ?? false) { - return AspectRatio( - aspectRatio: controller.value.aspectRatio, - child: VideoPlayer(controller), - ); - } else { - return const Text('waiting for video to load'); - } - }, + builder: (BuildContext context, AsyncSnapshot snapshot) { + if (snapshot.data ?? false) { + return AspectRatio( + aspectRatio: controller.value.aspectRatio, + child: VideoPlayer(controller), + ); + } else { + return const Text('waiting for video to load'); + } + }, ), ), ), @@ -252,25 +231,21 @@ void main() { // Write it to a file to use as a source. final String filename = _videoAssetKey.split('/').last; - final File file = File('$tempDir/$filename'); + final file = File('$tempDir/$filename'); await file.writeAsBytes(bytes.buffer.asInt8List()); controller = VideoPlayerController.file(file); }); - test( - 'test video player using static file() method as constructor', - () async { - await controller.initialize(); + test('test video player using static file() method as constructor', () async { + await controller.initialize(); - await controller.play(); - expect(controller.value.isPlaying, true); + await controller.play(); + expect(controller.value.isPlaying, true); - await controller.pause(); - expect(controller.value.isPlaying, false); - }, - skip: kIsWeb, - ); + await controller.pause(); + expect(controller.value.isPlaying, false); + }, skip: kIsWeb); }); group('network videos', () { @@ -285,15 +260,13 @@ void main() { // Mute to allow playing without DOM interaction on Web. // See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes await controller.setVolume(0); - final Completer started = Completer(); - final Completer ended = Completer(); + final started = Completer(); + final ended = Completer(); controller.addListener(() { if (!started.isCompleted && controller.value.isBuffering) { started.complete(); } - if (started.isCompleted && - !controller.value.isBuffering && - !ended.isCompleted) { + if (started.isCompleted && !controller.value.isBuffering && !ended.isCompleted) { ended.complete(); } }); @@ -304,10 +277,7 @@ void main() { await controller.pause(); expect(controller.value.isPlaying, false); - expect( - controller.value.position, - (Duration position) => position > Duration.zero, - ); + expect(controller.value.position, (Duration position) => position > Duration.zero); await expectLater(started.future, completes); await expectLater(ended.future, completes); @@ -348,10 +318,7 @@ void main() { await tester.pumpAndSettle(_playDuration); expect(controller.value.isPlaying, true); - expect( - controller.value.position, - (Duration position) => position > Duration.zero, - ); + expect(controller.value.position, (Duration position) => position > Duration.zero); }); test('can seek', () async { diff --git a/packages/video_player/example/lib/main.dart b/packages/video_player/example/lib/main.dart index 08eef8440..ed3ac1bd3 100644 --- a/packages/video_player/example/lib/main.dart +++ b/packages/video_player/example/lib/main.dart @@ -76,14 +76,9 @@ class _ButterFlyAssetVideoInList extends StatelessWidget { children: [ Column( children: [ - const ListTile( - leading: Icon(Icons.cake), - title: Text('Video video'), - ), + const ListTile(leading: Icon(Icons.cake), title: Text('Video video')), Stack( - alignment: - FractionalOffset.bottomRight + - const FractionalOffset(-0.1, -0.1), + alignment: FractionalOffset.bottomRight + const FractionalOffset(-0.1, -0.1), children: [ _ButterFlyAssetVideo(), Image.asset('assets/flutter-mark-square-64.png'), @@ -116,10 +111,7 @@ class _ExampleCard extends StatelessWidget { child: Column( mainAxisSize: MainAxisSize.min, children: [ - ListTile( - leading: const Icon(Icons.airline_seat_flat_angled), - title: Text(title), - ), + ListTile(leading: const Icon(Icons.airline_seat_flat_angled), title: Text(title)), Padding( padding: const EdgeInsets.all(8.0), child: OverflowBar( @@ -213,18 +205,14 @@ class _BumbleBeeRemoteVideoState extends State<_BumbleBeeRemoteVideo> { final String fileContents = await DefaultAssetBundle.of( context, ).loadString('assets/bumble_bee_captions.vtt'); - return WebVTTCaptionFile( - fileContents, - ); // For vtt files, use WebVTTCaptionFile + return WebVTTCaptionFile(fileContents); // For vtt files, use WebVTTCaptionFile } @override void initState() { super.initState(); _controller = VideoPlayerController.networkUrl( - Uri.parse( - 'https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4', - ), + Uri.parse('https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4'), closedCaptionFile: _loadCaptions(), videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true), ); @@ -396,9 +384,7 @@ class _PlayerVideoAndPopPageState extends State<_PlayerVideoAndPopPage> { void initState() { super.initState(); - _videoPlayerController = VideoPlayerController.asset( - 'assets/Butterfly-209.mp4', - ); + _videoPlayerController = VideoPlayerController.asset('assets/Butterfly-209.mp4'); _videoPlayerController.addListener(() { if (startedPlaying && !_videoPlayerController.value.isPlaying) { Navigator.pop(context); diff --git a/packages/video_player/lib/src/messages.g.dart b/packages/video_player/lib/src/messages.g.dart index 6f1c325f1..11a7b417e 100644 --- a/packages/video_player/lib/src/messages.g.dart +++ b/packages/video_player/lib/src/messages.g.dart @@ -18,9 +18,7 @@ PlatformException _createConnectionError(String channelName) { bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed.every( - ((int, dynamic) item) => _deepEquals(item.$2, b[item.$1]), - ); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -85,10 +83,7 @@ class LoopingMessage { static LoopingMessage decode(Object result) { result as List; - return LoopingMessage( - textureId: result[0]! as int, - isLooping: result[1]! as bool, - ); + return LoopingMessage(textureId: result[0]! as int, isLooping: result[1]! as bool); } @override @@ -125,10 +120,7 @@ class VolumeMessage { static VolumeMessage decode(Object result) { result as List; - return VolumeMessage( - textureId: result[0]! as int, - volume: result[1]! as double, - ); + return VolumeMessage(textureId: result[0]! as int, volume: result[1]! as double); } @override @@ -165,10 +157,7 @@ class PlaybackSpeedMessage { static PlaybackSpeedMessage decode(Object result) { result as List; - return PlaybackSpeedMessage( - textureId: result[0]! as int, - speed: result[1]! as double, - ); + return PlaybackSpeedMessage(textureId: result[0]! as int, speed: result[1]! as double); } @override @@ -205,10 +194,7 @@ class PositionMessage { static PositionMessage decode(Object result) { result as List; - return PositionMessage( - textureId: result[0]! as int, - position: result[1]! as int, - ); + return PositionMessage(textureId: result[0]! as int, position: result[1]! as int); } @override @@ -262,8 +248,7 @@ class CreateMessage { uri: result[1] as String?, packageName: result[2] as String?, formatHint: result[3] as String?, - httpHeaders: (result[4] as Map?)! - .cast(), + httpHeaders: (result[4] as Map?)!.cast(), ); } @@ -379,13 +364,11 @@ class TizenVideoPlayerApi { /// Constructor for [TizenVideoPlayerApi]. 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. - TizenVideoPlayerApi({ - BinaryMessenger? binaryMessenger, - String messageChannelSuffix = '', - }) : pigeonVar_binaryMessenger = binaryMessenger, - pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty - ? '.$messageChannelSuffix' - : ''; + TizenVideoPlayerApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; final BinaryMessenger? pigeonVar_binaryMessenger; static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -395,15 +378,13 @@ class TizenVideoPlayerApi { Future initialize() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_tizen.TizenVideoPlayerApi.initialize$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -420,17 +401,13 @@ class TizenVideoPlayerApi { Future create(CreateMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_tizen.TizenVideoPlayerApi.create$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [msg], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -452,17 +429,13 @@ class TizenVideoPlayerApi { Future dispose(TextureMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_tizen.TizenVideoPlayerApi.dispose$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [msg], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -479,17 +452,13 @@ class TizenVideoPlayerApi { Future setLooping(LoopingMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_tizen.TizenVideoPlayerApi.setLooping$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [msg], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -506,17 +475,13 @@ class TizenVideoPlayerApi { Future setVolume(VolumeMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_tizen.TizenVideoPlayerApi.setVolume$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [msg], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -533,17 +498,13 @@ class TizenVideoPlayerApi { Future setPlaybackSpeed(PlaybackSpeedMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_tizen.TizenVideoPlayerApi.setPlaybackSpeed$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [msg], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -560,17 +521,13 @@ class TizenVideoPlayerApi { Future play(TextureMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_tizen.TizenVideoPlayerApi.play$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [msg], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -587,17 +544,13 @@ class TizenVideoPlayerApi { Future position(TextureMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_tizen.TizenVideoPlayerApi.position$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [msg], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -619,17 +572,13 @@ class TizenVideoPlayerApi { Future seekTo(PositionMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_tizen.TizenVideoPlayerApi.seekTo$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [msg], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -646,17 +595,13 @@ class TizenVideoPlayerApi { Future pause(TextureMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_tizen.TizenVideoPlayerApi.pause$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [msg], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -673,17 +618,13 @@ class TizenVideoPlayerApi { Future setMixWithOthers(MixWithOthersMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_tizen.TizenVideoPlayerApi.setMixWithOthers$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [msg], + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/video_player/lib/video_player_tizen.dart b/packages/video_player/lib/video_player_tizen.dart index cbb7157f9..0a8209623 100644 --- a/packages/video_player/lib/video_player_tizen.dart +++ b/packages/video_player/lib/video_player_tizen.dart @@ -40,7 +40,7 @@ class VideoPlayerTizen extends platform_interface.VideoPlayerPlatform { String? packageName; String? uri; String? formatHint; - Map httpHeaders = {}; + var httpHeaders = {}; switch (dataSource.sourceType) { case platform_interface.DataSourceType.asset: asset = dataSource.asset; @@ -54,7 +54,7 @@ class VideoPlayerTizen extends platform_interface.VideoPlayerPlatform { case platform_interface.DataSourceType.contentUri: uri = dataSource.uri; } - final CreateMessage message = CreateMessage( + final message = CreateMessage( asset: asset, packageName: packageName, uri: uri, @@ -68,9 +68,7 @@ class VideoPlayerTizen extends platform_interface.VideoPlayerPlatform { @override Future setLooping(int textureId, bool looping) { - return _api.setLooping( - LoopingMessage(textureId: textureId, isLooping: looping), - ); + return _api.setLooping(LoopingMessage(textureId: textureId, isLooping: looping)); } @override @@ -92,32 +90,24 @@ class VideoPlayerTizen extends platform_interface.VideoPlayerPlatform { Future setPlaybackSpeed(int textureId, double speed) { assert(speed > 0); - return _api.setPlaybackSpeed( - PlaybackSpeedMessage(textureId: textureId, speed: speed), - ); + return _api.setPlaybackSpeed(PlaybackSpeedMessage(textureId: textureId, speed: speed)); } @override Future seekTo(int textureId, Duration position) { - return _api.seekTo( - PositionMessage(textureId: textureId, position: position.inMilliseconds), - ); + return _api.seekTo(PositionMessage(textureId: textureId, position: position.inMilliseconds)); } @override Future getPosition(int textureId) async { - final PositionMessage response = await _api.position( - TextureMessage(textureId: textureId), - ); + final PositionMessage response = await _api.position(TextureMessage(textureId: textureId)); return Duration(milliseconds: response.position); } @override Stream videoEventsFor(int textureId) { - return _eventChannelFor(textureId).receiveBroadcastStream().map(( - dynamic event, - ) { - final Map map = event as Map; + return _eventChannelFor(textureId).receiveBroadcastStream().map((dynamic event) { + final map = event as Map; switch (map['event']) { case 'initialized': return platform_interface.VideoEvent( @@ -134,12 +124,10 @@ class VideoPlayerTizen extends platform_interface.VideoPlayerPlatform { eventType: platform_interface.VideoEventType.completed, ); case 'bufferingUpdate': - final List values = map['values'] as List; + final values = map['values'] as List; return platform_interface.VideoEvent( - buffered: values - .map(_toDurationRange) - .toList(), + buffered: values.map(_toDurationRange).toList(), eventType: platform_interface.VideoEventType.bufferingUpdate, ); case 'bufferingStart': @@ -170,25 +158,23 @@ class VideoPlayerTizen extends platform_interface.VideoPlayerPlatform { @override Future setMixWithOthers(bool mixWithOthers) { - return _api.setMixWithOthers( - MixWithOthersMessage(mixWithOthers: mixWithOthers), - ); + return _api.setMixWithOthers(MixWithOthersMessage(mixWithOthers: mixWithOthers)); } EventChannel _eventChannelFor(int textureId) { return EventChannel('flutter.io/videoPlayer/videoEvents$textureId'); } - static const Map - _videoFormatStringMap = { - platform_interface.VideoFormat.ss: 'ss', - platform_interface.VideoFormat.hls: 'hls', - platform_interface.VideoFormat.dash: 'dash', - platform_interface.VideoFormat.other: 'other', - }; + static const Map _videoFormatStringMap = + { + platform_interface.VideoFormat.ss: 'ss', + platform_interface.VideoFormat.hls: 'hls', + platform_interface.VideoFormat.dash: 'dash', + platform_interface.VideoFormat.other: 'other', + }; platform_interface.DurationRange _toDurationRange(dynamic value) { - final List pair = value as List; + final pair = value as List; return platform_interface.DurationRange( Duration(milliseconds: pair[0] as int), Duration(milliseconds: pair[1] as int), diff --git a/packages/video_player_avplay/CHANGELOG.md b/packages/video_player_avplay/CHANGELOG.md index 377203b7d..3d3cf2fca 100644 --- a/packages/video_player_avplay/CHANGELOG.md +++ b/packages/video_player_avplay/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 0.8.18 * Replace ecore-wl2 code with tizen window manager plugin. diff --git a/packages/video_player_avplay/example/integration_test/video_player_test.dart b/packages/video_player_avplay/example/integration_test/video_player_test.dart index 61b942bbb..237f13625 100644 --- a/packages/video_player_avplay/example/integration_test/video_player_test.dart +++ b/packages/video_player_avplay/example/integration_test/video_player_test.dart @@ -16,8 +16,7 @@ import 'package:video_player_avplay/video_player.dart'; const Duration _playDuration = Duration(seconds: 1); // Use WebM for web to allow CI to use Chromium. -const String _videoAssetKey = - kIsWeb ? 'assets/Butterfly-209.webm' : 'assets/Butterfly-209.mp4'; +const String _videoAssetKey = kIsWeb ? 'assets/Butterfly-209.webm' : 'assets/Butterfly-209.mp4'; // Returns the URL to load an asset from this example app as a network source. String getUrlForAssetAsNetworkSource(String assetKey) { @@ -53,8 +52,7 @@ void main() { }); testWidgets('live stream duration != 0', (WidgetTester tester) async { - final VideoPlayerController networkController = - VideoPlayerController.network( + final networkController = VideoPlayerController.network( 'https://flutter.github.io/assets-for-api-docs/assets/videos/hls/bee.m3u8', ); await networkController.initialize(); @@ -208,7 +206,7 @@ void main() { // Write it to a file to use as a source. final String filename = _videoAssetKey.split('/').last; - final File file = File('$tempDir/$filename'); + final file = File('$tempDir/$filename'); await file.writeAsBytes(bytes.buffer.asInt8List()); controller = VideoPlayerController.file(file); @@ -241,15 +239,13 @@ void main() { // Mute to allow playing without DOM interaction on Web. // See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes await controller.setVolume(0); - final Completer started = Completer(); - final Completer ended = Completer(); + final started = Completer(); + final ended = Completer(); controller.addListener(() { if (!started.isCompleted && controller.value.isBuffering) { started.complete(); } - if (started.isCompleted && - !controller.value.isBuffering && - !ended.isCompleted) { + if (started.isCompleted && !controller.value.isBuffering && !ended.isCompleted) { ended.complete(); } }); diff --git a/packages/video_player_avplay/example/lib/main.dart b/packages/video_player_avplay/example/lib/main.dart index e75f0fba2..cfc07afde 100644 --- a/packages/video_player_avplay/example/lib/main.dart +++ b/packages/video_player_avplay/example/lib/main.dart @@ -70,8 +70,7 @@ class _HlsRomoteVideo extends StatefulWidget { class _HlsRomoteVideoState extends State<_HlsRomoteVideo> { late VideoPlayerController _controller; // Optional - final Map _streamingProperties = - { + final Map _streamingProperties = { StreamingPropertyType.adaptiveInfo: 'STARTBITRATE=460560', StreamingPropertyType.setAbr: '0', }; @@ -142,8 +141,7 @@ class _DashRomoteVideo extends StatefulWidget { class _DashRomoteVideoState extends State<_DashRomoteVideo> { late VideoPlayerController _controller; // Optional - final Map _streamingProperties = - { + final Map _streamingProperties = { /// You can set multiple parameters at once, please separate them with ";". StreamingPropertyType.adaptiveInfo: 'MAX_RESOLUTION=3840X2160;MAX_FRAMERATE=60;UPDATE_SAME_LANGUAGE_CODE=1;OPEN_SUBTITLE_STYLE=TRUE', @@ -182,8 +180,7 @@ class _DashRomoteVideoState extends State<_DashRomoteVideo> { _controller.updateDashToken('YWJyVHlwZT1CUi1BVkMtREFTSC'); // New features: get the following properties. _controller.getStreamingProperty(StreamingPropertyType.audioStreamInfo); - _controller - .getStreamingProperty(StreamingPropertyType.subtitleStreamInfo); + _controller.getStreamingProperty(StreamingPropertyType.subtitleStreamInfo); _controller.getStreamingProperty(StreamingPropertyType.videoStreamInfo); _controller.getData({DashPlayerProperty.httpHeader}); }); @@ -198,8 +195,7 @@ class _DashRomoteVideoState extends State<_DashRomoteVideo> { @override Widget build(BuildContext context) { - const TextStyle customTextStyle = - TextStyle(fontSize: 30, color: Colors.green); + const customTextStyle = TextStyle(fontSize: 30, color: Colors.green); return SingleChildScrollView( child: Column( children: [ @@ -214,8 +210,7 @@ class _DashRomoteVideoState extends State<_DashRomoteVideo> { children: [ VideoPlayer(_controller), ClosedCaption( - captions: _controller.value.captions, - customTextStyle: customTextStyle), + captions: _controller.value.captions, customTextStyle: customTextStyle), _ControlsOverlay(controller: _controller), VideoProgressIndicator(_controller, allowScrubbing: true), ], @@ -376,8 +371,7 @@ class _DrmRemoteVideoState2 extends State<_DrmRemoteVideo2> { 'https://test.playready.microsoft.com/smoothstreaming/SSWSS720H264PR/SuperSpeedway_720.ism/Manifest', drmConfigs: const DrmConfigs( type: DrmType.playready, - licenseServerUrl: - 'https://test.playready.microsoft.com/service/rightsmanager.asmx', + licenseServerUrl: 'https://test.playready.microsoft.com/service/rightsmanager.asmx', ), ); @@ -896,7 +890,7 @@ class _TestRemoteVideoState extends State<_TestRemoteVideo> { } DataSource restoreDataSource() { - final DataSource dataSource = DataSource( + final dataSource = DataSource( sourceType: DataSourceType.network, uri: 'https://media.w3.org/2010/05/bunny/trailer.mp4', ); @@ -906,7 +900,7 @@ class _TestRemoteVideoState extends State<_TestRemoteVideo> { int restoreTime() { /// if resumeTime >= 0 , it will restore from resumeTime /// if resumeTime is not set or <0, it will restore from the time when suspend is called - const int resumeTime = 0; + const resumeTime = 0; return resumeTime; } diff --git a/packages/video_player_avplay/lib/src/ad_info_from_dash.dart b/packages/video_player_avplay/lib/src/ad_info_from_dash.dart index 7ad30f84d..7c43201a6 100755 --- a/packages/video_player_avplay/lib/src/ad_info_from_dash.dart +++ b/packages/video_player_avplay/lib/src/ad_info_from_dash.dart @@ -39,13 +39,12 @@ class AdInfoFromDash { /// Parse the ad information from a map. Returns null if the map is null or empty. Otherwise, returns a new instance of [AdInfoFromDash]. static AdInfoFromDash? fromAdInfoMap(Map? adInfo) { if (adInfo?.isNotEmpty ?? false) { - final int adId = adInfo!['id']! as int; - final int startTime = adInfo['start_ms']! as int; - final int endTime = adInfo['end_ms']! as int; - final int durationTime = adInfo['duration_ms']! as int; - final int outOfNetworkIndicator = - adInfo['out_of_network_indicator']! as int; - final bool cancelIndicator = adInfo['cancel_indicator']! as bool; + final adId = adInfo!['id']! as int; + final startTime = adInfo['start_ms']! as int; + final endTime = adInfo['end_ms']! as int; + final durationTime = adInfo['duration_ms']! as int; + final outOfNetworkIndicator = adInfo['out_of_network_indicator']! as int; + final cancelIndicator = adInfo['cancel_indicator']! as bool; return AdInfoFromDash( adId: adId, @@ -83,6 +82,6 @@ class AdInfoFromDash { outOfNetworkIndicator == other.outOfNetworkIndicator; @override - int get hashCode => Object.hash(adId, cancelIndicator, startTime, endTime, - durationTime, outOfNetworkIndicator); + int get hashCode => + Object.hash(adId, cancelIndicator, startTime, endTime, durationTime, outOfNetworkIndicator); } diff --git a/packages/video_player_avplay/lib/src/closed_caption_file.dart b/packages/video_player_avplay/lib/src/closed_caption_file.dart index 1d844d4e2..3a2ff0668 100644 --- a/packages/video_player_avplay/lib/src/closed_caption_file.dart +++ b/packages/video_player_avplay/lib/src/closed_caption_file.dart @@ -3,8 +3,7 @@ // found in the LICENSE file. import 'dart:typed_data' show Uint8List; -import 'package:flutter/foundation.dart' - show immutable, listEquals, objectRuntimeType; +import 'package:flutter/foundation.dart' show immutable, listEquals, objectRuntimeType; import 'package:flutter/material.dart'; import '../video_player_platform_interface.dart'; @@ -157,22 +156,14 @@ class TextCaption extends Caption { } /// Process subtitle attributes and return the text alignment and text style. - static ( - TextOriginAndExtent?, - TextStyle?, - AlignmentGeometry, - Color, - double, - Paint - ) processSubtitleAttributes(List subtitleAttributes) { + static (TextOriginAndExtent?, TextStyle?, AlignmentGeometry, Color, double, Paint) + processSubtitleAttributes(List subtitleAttributes) { TextOriginAndExtent actualTextOriginAndExtent = TextOriginAndExtent.none; - TextStyle actualTextStyle = - const TextStyle(height: 1.0, fontSize: 1 / 15.0); + var actualTextStyle = const TextStyle(height: 1.0, fontSize: 1 / 15.0); AlignmentGeometry actualTextAlign = Alignment.center; - Color actualWindowBgColor = - const Color(0x00000000); // default transparent color. + var actualWindowBgColor = const Color(0x00000000); // default transparent color. double actualFontSize = 1 / 15.0; - Paint foreground = Paint()..style = PaintingStyle.stroke; + var foreground = Paint()..style = PaintingStyle.stroke; if (subtitleAttributes.isEmpty) { return ( @@ -185,60 +176,54 @@ class TextCaption extends Caption { ); } - for (final SubtitleAttribute attr in subtitleAttributes) { + for (final attr in subtitleAttributes) { switch (attr.attrType) { // For text origin and extent. case SubtitleAttrType.subAttrRegionXPos: - final double xPos = attr.attrValue as double; + final xPos = attr.attrValue as double; if (xPos > 0) { - actualTextOriginAndExtent = - actualTextOriginAndExtent.addValue(originX: xPos); + actualTextOriginAndExtent = actualTextOriginAndExtent.addValue(originX: xPos); } case SubtitleAttrType.subAttrRegionYPos: - final double yPos = attr.attrValue as double; + final yPos = attr.attrValue as double; if (yPos > 0) { - actualTextOriginAndExtent = - actualTextOriginAndExtent.addValue(originY: yPos); + actualTextOriginAndExtent = actualTextOriginAndExtent.addValue(originY: yPos); } case SubtitleAttrType.subAttrRegionWidth: - final double width = attr.attrValue as double; + final width = attr.attrValue as double; if (width > 0) { - actualTextOriginAndExtent = - actualTextOriginAndExtent.addValue(extentWidth: width); + actualTextOriginAndExtent = actualTextOriginAndExtent.addValue(extentWidth: width); } case SubtitleAttrType.subAttrRegionHeight: - final double height = attr.attrValue as double; + final height = attr.attrValue as double; if (height > 0) { - actualTextOriginAndExtent = - actualTextOriginAndExtent.addValue(extentHeight: height); + actualTextOriginAndExtent = actualTextOriginAndExtent.addValue(extentHeight: height); } // For text style. case SubtitleAttrType.subAttrFontFamily: - actualTextStyle = - actualTextStyle.copyWith(fontFamily: attr.attrValue as String); + actualTextStyle = actualTextStyle.copyWith(fontFamily: attr.attrValue as String); case SubtitleAttrType.subAttrFontSize: - final double fontSize = attr.attrValue as double; + final fontSize = attr.attrValue as double; if (fontSize > 0) { actualFontSize = fontSize; } case SubtitleAttrType.subAttrFontWeight: - actualTextStyle = actualTextStyle.copyWith( - fontWeight: _intToFontWeight(attr.attrValue as int)); + actualTextStyle = + actualTextStyle.copyWith(fontWeight: _intToFontWeight(attr.attrValue as int)); case SubtitleAttrType.subAttrFontStyle: - actualTextStyle = actualTextStyle.copyWith( - fontStyle: _intToFontStyle(attr.attrValue as int)); + actualTextStyle = + actualTextStyle.copyWith(fontStyle: _intToFontStyle(attr.attrValue as int)); case SubtitleAttrType.subAttrFontColor: if (actualTextStyle.foreground == null) { - actualTextStyle = actualTextStyle.copyWith( - color: _intToColor(attr.attrValue as int)); + actualTextStyle = actualTextStyle.copyWith(color: _intToColor(attr.attrValue as int)); } case SubtitleAttrType.subAttrFontBgColor: if (actualTextStyle.background == null) { - actualTextStyle = actualTextStyle.copyWith( - backgroundColor: _intToColor(attr.attrValue as int)); + actualTextStyle = + actualTextStyle.copyWith(backgroundColor: _intToColor(attr.attrValue as int)); } case SubtitleAttrType.subAttrFontOpacity: - final double fontOpacity = attr.attrValue as double; + final fontOpacity = attr.attrValue as double; if (fontOpacity >= 0.0 && fontOpacity <= 1.0) { if (actualTextStyle.color == null) { actualTextStyle = actualTextStyle.copyWith(color: Colors.white); @@ -247,29 +232,25 @@ class TextCaption extends Caption { color: actualTextStyle.color!.withValues(alpha: fontOpacity)); } case SubtitleAttrType.subAttrFontBgOpacity: - final double fontBgOpacity = attr.attrValue as double; + final fontBgOpacity = attr.attrValue as double; if (fontBgOpacity >= 0.0 && fontBgOpacity <= 1.0 && actualTextStyle.backgroundColor != null) { actualTextStyle = actualTextStyle.copyWith( - backgroundColor: actualTextStyle.backgroundColor! - .withValues(alpha: fontBgOpacity)); + backgroundColor: actualTextStyle.backgroundColor!.withValues(alpha: fontBgOpacity)); } // For text vertical and horizontal align. case SubtitleAttrType.subAttrFontVerticalAlign: - actualTextAlign = actualTextAlign - .add(_intToTextVerticalAlign(attr.attrValue as int)); + actualTextAlign = actualTextAlign.add(_intToTextVerticalAlign(attr.attrValue as int)); case SubtitleAttrType.subAttrFontHorizontalAlign: - actualTextAlign = actualTextAlign - .add(_intToTextHorizontalAlign(attr.attrValue as int)); + actualTextAlign = actualTextAlign.add(_intToTextHorizontalAlign(attr.attrValue as int)); // For text background window. case SubtitleAttrType.subAttrWindowBgColor: actualWindowBgColor = _intToColor(attr.attrValue as int); case SubtitleAttrType.subAttrWindowOpacity: - final double windowOpacity = attr.attrValue as double; + final windowOpacity = attr.attrValue as double; if (windowOpacity >= 0.0 && windowOpacity <= 1.0) { - actualWindowBgColor = - actualWindowBgColor.withValues(alpha: windowOpacity); + actualWindowBgColor = actualWindowBgColor.withValues(alpha: windowOpacity); } // For text outline. case SubtitleAttrType.subAttrFontTextOutlineColor: @@ -300,12 +281,8 @@ class TextCaption extends Caption { } } return ( - actualTextOriginAndExtent == TextOriginAndExtent.none - ? null - : actualTextOriginAndExtent, - actualTextStyle == const TextStyle(height: 1.0, fontSize: 1 / 15.0) - ? null - : actualTextStyle, + actualTextOriginAndExtent == TextOriginAndExtent.none ? null : actualTextOriginAndExtent, + actualTextStyle == const TextStyle(height: 1.0, fontSize: 1 / 15.0) ? null : actualTextStyle, actualTextAlign, actualWindowBgColor, actualFontSize, @@ -337,8 +314,7 @@ class TextCaption extends Caption { textStyle == other.textStyle; @override - int get hashCode => - Object.hash(number, start, end, text, subtitleAttributes, textStyle); + int get hashCode => Object.hash(number, start, end, text, subtitleAttributes, textStyle); } /// A representation of a picture-based caption. @@ -397,8 +373,7 @@ class PictureCaption extends Caption { pictureHeight == other.pictureHeight; @override - int get hashCode => - Object.hash(number, start, end, picture, pictureWidth, pictureHeight); + int get hashCode => Object.hash(number, start, end, picture, pictureWidth, pictureHeight); } /// This attribute defines the upper-left corner of a rectangular region using [originX] and [originY] coordinate values @@ -408,10 +383,7 @@ class PictureCaption extends Caption { class TextOriginAndExtent { /// Creates a new [TextOriginAndExtent] object. const TextOriginAndExtent( - {required this.originX, - required this.originY, - this.extentWidth, - this.extentHeight}); + {required this.originX, required this.originY, this.extentWidth, this.extentHeight}); /// The x-coordinate of the upper-left corner of the rectangular region. final double originX; @@ -427,10 +399,7 @@ class TextOriginAndExtent { /// Adds values to the current [TextOriginAndExtent] object. TextOriginAndExtent addValue( - {double? originX, - double? originY, - double? extentWidth, - double? extentHeight}) { + {double? originX, double? originY, double? extentWidth, double? extentHeight}) { return TextOriginAndExtent( originX: originX ?? this.originX, originY: originY ?? this.originY, @@ -439,8 +408,8 @@ class TextOriginAndExtent { } /// A no text origin and extent object. This is a caption with [originX], [originY], [extentWidth], and [extentHeight] of zero. - static const TextOriginAndExtent none = TextOriginAndExtent( - originX: 0.0, originY: 0.0, extentWidth: 0.0, extentHeight: 0.0); + static const TextOriginAndExtent none = + TextOriginAndExtent(originX: 0.0, originY: 0.0, extentWidth: 0.0, extentHeight: 0.0); @override bool operator ==(Object other) => @@ -635,25 +604,22 @@ class SubtitleAttribute { static List fromEventSubtitleAttrList( List? eventSubtitleAttrList, ) { - final List subtitleAttributes = []; + final subtitleAttributes = []; final List?> subtitleAttrList = eventSubtitleAttrList!.cast?>(); - for (final Map? attr in subtitleAttrList) { + for (final attr in subtitleAttrList) { if (attr != null && attr['attrType'] != null) { - final int attrTypeNum = attr['attrType']! as int; - final int startTime = attr['startTime']! as int; - final int stopTime = attr['stopTime']! as int; + final attrTypeNum = attr['attrType']! as int; + final startTime = attr['startTime']! as int; + final stopTime = attr['stopTime']! as int; Object attrValue; - if (SubtitleAttrType.getValueType(attrTypeNum) == - SubtitleAttrValueType.double) { + if (SubtitleAttrType.getValueType(attrTypeNum) == SubtitleAttrValueType.double) { attrValue = attr['attrValue']! as double; - } else if (SubtitleAttrType.getValueType(attrTypeNum) == - SubtitleAttrValueType.int) { + } else if (SubtitleAttrType.getValueType(attrTypeNum) == SubtitleAttrValueType.int) { attrValue = attr['attrValue']! as int; - } else if (SubtitleAttrType.getValueType(attrTypeNum) == - SubtitleAttrValueType.string) { + } else if (SubtitleAttrType.getValueType(attrTypeNum) == SubtitleAttrValueType.string) { attrValue = attr['attrValue']! as String; } else { attrValue = 'failed'; @@ -714,13 +680,12 @@ class Captions { final PictureCaption? pictureCaption; /// Parses a subtitle from a [VideoEvent.subtitlesInfo] into a [Captions] object. - static Captions? parseSubtitle( - Duration position, SubtitlesInfo subtitlesInfo) { + static Captions? parseSubtitle(Duration position, SubtitlesInfo subtitlesInfo) { final Duration textDuration = subtitlesInfo.textDuration == 0 ? Duration.zero : Duration(milliseconds: subtitlesInfo.textDuration!); if (subtitlesInfo.pictureInfo?.isNotEmpty ?? false) { - final PictureCaption pictureCaption = PictureCaption( + final pictureCaption = PictureCaption( number: 0, start: position, end: position + textDuration, @@ -729,22 +694,18 @@ class Captions { pictureHeight: subtitlesInfo.pictureInfo!['pictureHeight'] as double?, ); return Captions( - textCaptions: const [TextCaption.none], - pictureCaption: pictureCaption); + textCaptions: const [TextCaption.none], pictureCaption: pictureCaption); } else { - final int textLines = (subtitlesInfo.textsInfo == null || - subtitlesInfo.textsInfo![0] == null) + final int textLines = (subtitlesInfo.textsInfo == null || subtitlesInfo.textsInfo![0] == null) ? 0 : subtitlesInfo.textsInfo!.length; if (textLines > 0) { - final List textCaptions = []; - for (int i = 0; i < textLines; i++) { - final Map textInfo = - subtitlesInfo.textsInfo![i] as Map; - final String? text = textInfo['text'] as String?; - final List? subtitleAttrList = - textInfo['attributes'] as List?; + final textCaptions = []; + for (var i = 0; i < textLines; i++) { + final textInfo = subtitlesInfo.textsInfo![i] as Map; + final text = textInfo['text'] as String?; + final subtitleAttrList = textInfo['attributes'] as List?; final List subtitleAttributes = SubtitleAttribute.fromEventSubtitleAttrList(subtitleAttrList); @@ -756,17 +717,15 @@ class Captions { Color, double, Paint - ) subtitleAttr = - TextCaption.processSubtitleAttributes(subtitleAttributes); - final TextOriginAndExtent? actualTextOriginAndExtent = - subtitleAttr.$1; + ) subtitleAttr = TextCaption.processSubtitleAttributes(subtitleAttributes); + final TextOriginAndExtent? actualTextOriginAndExtent = subtitleAttr.$1; final TextStyle? actualTextStyle = subtitleAttr.$2; final AlignmentGeometry actualTextAlign = subtitleAttr.$3; final Color actualWindowBgColor = subtitleAttr.$4; final double actualFontSize = subtitleAttr.$5; final Paint actualForeground = subtitleAttr.$6; - final TextCaption textCaption = TextCaption( + final textCaption = TextCaption( number: 0, start: position, end: position + textDuration, @@ -781,17 +740,15 @@ class Captions { textCaptions.add(textCaption); } - return Captions( - textCaptions: textCaptions, pictureCaption: PictureCaption.none); + return Captions(textCaptions: textCaptions, pictureCaption: PictureCaption.none); } } return null; } /// A no captions object. This is a caption with a list of [TextCaption.none] and a [PictureCaption.none]. - static const Captions none = Captions( - textCaptions: [TextCaption.none], - pictureCaption: PictureCaption.none); + static const Captions none = + Captions(textCaptions: [TextCaption.none], pictureCaption: PictureCaption.none); @override String toString() { diff --git a/packages/video_player_avplay/lib/src/hole.dart b/packages/video_player_avplay/lib/src/hole.dart index 74a4a6e6d..1b9504a59 100644 --- a/packages/video_player_avplay/lib/src/hole.dart +++ b/packages/video_player_avplay/lib/src/hole.dart @@ -55,9 +55,9 @@ class _HoleLayer extends Layer { } Picture _createHolePicture(Rect holeRect) { - final PictureRecorder recorder = PictureRecorder(); - final Canvas canvas = Canvas(recorder); - final Paint paint = Paint(); + final recorder = PictureRecorder(); + final canvas = Canvas(recorder); + final paint = Paint(); paint.color = Colors.transparent; paint.blendMode = BlendMode.src; canvas.drawRect(rect, paint); diff --git a/packages/video_player_avplay/lib/src/messages.g.dart b/packages/video_player_avplay/lib/src/messages.g.dart index e0f01d9a7..13bb91a06 100644 --- a/packages/video_player_avplay/lib/src/messages.g.dart +++ b/packages/video_player_avplay/lib/src/messages.g.dart @@ -18,8 +18,7 @@ PlatformException _createConnectionError(String channelName) { bool _deepEquals(Object? a, Object? b) { if (a is List && b is List) { return a.length == b.length && - a.indexed - .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); + a.indexed.every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { return a.length == b.length && @@ -454,16 +453,11 @@ class CreateMessage { uri: result[1] as String?, packageName: result[2] as String?, formatHint: result[3] as String?, - httpHeaders: - (result[4] as Map?)?.cast(), - drmConfigs: - (result[5] as Map?)?.cast(), - playerOptions: - (result[6] as Map?)?.cast(), - streamingProperty: - (result[7] as Map?)?.cast(), - windowGeometry: - (result[8] as Map?)?.cast(), + httpHeaders: (result[4] as Map?)?.cast(), + drmConfigs: (result[5] as Map?)?.cast(), + playerOptions: (result[6] as Map?)?.cast(), + streamingProperty: (result[7] as Map?)?.cast(), + windowGeometry: (result[8] as Map?)?.cast(), ); } @@ -664,8 +658,7 @@ class StreamingPropertyTypeMessage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! StreamingPropertyTypeMessage || - other.runtimeType != runtimeType) { + if (other is! StreamingPropertyTypeMessage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -716,8 +709,7 @@ class StreamingPropertyMessage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! StreamingPropertyMessage || - other.runtimeType != runtimeType) { + if (other is! StreamingPropertyMessage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -906,8 +898,7 @@ class DashPropertyTypeListMessage { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { - if (other is! DashPropertyTypeListMessage || - other.runtimeType != runtimeType) { + if (other is! DashPropertyTypeListMessage || other.runtimeType != runtimeType) { return false; } if (identical(this, other)) { @@ -1087,8 +1078,7 @@ class VideoPlayerAvplayApi { /// Constructor for [VideoPlayerAvplayApi]. 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. - VideoPlayerAvplayApi( - {BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) + VideoPlayerAvplayApi({BinaryMessenger? binaryMessenger, String messageChannelSuffix = ''}) : pigeonVar_binaryMessenger = binaryMessenger, pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty ? '.$messageChannelSuffix' : ''; @@ -1101,15 +1091,13 @@ class VideoPlayerAvplayApi { Future initialize() async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.initialize$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1126,16 +1114,13 @@ class VideoPlayerAvplayApi { Future create(CreateMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.create$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1157,16 +1142,13 @@ class VideoPlayerAvplayApi { Future dispose(PlayerMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.dispose$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1183,16 +1165,13 @@ class VideoPlayerAvplayApi { Future setLooping(LoopingMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.setLooping$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1209,16 +1188,13 @@ class VideoPlayerAvplayApi { Future setVolume(VolumeMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.setVolume$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1235,16 +1211,13 @@ class VideoPlayerAvplayApi { Future setPlaybackSpeed(PlaybackSpeedMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.setPlaybackSpeed$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1261,16 +1234,13 @@ class VideoPlayerAvplayApi { Future play(PlayerMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.play$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1287,16 +1257,13 @@ class VideoPlayerAvplayApi { Future setDeactivate(PlayerMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.setDeactivate$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1318,16 +1285,13 @@ class VideoPlayerAvplayApi { Future setActivate(PlayerMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.setActivate$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1349,16 +1313,13 @@ class VideoPlayerAvplayApi { Future track(TrackTypeMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.track$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1380,16 +1341,13 @@ class VideoPlayerAvplayApi { Future setTrackSelection(SelectedTracksMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.setTrackSelection$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1411,16 +1369,13 @@ class VideoPlayerAvplayApi { Future position(PlayerMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.position$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1442,16 +1397,13 @@ class VideoPlayerAvplayApi { Future duration(PlayerMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.duration$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1473,16 +1425,13 @@ class VideoPlayerAvplayApi { Future seekTo(PositionMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.seekTo$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1499,16 +1448,13 @@ class VideoPlayerAvplayApi { Future pause(PlayerMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.pause$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1525,16 +1471,13 @@ class VideoPlayerAvplayApi { Future setMixWithOthers(MixWithOthersMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.setMixWithOthers$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1551,16 +1494,13 @@ class VideoPlayerAvplayApi { Future setDisplayGeometry(GeometryMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.setDisplayGeometry$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1577,16 +1517,13 @@ class VideoPlayerAvplayApi { Future getStreamingProperty(StreamingPropertyTypeMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.getStreamingProperty$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1608,16 +1545,13 @@ class VideoPlayerAvplayApi { Future setBufferConfig(BufferConfigMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.setBufferConfig$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1639,16 +1573,13 @@ class VideoPlayerAvplayApi { Future setStreamingProperty(StreamingPropertyMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.setStreamingProperty$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1665,16 +1596,13 @@ class VideoPlayerAvplayApi { Future setDisplayRotate(RotationMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.setDisplayRotate$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1696,16 +1624,13 @@ class VideoPlayerAvplayApi { Future setDisplayMode(DisplayModeMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.setDisplayMode$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1727,16 +1652,13 @@ class VideoPlayerAvplayApi { Future suspend(int playerId) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.suspend$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([playerId]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([playerId]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1753,16 +1675,14 @@ class VideoPlayerAvplayApi { Future restore(int playerId, CreateMessage? msg, int resumeTime) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.restore$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); final Future pigeonVar_sendFuture = pigeonVar_channel.send([playerId, msg, resumeTime]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1779,16 +1699,13 @@ class VideoPlayerAvplayApi { Future setData(DashPropertyMapMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.setData$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1807,20 +1724,16 @@ class VideoPlayerAvplayApi { } } - Future getData( - DashPropertyTypeListMessage msg) async { + Future getData(DashPropertyTypeListMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.getData$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1842,16 +1755,14 @@ class VideoPlayerAvplayApi { Future updateDashToken(int playerId, String dashToken) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.updateDashToken$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); final Future pigeonVar_sendFuture = pigeonVar_channel.send([playerId, dashToken]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1873,16 +1784,13 @@ class VideoPlayerAvplayApi { Future getActiveTrackInfo(PlayerMessage msg) async { final String pigeonVar_channelName = 'dev.flutter.pigeon.video_player_avplay.VideoPlayerAvplayApi.getActiveTrackInfo$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( + final BasicMessageChannel pigeonVar_channel = BasicMessageChannel( pigeonVar_channelName, pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final Future pigeonVar_sendFuture = - pigeonVar_channel.send([msg]); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel.send([msg]); + final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/video_player_avplay/lib/src/sub_rip.dart b/packages/video_player_avplay/lib/src/sub_rip.dart index c8b35c0cd..5be5b4cec 100644 --- a/packages/video_player_avplay/lib/src/sub_rip.dart +++ b/packages/video_player_avplay/lib/src/sub_rip.dart @@ -12,8 +12,7 @@ class SubRipCaptionFile extends ClosedCaptionFile { /// Parses a string into a [ClosedCaptionFile], assuming [fileContents] is in /// the SubRip file format. /// * See: https://en.wikipedia.org/wiki/SubRip - SubRipCaptionFile(this.fileContents) - : _captions = _parseCaptionsFromSubRipString(fileContents); + SubRipCaptionFile(this.fileContents) : _captions = _parseCaptionsFromSubRipString(fileContents); /// The entire body of the SubRip file. // TODO(cyanglaz): Remove this public member as it doesn't seem need to exist. @@ -27,7 +26,7 @@ class SubRipCaptionFile extends ClosedCaptionFile { } List _parseCaptionsFromSubRipString(String file) { - final List captions = []; + final captions = []; for (final List captionLines in _readSubRipFile(file)) { if (captionLines.length < 3) { break; @@ -40,7 +39,7 @@ List _parseCaptionsFromSubRipString(String file) { final String text = captionLines.sublist(2).join('\n'); - final TextCaption newCaption = TextCaption( + final newCaption = TextCaption( number: captionNumber, start: captionRange.start, end: captionRange.end, @@ -64,7 +63,7 @@ class _CaptionRange { // For example: // 00:01:54,724 --> 00:01:56,760 static _CaptionRange fromSubRipString(String line) { - final RegExp format = RegExp( + final format = RegExp( _subRipTimeStamp + _subRipArrow + _subRipTimeStamp, ); @@ -113,10 +112,10 @@ Duration _parseSubRipTimestamp(String timestampString) { List> _readSubRipFile(String file) { final List lines = LineSplitter.split(file).toList(); - final List> captionStrings = >[]; - List currentCaption = []; - int lineIndex = 0; - for (final String line in lines) { + final captionStrings = >[]; + var currentCaption = []; + var lineIndex = 0; + for (final line in lines) { final bool isLineBlank = line.trim().isEmpty; if (!isLineBlank) { currentCaption.add(line); diff --git a/packages/video_player_avplay/lib/src/video_player_tizen.dart b/packages/video_player_avplay/lib/src/video_player_tizen.dart index 5df865ef4..90b7afd89 100644 --- a/packages/video_player_avplay/lib/src/video_player_tizen.dart +++ b/packages/video_player_avplay/lib/src/video_player_tizen.dart @@ -28,7 +28,7 @@ class VideoPlayerTizen extends VideoPlayerPlatform { @override Future create(DataSource dataSource) async { - final CreateMessage message = CreateMessage(); + final message = CreateMessage(); switch (dataSource.sourceType) { case DataSourceType.asset: @@ -127,13 +127,13 @@ class VideoPlayerTizen extends VideoPlayerPlatform { TrackTypeMessage(playerId: playerId, trackType: TrackType.video.name), ); - final List videoTracks = []; + final videoTracks = []; for (final Map? trackMap in response.tracks) { - final int trackId = trackMap!['trackId']! as int; - final String mimetype = trackMap['mimetype']! as String; - final int bitrate = trackMap['bitrate']! as int; - final int width = trackMap['width']! as int; - final int height = trackMap['height']! as int; + final trackId = trackMap!['trackId']! as int; + final mimetype = trackMap['mimetype']! as String; + final bitrate = trackMap['bitrate']! as int; + final width = trackMap['width']! as int; + final height = trackMap['height']! as int; videoTracks.add( VideoTrack( @@ -155,13 +155,13 @@ class VideoPlayerTizen extends VideoPlayerPlatform { TrackTypeMessage(playerId: playerId, trackType: TrackType.audio.name), ); - final List audioTracks = []; + final audioTracks = []; for (final Map? trackMap in response.tracks) { - final int trackId = trackMap!['trackId']! as int; - final String mimetype = trackMap['mimetype']! as String; - final String language = trackMap['language']! as String; - final int channel = trackMap['channel']! as int; - final int bitrate = trackMap['bitrate']! as int; + final trackId = trackMap!['trackId']! as int; + final mimetype = trackMap['mimetype']! as String; + final language = trackMap['language']! as String; + final channel = trackMap['channel']! as int; + final bitrate = trackMap['bitrate']! as int; audioTracks.add( AudioTrack( @@ -183,11 +183,11 @@ class VideoPlayerTizen extends VideoPlayerPlatform { TrackTypeMessage(playerId: playerId, trackType: TrackType.text.name), ); - final List textTracks = []; + final textTracks = []; for (final Map? trackMap in response.tracks) { - final int trackId = trackMap!['trackId']! as int; - final String mimetype = trackMap['mimetype']! as String; - final String language = trackMap['language']! as String; + final trackId = trackMap!['trackId']! as int; + final mimetype = trackMap['mimetype']! as String; + final language = trackMap['language']! as String; textTracks.add( TextTrack(trackId: trackId, mimetype: mimetype, language: language), @@ -280,7 +280,7 @@ class VideoPlayerTizen extends VideoPlayerPlatform { DataSource? dataSource, int resumeTime = -1, }) async { - final CreateMessage message = CreateMessage(); + final message = CreateMessage(); if (dataSource != null) { switch (dataSource.sourceType) { @@ -330,8 +330,8 @@ class VideoPlayerTizen extends VideoPlayerPlatform { int playerId, Set keys, ) async { - final List keysList = []; - for (final DashPlayerProperty key in keys) { + final keysList = []; + for (final key in keys) { keysList.add(_dashPlayerPropertyMap[key]); } final DashPropertyMapMessage msg = await _api.getData( @@ -356,15 +356,15 @@ class VideoPlayerTizen extends VideoPlayerPlatform { final TrackMessage msg = await _api.getActiveTrackInfo( PlayerMessage(playerId: playerId), ); - final List tracks = []; + final tracks = []; for (final Map? trackMap in msg.tracks) { - final String trackType = trackMap!['trackType']! as String; - final int trackId = trackMap['trackId']! as int; - final String mimetype = trackMap['mimetype']! as String; + final trackType = trackMap!['trackType']! as String; + final trackId = trackMap['trackId']! as int; + final mimetype = trackMap['mimetype']! as String; if (trackType == 'video') { - final int bitrate = trackMap['bitrate']! as int; - final int width = trackMap['width']! as int; - final int height = trackMap['height']! as int; + final bitrate = trackMap['bitrate']! as int; + final width = trackMap['width']! as int; + final height = trackMap['height']! as int; tracks.add( VideoTrack( trackId: trackId, @@ -375,9 +375,9 @@ class VideoPlayerTizen extends VideoPlayerPlatform { ), ); } else if (trackType == 'audio') { - final String language = trackMap['language']! as String; - final int channel = trackMap['channel']! as int; - final int bitrate = trackMap['bitrate']! as int; + final language = trackMap['language']! as String; + final channel = trackMap['channel']! as int; + final bitrate = trackMap['bitrate']! as int; tracks.add( AudioTrack( trackId: trackId, @@ -388,7 +388,7 @@ class VideoPlayerTizen extends VideoPlayerPlatform { ), ); } else if (trackType == 'text') { - final String language = trackMap['language']! as String; + final language = trackMap['language']! as String; tracks.add( TextTrack(trackId: trackId, mimetype: mimetype, language: language), ); @@ -417,11 +417,11 @@ class VideoPlayerTizen extends VideoPlayerPlatform { return _eventChannelFor(playerId).receiveBroadcastStream().map(( dynamic event, ) { - final Map map = event as Map; + final map = event as Map; switch (map['event']) { case 'initialized': case 'restored': - final List? durationVal = map['duration'] as List?; + final durationVal = map['duration'] as List?; VideoEventType videoEventType; if (map['event'] == 'initialized') { videoEventType = VideoEventType.initialized; @@ -442,7 +442,7 @@ class VideoPlayerTizen extends VideoPlayerPlatform { case 'completed': return VideoEvent(eventType: VideoEventType.completed); case 'bufferingUpdate': - final int value = map['value']! as int; + final value = map['value']! as int; return VideoEvent( buffered: value, @@ -455,10 +455,8 @@ class VideoPlayerTizen extends VideoPlayerPlatform { case 'subtitleUpdate': return VideoEvent( eventType: VideoEventType.subtitleUpdate, - subtitlesInfo: SubtitlesInfo( - map['duration'] as int?, - map['textsInfo'] as List?, - map['pictureInfo'] as Map?), + subtitlesInfo: SubtitlesInfo(map['duration'] as int?, + map['textsInfo'] as List?, map['pictureInfo'] as Map?), ); case 'isPlayingStateUpdate': return VideoEvent( @@ -516,8 +514,7 @@ class VideoPlayerTizen extends VideoPlayerPlatform { return EventChannel('tizen/video_player/video_events_$playerId'); } - static const Map _videoFormatStringMap = - { + static const Map _videoFormatStringMap = { VideoFormat.ss: 'ss', VideoFormat.hls: 'hls', VideoFormat.dash: 'dash', @@ -549,17 +546,14 @@ class VideoPlayerTizen extends VideoPlayerPlatform { StreamingPropertyType.setAbr: 'SET_ABR', }; - static const Map _bufferConfigTypeMap = - { + static const Map _bufferConfigTypeMap = { BufferConfigType.totalBufferSizeInByte: 'total_buffer_size_in_byte', BufferConfigType.totalBufferSizeInTime: 'total_buffer_size_in_time', BufferConfigType.bufferSizeInByteForPlay: 'buffer_size_in_byte_for_play', BufferConfigType.bufferSizeInSecForPlay: 'buffer_size_in_sec_for_play', - BufferConfigType.bufferSizeInByteForResume: - 'buffer_size_in_byte_for_resume', + BufferConfigType.bufferSizeInByteForResume: 'buffer_size_in_byte_for_resume', BufferConfigType.bufferSizeInSecForResume: 'buffer_size_in_sec_for_resume', - BufferConfigType.bufferingTimeoutInSecForPlay: - 'buffering_timeout_in_sec_for_play', + BufferConfigType.bufferingTimeoutInSecForPlay: 'buffering_timeout_in_sec_for_play', }; static const Map _dashPlayerPropertyMap = diff --git a/packages/video_player_avplay/lib/src/web_vtt.dart b/packages/video_player_avplay/lib/src/web_vtt.dart index fbcf81408..a4d3d2ab2 100644 --- a/packages/video_player_avplay/lib/src/web_vtt.dart +++ b/packages/video_player_avplay/lib/src/web_vtt.dart @@ -15,8 +15,7 @@ class WebVTTCaptionFile extends ClosedCaptionFile { /// Parses a string into a [ClosedCaptionFile], assuming [fileContents] is in /// the WebVTT file format. /// * See: https://en.wikipedia.org/wiki/WebVTT - WebVTTCaptionFile(String fileContents) - : _captions = _parseCaptionsFromWebVTTString(fileContents); + WebVTTCaptionFile(String fileContents) : _captions = _parseCaptionsFromWebVTTString(fileContents); @override List get textCaptions => _captions; @@ -25,12 +24,12 @@ class WebVTTCaptionFile extends ClosedCaptionFile { } List _parseCaptionsFromWebVTTString(String file) { - final List captions = []; + final captions = []; // Ignore metadata - final Set metadata = {'HEADER', 'NOTE', 'REGION', 'WEBVTT'}; + final metadata = {'HEADER', 'NOTE', 'REGION', 'WEBVTT'}; - int captionNumber = 1; + var captionNumber = 1; for (final List captionLines in _readWebVTTFile(file)) { // CaptionLines represent a complete caption. // E.g @@ -72,7 +71,7 @@ List _parseCaptionsFromWebVTTString(String file) { // https://github.com/flutter/flutter/issues/90007. final String textWithoutFormat = _extractTextFromHtml(text); - final TextCaption newCaption = TextCaption( + final newCaption = TextCaption( number: captionNumber, start: captionRange.start, end: captionRange.end, @@ -95,7 +94,7 @@ class _CaptionRange { // For example: // 00:09.000 --> 00:11.000 static _CaptionRange? fromWebVTTString(String line) { - final RegExp format = RegExp( + final format = RegExp( _webVTTTimeStamp + _webVTTArrow + _webVTTTimeStamp, ); @@ -149,7 +148,7 @@ Duration? _parseWebVTTTimestamp(String timestampString) { if (timeComponents.length > 3 || timeComponents.length < 2) { return null; } - int hours = 0; + var hours = 0; if (timeComponents.length == 3) { final String hourString = timeComponents.removeAt(0); if (hourString.length < 2) { @@ -192,10 +191,10 @@ Duration? _parseWebVTTTimestamp(String timestampString) { List> _readWebVTTFile(String file) { final List lines = LineSplitter.split(file).toList(); - final List> captionStrings = >[]; - List currentCaption = []; - int lineIndex = 0; - for (final String line in lines) { + final captionStrings = >[]; + var currentCaption = []; + var lineIndex = 0; + for (final line in lines) { final bool isLineBlank = line.trim().isEmpty; if (!isLineBlank) { currentCaption.add(line); diff --git a/packages/video_player_avplay/lib/video_player.dart b/packages/video_player_avplay/lib/video_player.dart index ad940483a..32025e650 100644 --- a/packages/video_player_avplay/lib/video_player.dart +++ b/packages/video_player_avplay/lib/video_player.dart @@ -252,9 +252,8 @@ class VideoPlayerValue { isBuffering: isBuffering ?? this.isBuffering, volume: volume ?? this.volume, playbackSpeed: playbackSpeed ?? this.playbackSpeed, - errorDescription: errorDescription != _defaultErrorDescription - ? errorDescription - : this.errorDescription, + errorDescription: + errorDescription != _defaultErrorDescription ? errorDescription : this.errorDescription, isCompleted: isCompleted ?? this.isCompleted, adInfo: adInfo, manifestInfo: manifestInfo, @@ -503,11 +502,10 @@ class VideoPlayerController extends ValueNotifier { ); Future _checkPlatformAndApiVersion() async { - final DeviceInfoPluginTizen deviceInfoPlugin = DeviceInfoPluginTizen(); + final deviceInfoPlugin = DeviceInfoPluginTizen(); final TizenDeviceInfo deviceInfo = await deviceInfoPlugin.tizenInfo; - if ((deviceInfo.platformVersion != null && - deviceInfo.platformVersion!.isNotEmpty) && + if ((deviceInfo.platformVersion != null && deviceInfo.platformVersion!.isNotEmpty) && tizen.apiVersion != 'none') { if (deviceInfo.platformVersion != tizen.apiVersion) { final double? platformVersion = double.tryParse( @@ -538,8 +536,7 @@ class VideoPlayerController extends ValueNotifier { Future initialize() async { await _checkPlatformAndApiVersion(); - final bool allowBackgroundPlayback = - videoPlayerOptions?.allowBackgroundPlayback ?? false; + final bool allowBackgroundPlayback = videoPlayerOptions?.allowBackgroundPlayback ?? false; if (!allowBackgroundPlayback) { _lifeCycleObserver = _VideoAppLifeCycleObserver(this); } @@ -582,10 +579,10 @@ class VideoPlayerController extends ValueNotifier { ); } - _playerId = (await _videoPlayerPlatform.create(dataSourceDescription)) ?? - kUninitializedPlayerId; + _playerId = + (await _videoPlayerPlatform.create(dataSourceDescription)) ?? kUninitializedPlayerId; _creatingCompleter!.complete(null); - final Completer initializingCompleter = Completer(); + final initializingCompleter = Completer(); void eventListener(VideoEvent event) { if (_isDisposed) { @@ -619,8 +616,7 @@ class VideoPlayerController extends ValueNotifier { // NOTE(jsuya): The plusplayer's SetVolume() work when player is // paused or played, so it changes the order of _applyPlayPause() // and _applyVolume(). - if (event.eventType == VideoEventType.restored && - _onRestoreDataSource != null) { + if (event.eventType == VideoEventType.restored && _onRestoreDataSource != null) { play(); } else { _applyPlayPause(); @@ -643,8 +639,7 @@ class VideoPlayerController extends ValueNotifier { case VideoEventType.bufferingEnd: value = value.copyWith(isBuffering: false); case VideoEventType.subtitleUpdate: - final Captions? captions = - Captions.parseSubtitle(value.position, event.subtitlesInfo!); + final Captions? captions = Captions.parseSubtitle(value.position, event.subtitlesInfo!); value = value.copyWith(captions: captions); case VideoEventType.isPlayingStateUpdate: if (event.isPlaying ?? false) { @@ -657,8 +652,7 @@ class VideoPlayerController extends ValueNotifier { value = value.copyWith(isPlaying: event.isPlaying); } case VideoEventType.adFromDash: - final AdInfoFromDash? adInfo = - AdInfoFromDash.fromAdInfoMap(event.adInfo); + final AdInfoFromDash? adInfo = AdInfoFromDash.fromAdInfoMap(event.adInfo); value = value.copyWith(adInfo: adInfo); case VideoEventType.manifestInfoUpdated: value = value.copyWith(manifestInfo: event.manifestInfo); @@ -678,9 +672,8 @@ class VideoPlayerController extends ValueNotifier { if (drmConfigs?.licenseCallback != null) { _channel.setMethodCallHandler((MethodCall call) async { if (call.method == 'requestLicense') { - final Map argumentsMap = - call.arguments as Map; - final Uint8List message = argumentsMap['message']! as Uint8List; + final argumentsMap = call.arguments as Map; + final message = argumentsMap['message']! as Uint8List; return drmConfigs!.licenseCallback!(message); } else { throw Exception('not implemented ${call.method}'); @@ -689,7 +682,7 @@ class VideoPlayerController extends ValueNotifier { } void errorListener(Object obj) { - final PlatformException e = obj as PlatformException; + final e = obj as PlatformException; value = VideoPlayerValue.erroneous(e.message!); _timer?.cancel(); _durationTimer?.cancel(); @@ -935,10 +928,8 @@ class VideoPlayerController extends ValueNotifier { return; } if (formatHint != VideoFormat.dash && - (type == StreamingPropertyType.dashToken || - type == StreamingPropertyType.openHttpHeader)) { - throw Exception( - 'setStreamingProperty().$type only support for dash format!'); + (type == StreamingPropertyType.dashToken || type == StreamingPropertyType.openHttpHeader)) { + throw Exception('setStreamingProperty().$type only support for dash format!'); } return _videoPlayerPlatform.setStreamingProperty(_playerId, type, value); } @@ -1014,8 +1005,7 @@ class VideoPlayerController extends ValueNotifier { return; } - final DataSource? dataSource = - (_onRestoreDataSource != null) ? _onRestoreDataSource!() : null; + final DataSource? dataSource = (_onRestoreDataSource != null) ? _onRestoreDataSource!() : null; final int resumeTime = (_onRestoreTime != null) ? _onRestoreTime!() : -1; await _videoPlayerPlatform.restore( @@ -1157,8 +1147,7 @@ class VideoPlayerController extends ValueNotifier { final Duration delayedPosition = position + value.captionOffset; // TODO(johnsonmh): This would be more efficient as a binary search. for (final TextCaption textCaption in _closedCaptionFile!.textCaptions) { - if (textCaption.start <= delayedPosition && - textCaption.end >= delayedPosition) { + if (textCaption.start <= delayedPosition && textCaption.end >= delayedPosition) { return [textCaption]; } } @@ -1179,8 +1168,7 @@ class VideoPlayerController extends ValueNotifier { value = value.copyWith( position: position, captions: Captions( - textCaptions: _getCaptionAt(position), - pictureCaption: _getPictureCaptionAt(position)), + textCaptions: _getCaptionAt(position), pictureCaption: _getPictureCaptionAt(position)), isCompleted: position == value.duration.end, ); } @@ -1288,15 +1276,12 @@ class _VideoPlayerState extends State { final double offsetHeight = rect.height.ceil() - rect.height; final int left = _isInvalid(rect.left) ? 0 : rect.left.floor(); final int top = _isInvalid(rect.top) ? 0 : rect.top.floor(); - final int width = _isInvalid(rect.width) - ? 1 - : rect.width.ceil() + ((offsetLeft > offsetWidth) ? 1 : 0); - final int height = _isInvalid(rect.height) - ? 1 - : rect.height.ceil() + ((offsetTop > offsetHeight) ? 1 : 0); - - _videoPlayerPlatform.setDisplayGeometry( - _playerId, left, top, width, height); + final int width = + _isInvalid(rect.width) ? 1 : rect.width.ceil() + ((offsetLeft > offsetWidth) ? 1 : 0); + final int height = + _isInvalid(rect.height) ? 1 : rect.height.ceil() + ((offsetTop > offsetHeight) ? 1 : 0); + + _videoPlayerPlatform.setDisplayGeometry(_playerId, left, top, width, height); _playerRect = rect; } } @@ -1304,14 +1289,13 @@ class _VideoPlayerState extends State { } Rect _getCurrentRect() { - final RenderObject? renderObject = - _videoBoxKey.currentContext?.findRenderObject(); + final RenderObject? renderObject = _videoBoxKey.currentContext?.findRenderObject(); if (renderObject == null) { return Rect.zero; } // ignore: deprecated_member_use final double pixelRatio = WidgetsBinding.instance.window.devicePixelRatio; - final RenderBox renderBox = renderObject as RenderBox; + final renderBox = renderObject as RenderBox; final Offset offset = renderBox.localToGlobal(Offset.zero) * pixelRatio; final Size size = renderBox.size * pixelRatio * widget.scale; return offset & size; @@ -1420,7 +1404,7 @@ class _VideoScrubberState extends State<_VideoScrubber> { @override Widget build(BuildContext context) { void seekToRelativePosition(Offset globalPosition) { - final RenderBox box = context.findRenderObject()! as RenderBox; + final box = context.findRenderObject()! as RenderBox; final Offset tapPos = box.globalToLocal(globalPosition); final double relative = tapPos.dx / box.size.width; final Duration position = controller.value.duration.end * relative; @@ -1446,8 +1430,7 @@ class _VideoScrubberState extends State<_VideoScrubber> { seekToRelativePosition(details.globalPosition); }, onHorizontalDragEnd: (DragEndDetails details) { - if (_controllerWasPlaying && - controller.value.position != controller.value.duration.end) { + if (_controllerWasPlaying && controller.value.position != controller.value.duration.end) { controller.play(); } }, @@ -1609,10 +1592,9 @@ class ClosedCaption extends StatelessWidget { Widget build(BuildContext context) { if (captions?.pictureCaption?.picture?.isNotEmpty ?? false) { final PictureCaption pictureCaption = captions!.pictureCaption!; - final Image subtitleImage = Image.memory(pictureCaption.picture!, - width: pictureCaption.pictureWidth, - height: pictureCaption.pictureHeight, errorBuilder: - (BuildContext context, Object error, StackTrace? stackTrace) { + final subtitleImage = Image.memory(pictureCaption.picture!, + width: pictureCaption.pictureWidth, height: pictureCaption.pictureHeight, + errorBuilder: (BuildContext context, Object error, StackTrace? stackTrace) { FlutterError.reportError( FlutterErrorDetails( exception: error, @@ -1630,8 +1612,7 @@ class ClosedCaption extends StatelessWidget { child: subtitleImage, )); } else { - if (captions?.textCaptions == null || - captions?.textCaptions![0] == null) { + if (captions?.textCaptions == null || captions?.textCaptions![0] == null) { return const SizedBox.shrink(); } @@ -1639,10 +1620,7 @@ class ClosedCaption extends StatelessWidget { return Stack( alignment: AlignmentDirectional.bottomCenter, - children: textCaptions - .asMap() - .entries - .map((MapEntry entry) { + children: textCaptions.asMap().entries.map((MapEntry entry) { final int index = entry.key; final TextCaption? textCaption = entry.value; final String? text = textCaption?.text; @@ -1650,8 +1628,8 @@ class ClosedCaption extends StatelessWidget { return const SizedBox.shrink(); } - return Positioned.fill(child: LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { + return Positioned.fill( + child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { final double dynamicFontSize = constraints.maxHeight * (textCaption?.fontSize ?? 1 / 15.0); @@ -1660,23 +1638,19 @@ class ClosedCaption extends StatelessWidget { ? DefaultTextStyle.of( context, ).style.copyWith(fontSize: 36.0, color: Colors.white) - : textCaption!.textStyle! - .copyWith(fontSize: dynamicFontSize)); + : textCaption!.textStyle!.copyWith(fontSize: dynamicFontSize)); - if (customTextStyle != null || - textCaption?.textOriginAndExtent == null) { - const double bottomOffset = 24.0; - const double lineHeight = 43.5; + if (customTextStyle != null || textCaption?.textOriginAndExtent == null) { + const bottomOffset = 24.0; + const lineHeight = 43.5; return Align( alignment: Alignment.bottomCenter, child: Padding( padding: EdgeInsets.only( - bottom: bottomOffset + - (textCaptions.length - 1 - index) * lineHeight), + bottom: bottomOffset + (textCaptions.length - 1 - index) * lineHeight), child: DecoratedBox( decoration: BoxDecoration( - color: textCaption?.windowBgColor ?? - const Color(0xB8000000), + color: textCaption?.windowBgColor ?? const Color(0xB8000000), borderRadius: BorderRadius.circular(2.0)), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 2.0), @@ -1701,11 +1675,9 @@ class ClosedCaption extends StatelessWidget { child: Stack( children: [ ColoredBox( - color: textCaption.windowBgColor ?? - const Color(0xB8000000), + color: textCaption.windowBgColor ?? const Color(0xB8000000), child: Align( - alignment: - textCaption.textAlign ?? Alignment.center, + alignment: textCaption.textAlign ?? Alignment.center, child: Text( text, style: effectiveTextStyle, @@ -1715,8 +1687,7 @@ class ClosedCaption extends StatelessWidget { ColoredBox( color: Colors.transparent, child: Align( - alignment: - textCaption.textAlign ?? Alignment.center, + alignment: textCaption.textAlign ?? Alignment.center, child: Text( text, style: effectiveTextStyle.copyWith( diff --git a/packages/video_player_avplay/lib/video_player_platform_interface.dart b/packages/video_player_avplay/lib/video_player_platform_interface.dart index ca76d433a..c4216be59 100644 --- a/packages/video_player_avplay/lib/video_player_platform_interface.dart +++ b/packages/video_player_avplay/lib/video_player_platform_interface.dart @@ -701,8 +701,7 @@ class DurationRange { } @override - String toString() => - '${objectRuntimeType(this, 'DurationRange')}(start: $start, end: $end)'; + String toString() => '${objectRuntimeType(this, 'DurationRange')}(start: $start, end: $end)'; @override bool operator ==(Object other) => @@ -741,8 +740,7 @@ class SubtitlesInfo { } @override - int get hashCode => - textDuration.hashCode ^ textsInfo.hashCode ^ pictureInfo.hashCode; + int get hashCode => textDuration.hashCode ^ textsInfo.hashCode ^ pictureInfo.hashCode; } /// [VideoPlayerOptions] can be optionally used to set additional player settings diff --git a/packages/video_player_videohole/CHANGELOG.md b/packages/video_player_videohole/CHANGELOG.md index 628d76850..198c8744f 100644 --- a/packages/video_player_videohole/CHANGELOG.md +++ b/packages/video_player_videohole/CHANGELOG.md @@ -9,6 +9,8 @@ * Replace ecore-wl2 code with tizen window manager plugin. * Resolve `strict_top_level_inference` lint. +* Omit obvious local variable types. +* Reformat with a line length of 100. ## 0.5.10 diff --git a/packages/video_player_videohole/example/integration_test/video_player_test.dart b/packages/video_player_videohole/example/integration_test/video_player_test.dart index 001d3f021..b0f7a34f0 100644 --- a/packages/video_player_videohole/example/integration_test/video_player_test.dart +++ b/packages/video_player_videohole/example/integration_test/video_player_test.dart @@ -16,8 +16,7 @@ import 'package:video_player_videohole/video_player.dart'; const Duration _playDuration = Duration(seconds: 1); // Use WebM for web to allow CI to use Chromium. -const String _videoAssetKey = - kIsWeb ? 'assets/Butterfly-209.webm' : 'assets/Butterfly-209.mp4'; +const String _videoAssetKey = kIsWeb ? 'assets/Butterfly-209.webm' : 'assets/Butterfly-209.mp4'; // Returns the URL to load an asset from this example app as a network source. String getUrlForAssetAsNetworkSource(String assetKey) { @@ -53,8 +52,7 @@ void main() { }); testWidgets('live stream duration != 0', (WidgetTester tester) async { - final VideoPlayerController networkController = - VideoPlayerController.network( + final networkController = VideoPlayerController.network( 'https://flutter.github.io/assets-for-api-docs/assets/videos/hls/bee.m3u8', ); await networkController.initialize(); @@ -208,7 +206,7 @@ void main() { // Write it to a file to use as a source. final String filename = _videoAssetKey.split('/').last; - final File file = File('$tempDir/$filename'); + final file = File('$tempDir/$filename'); await file.writeAsBytes(bytes.buffer.asInt8List()); controller = VideoPlayerController.file(file); @@ -241,15 +239,13 @@ void main() { // Mute to allow playing without DOM interaction on Web. // See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes await controller.setVolume(0); - final Completer started = Completer(); - final Completer ended = Completer(); + final started = Completer(); + final ended = Completer(); controller.addListener(() { if (!started.isCompleted && controller.value.isBuffering) { started.complete(); } - if (started.isCompleted && - !controller.value.isBuffering && - !ended.isCompleted) { + if (started.isCompleted && !controller.value.isBuffering && !ended.isCompleted) { ended.complete(); } }); diff --git a/packages/video_player_videohole/example/lib/main.dart b/packages/video_player_videohole/example/lib/main.dart index 26de08ab7..c3d428648 100644 --- a/packages/video_player_videohole/example/lib/main.dart +++ b/packages/video_player_videohole/example/lib/main.dart @@ -325,8 +325,7 @@ class _DrmRemoteVideoState2 extends State<_DrmRemoteVideo2> { 'https://test.playready.microsoft.com/smoothstreaming/SSWSS720H264PR/SuperSpeedway_720.ism/Manifest', drmConfigs: const DrmConfigs( type: DrmType.playready, - licenseServerUrl: - 'https://test.playready.microsoft.com/service/rightsmanager.asmx', + licenseServerUrl: 'https://test.playready.microsoft.com/service/rightsmanager.asmx', ), ); @@ -786,7 +785,7 @@ class _TestRemoteVideoState extends State<_TestRemoteVideo> { } DataSource restoreDataSource() { - final DataSource dataSource = DataSource( + final dataSource = DataSource( sourceType: DataSourceType.network, uri: 'https://media.w3.org/2010/05/bunny/trailer.mp4', ); @@ -796,7 +795,7 @@ class _TestRemoteVideoState extends State<_TestRemoteVideo> { int restoreTime() { /// if resumeTime >= 0 , it will restore from resumeTime /// if resumeTime is not set or <0, it will restore from the time when suspend is called - const int resumeTime = 0; + const resumeTime = 0; return resumeTime; } diff --git a/packages/video_player_videohole/lib/src/hole.dart b/packages/video_player_videohole/lib/src/hole.dart index 74a4a6e6d..1b9504a59 100644 --- a/packages/video_player_videohole/lib/src/hole.dart +++ b/packages/video_player_videohole/lib/src/hole.dart @@ -55,9 +55,9 @@ class _HoleLayer extends Layer { } Picture _createHolePicture(Rect holeRect) { - final PictureRecorder recorder = PictureRecorder(); - final Canvas canvas = Canvas(recorder); - final Paint paint = Paint(); + final recorder = PictureRecorder(); + final canvas = Canvas(recorder); + final paint = Paint(); paint.color = Colors.transparent; paint.blendMode = BlendMode.src; canvas.drawRect(rect, paint); diff --git a/packages/video_player_videohole/lib/src/sub_rip.dart b/packages/video_player_videohole/lib/src/sub_rip.dart index c9d8189a7..490e48972 100644 --- a/packages/video_player_videohole/lib/src/sub_rip.dart +++ b/packages/video_player_videohole/lib/src/sub_rip.dart @@ -12,8 +12,7 @@ class SubRipCaptionFile extends ClosedCaptionFile { /// Parses a string into a [ClosedCaptionFile], assuming [fileContents] is in /// the SubRip file format. /// * See: https://en.wikipedia.org/wiki/SubRip - SubRipCaptionFile(this.fileContents) - : _captions = _parseCaptionsFromSubRipString(fileContents); + SubRipCaptionFile(this.fileContents) : _captions = _parseCaptionsFromSubRipString(fileContents); /// The entire body of the SubRip file. // TODO(cyanglaz): Remove this public member as it doesn't seem need to exist. @@ -27,7 +26,7 @@ class SubRipCaptionFile extends ClosedCaptionFile { } List _parseCaptionsFromSubRipString(String file) { - final List captions = []; + final captions = []; for (final List captionLines in _readSubRipFile(file)) { if (captionLines.length < 3) { break; @@ -40,7 +39,7 @@ List _parseCaptionsFromSubRipString(String file) { final String text = captionLines.sublist(2).join('\n'); - final Caption newCaption = Caption( + final newCaption = Caption( number: captionNumber, start: captionRange.start, end: captionRange.end, @@ -64,7 +63,7 @@ class _CaptionRange { // For example: // 00:01:54,724 --> 00:01:56,760 static _CaptionRange fromSubRipString(String line) { - final RegExp format = RegExp( + final format = RegExp( _subRipTimeStamp + _subRipArrow + _subRipTimeStamp, ); @@ -113,10 +112,10 @@ Duration _parseSubRipTimestamp(String timestampString) { List> _readSubRipFile(String file) { final List lines = LineSplitter.split(file).toList(); - final List> captionStrings = >[]; - List currentCaption = []; - int lineIndex = 0; - for (final String line in lines) { + final captionStrings = >[]; + var currentCaption = []; + var lineIndex = 0; + for (final line in lines) { final bool isLineBlank = line.trim().isEmpty; if (!isLineBlank) { currentCaption.add(line); diff --git a/packages/video_player_videohole/lib/src/video_player_tizen.dart b/packages/video_player_videohole/lib/src/video_player_tizen.dart index e98c0d004..f89a680ec 100644 --- a/packages/video_player_videohole/lib/src/video_player_tizen.dart +++ b/packages/video_player_videohole/lib/src/video_player_tizen.dart @@ -76,7 +76,7 @@ class VideoPlayerTizen extends VideoPlayerPlatform { Future create(DataSource dataSource) async { _ensureEventPortRegistered(); - final CreateMessage message = CreateMessage(); + final message = CreateMessage(); switch (dataSource.sourceType) { case DataSourceType.asset: @@ -127,22 +127,20 @@ class VideoPlayerTizen extends VideoPlayerPlatform { _eventPort!.handler = (dynamic message) { try { if (message is List && message.length == 2) { - final int receivingPlayerId = message[0] as int; - final String eventJson = message[1] as String; + final receivingPlayerId = message[0] as int; + final eventJson = message[1] as String; - final Map eventMap = - jsonDecode(eventJson) as Map; + final eventMap = jsonDecode(eventJson) as Map; if (eventMap['event'] == 'seekCompleted') { _handleSeekCompleted(receivingPlayerId); return; } - final StreamController? controller = - _eventControllers[receivingPlayerId]; + final StreamController? controller = _eventControllers[receivingPlayerId]; if (eventMap['event'] == 'error') { - final PlatformException exception = PlatformException( + final exception = PlatformException( code: eventMap['code'] as String? ?? 'unknown', message: eventMap['message'] as String?, ); @@ -261,13 +259,12 @@ class VideoPlayerTizen extends VideoPlayerPlatform { Future seekTo(int playerId, Duration position) async { _ensureEventPortRegistered(); - final Completer completer = Completer(); + final completer = Completer(); if (_activeSeeks.containsKey(playerId)) { final _SeekOperation pendingSeek = _pendingSeeks.putIfAbsent( playerId, - () => - _SeekOperation(position: position, completers: >[]), + () => _SeekOperation(position: position, completers: >[]), ); pendingSeek.position = position; pendingSeek.completers.add(completer); @@ -282,12 +279,12 @@ class VideoPlayerTizen extends VideoPlayerPlatform { Future> getVideoTracks(int playerId) async { final TrackMessage message = _ffiApi.getTrackInfo(playerId, 'video'); - final List videoTracks = []; + final videoTracks = []; for (final Map? trackMap in message.tracks) { - final int trackId = trackMap!['trackId']! as int; - final int bitrate = trackMap['bitrate']! as int; - final int width = trackMap['width']! as int; - final int height = trackMap['height']! as int; + final trackId = trackMap!['trackId']! as int; + final bitrate = trackMap['bitrate']! as int; + final width = trackMap['width']! as int; + final height = trackMap['height']! as int; videoTracks.add( VideoTrack( @@ -306,12 +303,12 @@ class VideoPlayerTizen extends VideoPlayerPlatform { Future> getAudioTracks(int playerId) async { final TrackMessage message = _ffiApi.getTrackInfo(playerId, 'audio'); - final List audioTracks = []; + final audioTracks = []; for (final Map? trackMap in message.tracks) { - final int trackId = trackMap!['trackId']! as int; - final String language = trackMap['language']! as String; - final int channel = trackMap['channel']! as int; - final int bitrate = trackMap['bitrate']! as int; + final trackId = trackMap!['trackId']! as int; + final language = trackMap['language']! as String; + final channel = trackMap['channel']! as int; + final bitrate = trackMap['bitrate']! as int; audioTracks.add( AudioTrack( @@ -330,10 +327,10 @@ class VideoPlayerTizen extends VideoPlayerPlatform { Future> getTextTracks(int playerId) async { final TrackMessage message = _ffiApi.getTrackInfo(playerId, 'text'); - final List textTracks = []; + final textTracks = []; for (final Map? trackMap in message.tracks) { - final int trackId = trackMap!['trackId']! as int; - final String language = trackMap['language']! as String; + final trackId = trackMap!['trackId']! as int; + final language = trackMap['language']! as String; textTracks.add(TextTrack(trackId: trackId, language: language)); } @@ -399,7 +396,7 @@ class VideoPlayerTizen extends VideoPlayerPlatform { switch (map['event']) { case 'initialized': case 'restored': - final List? durationVal = map['duration'] as List?; + final durationVal = map['duration'] as List?; VideoEventType videoEventType; if (map['event'] == 'initialized') { videoEventType = VideoEventType.initialized; @@ -420,7 +417,7 @@ class VideoPlayerTizen extends VideoPlayerPlatform { case 'completed': return VideoEvent(eventType: VideoEventType.completed); case 'bufferingUpdate': - final int value = map['value']! as int; + final value = map['value']! as int; return VideoEvent( buffered: value, eventType: VideoEventType.bufferingUpdate, @@ -547,7 +544,7 @@ class VideoPlayerTizen extends VideoPlayerPlatform { Duration position, List> completers, ) { - final _SeekOperation seek = _SeekOperation( + final seek = _SeekOperation( position: position, completers: completers, ); @@ -650,8 +647,7 @@ class VideoPlayerTizen extends VideoPlayerPlatform { } } - static const Map _videoFormatStringMap = - { + static const Map _videoFormatStringMap = { VideoFormat.ss: 'ss', VideoFormat.hls: 'hls', VideoFormat.dash: 'dash', diff --git a/packages/video_player_videohole/lib/src/web_vtt.dart b/packages/video_player_videohole/lib/src/web_vtt.dart index e885b0d16..273d6c701 100644 --- a/packages/video_player_videohole/lib/src/web_vtt.dart +++ b/packages/video_player_videohole/lib/src/web_vtt.dart @@ -15,8 +15,7 @@ class WebVTTCaptionFile extends ClosedCaptionFile { /// Parses a string into a [ClosedCaptionFile], assuming [fileContents] is in /// the WebVTT file format. /// * See: https://en.wikipedia.org/wiki/WebVTT - WebVTTCaptionFile(String fileContents) - : _captions = _parseCaptionsFromWebVTTString(fileContents); + WebVTTCaptionFile(String fileContents) : _captions = _parseCaptionsFromWebVTTString(fileContents); @override List get captions => _captions; @@ -25,12 +24,12 @@ class WebVTTCaptionFile extends ClosedCaptionFile { } List _parseCaptionsFromWebVTTString(String file) { - final List captions = []; + final captions = []; // Ignore metadata - final Set metadata = {'HEADER', 'NOTE', 'REGION', 'WEBVTT'}; + final metadata = {'HEADER', 'NOTE', 'REGION', 'WEBVTT'}; - int captionNumber = 1; + var captionNumber = 1; for (final List captionLines in _readWebVTTFile(file)) { // CaptionLines represent a complete caption. // E.g @@ -72,7 +71,7 @@ List _parseCaptionsFromWebVTTString(String file) { // https://github.com/flutter/flutter/issues/90007. final String textWithoutFormat = _extractTextFromHtml(text); - final Caption newCaption = Caption( + final newCaption = Caption( number: captionNumber, start: captionRange.start, end: captionRange.end, @@ -95,7 +94,7 @@ class _CaptionRange { // For example: // 00:09.000 --> 00:11.000 static _CaptionRange? fromWebVTTString(String line) { - final RegExp format = RegExp( + final format = RegExp( _webVTTTimeStamp + _webVTTArrow + _webVTTTimeStamp, ); @@ -149,7 +148,7 @@ Duration? _parseWebVTTTimestamp(String timestampString) { if (timeComponents.length > 3 || timeComponents.length < 2) { return null; } - int hours = 0; + var hours = 0; if (timeComponents.length == 3) { final String hourString = timeComponents.removeAt(0); if (hourString.length < 2) { @@ -192,10 +191,10 @@ Duration? _parseWebVTTTimestamp(String timestampString) { List> _readWebVTTFile(String file) { final List lines = LineSplitter.split(file).toList(); - final List> captionStrings = >[]; - List currentCaption = []; - int lineIndex = 0; - for (final String line in lines) { + final captionStrings = >[]; + var currentCaption = []; + var lineIndex = 0; + for (final line in lines) { final bool isLineBlank = line.trim().isEmpty; if (!isLineBlank) { currentCaption.add(line); diff --git a/packages/video_player_videohole/lib/video_player.dart b/packages/video_player_videohole/lib/video_player.dart index 19437a7d7..8542b07ec 100644 --- a/packages/video_player_videohole/lib/video_player.dart +++ b/packages/video_player_videohole/lib/video_player.dart @@ -192,9 +192,8 @@ class VideoPlayerValue { isBuffering: isBuffering ?? this.isBuffering, volume: volume ?? this.volume, playbackSpeed: playbackSpeed ?? this.playbackSpeed, - errorDescription: errorDescription != _defaultErrorDescription - ? errorDescription - : this.errorDescription, + errorDescription: + errorDescription != _defaultErrorDescription ? errorDescription : this.errorDescription, isCompleted: isCompleted ?? this.isCompleted, ); } @@ -390,8 +389,7 @@ class VideoPlayerController extends ValueNotifier { /// Attempts to open the given [dataSource] and load metadata about the video. Future initialize() async { - final bool allowBackgroundPlayback = - videoPlayerOptions?.allowBackgroundPlayback ?? false; + final bool allowBackgroundPlayback = videoPlayerOptions?.allowBackgroundPlayback ?? false; if (!allowBackgroundPlayback) { _lifeCycleObserver = _VideoAppLifeCycleObserver(this); } @@ -433,10 +431,10 @@ class VideoPlayerController extends ValueNotifier { ); } - _playerId = (await _videoPlayerPlatform.create(dataSourceDescription)) ?? - kUninitializedPlayerId; + _playerId = + (await _videoPlayerPlatform.create(dataSourceDescription)) ?? kUninitializedPlayerId; _creatingCompleter!.complete(null); - final Completer initializingCompleter = Completer(); + final initializingCompleter = Completer(); _eventListener = (VideoEvent event) { if (_isDisposed) { @@ -469,8 +467,7 @@ class VideoPlayerController extends ValueNotifier { } _applyLooping(); _applyVolume(); - if (VideoEventType.restored == event.eventType && - _onRestoreDataSource != null) { + if (VideoEventType.restored == event.eventType && _onRestoreDataSource != null) { play(); } else { _applyPlayPause(); @@ -492,7 +489,7 @@ class VideoPlayerController extends ValueNotifier { case VideoEventType.bufferingEnd: value = value.copyWith(isBuffering: false); case VideoEventType.subtitleUpdate: - final Caption caption = Caption( + final caption = Caption( number: 0, start: value.position, end: value.position + (event.duration?.end ?? Duration.zero), @@ -522,9 +519,8 @@ class VideoPlayerController extends ValueNotifier { if (drmConfigs?.licenseCallback != null) { _channel.setMethodCallHandler((MethodCall call) async { if (call.method == 'requestLicense') { - final Map argumentsMap = - call.arguments as Map; - final Uint8List message = argumentsMap['message']! as Uint8List; + final argumentsMap = call.arguments as Map; + final message = argumentsMap['message']! as Uint8List; return drmConfigs!.licenseCallback!(message); } else { throw Exception('not implemented ${call.method}'); @@ -533,7 +529,7 @@ class VideoPlayerController extends ValueNotifier { } _errorListener = (Object obj) { - final PlatformException e = obj as PlatformException; + final e = obj as PlatformException; value = VideoPlayerValue.erroneous(e.message!); if (!initializingCompleter.isCompleted) { initializingCompleter.completeError(obj); @@ -912,8 +908,7 @@ class VideoPlayerController extends ValueNotifier { return; } - final DataSource? dataSource = - (_onRestoreDataSource != null) ? _onRestoreDataSource!() : null; + final DataSource? dataSource = (_onRestoreDataSource != null) ? _onRestoreDataSource!() : null; final int resumeTime = (_onRestoreTime != null) ? _onRestoreTime!() : -1; await _videoPlayerPlatform.restore( @@ -1009,15 +1004,9 @@ class _VideoPlayerState extends State { if (currentRect != Rect.zero && _playerRect != currentRect) { _videoPlayerPlatform.setDisplayGeometry( _playerId, - (currentRect.left.isInfinite || currentRect.left.isNaN) - ? 0 - : currentRect.left.toInt(), - (currentRect.top.isInfinite || currentRect.top.isNaN) - ? 0 - : currentRect.top.toInt(), - (currentRect.width.isInfinite || currentRect.width.isNaN) - ? 0 - : currentRect.width.toInt(), + (currentRect.left.isInfinite || currentRect.left.isNaN) ? 0 : currentRect.left.toInt(), + (currentRect.top.isInfinite || currentRect.top.isNaN) ? 0 : currentRect.top.toInt(), + (currentRect.width.isInfinite || currentRect.width.isNaN) ? 0 : currentRect.width.toInt(), (currentRect.height.isInfinite || currentRect.height.isNaN) ? 0 : currentRect.height.toInt(), @@ -1029,14 +1018,13 @@ class _VideoPlayerState extends State { } Rect _getCurrentRect() { - final RenderObject? renderObject = - _videoBoxKey.currentContext?.findRenderObject(); + final RenderObject? renderObject = _videoBoxKey.currentContext?.findRenderObject(); if (renderObject == null) { return Rect.zero; } // ignore: deprecated_member_use final double pixelRatio = WidgetsBinding.instance.window.devicePixelRatio; - final RenderBox renderBox = renderObject as RenderBox; + final renderBox = renderObject as RenderBox; final Offset offset = renderBox.localToGlobal(Offset.zero) * pixelRatio; final Size size = renderBox.size * pixelRatio; return offset & size; @@ -1145,7 +1133,7 @@ class _VideoScrubberState extends State<_VideoScrubber> { @override Widget build(BuildContext context) { void seekToRelativePosition(Offset globalPosition) { - final RenderBox box = context.findRenderObject()! as RenderBox; + final box = context.findRenderObject()! as RenderBox; final Offset tapPos = box.globalToLocal(globalPosition); final double relative = tapPos.dx / box.size.width; final Duration position = controller.value.duration.end * relative; @@ -1171,8 +1159,7 @@ class _VideoScrubberState extends State<_VideoScrubber> { seekToRelativePosition(details.globalPosition); }, onHorizontalDragEnd: (DragEndDetails details) { - if (_controllerWasPlaying && - controller.value.position != controller.value.duration.end) { + if (_controllerWasPlaying && controller.value.position != controller.value.duration.end) { controller.play(); } }, diff --git a/packages/video_player_videohole/lib/video_player_platform_interface.dart b/packages/video_player_videohole/lib/video_player_platform_interface.dart index 0097a179a..6ddb3aa28 100644 --- a/packages/video_player_videohole/lib/video_player_platform_interface.dart +++ b/packages/video_player_videohole/lib/video_player_platform_interface.dart @@ -346,11 +346,7 @@ class VideoEvent { @override int get hashCode => - eventType.hashCode ^ - duration.hashCode ^ - size.hashCode ^ - buffered.hashCode ^ - text.hashCode; + eventType.hashCode ^ duration.hashCode ^ size.hashCode ^ buffered.hashCode ^ text.hashCode; } /// Type of the event. @@ -454,8 +450,7 @@ class DurationRange { } @override - String toString() => - '${objectRuntimeType(this, 'DurationRange')}(start: $start, end: $end)'; + String toString() => '${objectRuntimeType(this, 'DurationRange')}(start: $start, end: $end)'; @override bool operator ==(Object other) => diff --git a/packages/wearable_rotary/CHANGELOG.md b/packages/wearable_rotary/CHANGELOG.md index 6a509fb24..47bf3e18e 100644 --- a/packages/wearable_rotary/CHANGELOG.md +++ b/packages/wearable_rotary/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 2.0.4 - Upgrades `compileSdkVersion` to 35 diff --git a/packages/wearable_rotary/example/lib/main.dart b/packages/wearable_rotary/example/lib/main.dart index b9b32fe12..367df3fc9 100644 --- a/packages/wearable_rotary/example/lib/main.dart +++ b/packages/wearable_rotary/example/lib/main.dart @@ -73,9 +73,7 @@ class RotaryScrollPage extends StatelessWidget { return Scaffold( appBar: AppBar( title: Text( - scrollDirection == Axis.vertical - ? 'VerticalScrollView' - : 'HorizontalScrollView', + scrollDirection == Axis.vertical ? 'VerticalScrollView' : 'HorizontalScrollView', ), ), body: Center( diff --git a/packages/webview_flutter/CHANGELOG.md b/packages/webview_flutter/CHANGELOG.md index 164c8e0d3..d3720af7f 100644 --- a/packages/webview_flutter/CHANGELOG.md +++ b/packages/webview_flutter/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 0.11.0 * Move the native web-engine code behind a `WebViewBackend` interface. diff --git a/packages/webview_flutter/example/integration_test/webview_flutter_test.dart b/packages/webview_flutter/example/integration_test/webview_flutter_test.dart index 1068d5898..ceae1bd66 100644 --- a/packages/webview_flutter/example/integration_test/webview_flutter_test.dart +++ b/packages/webview_flutter/example/integration_test/webview_flutter_test.dart @@ -35,15 +35,15 @@ Future main() async { request.response.close(); }), ); - final String prefixUrl = 'http://${server.address.address}:${server.port}'; - final String primaryUrl = '$prefixUrl/hello.txt'; - final String secondaryUrl = '$prefixUrl/secondary.txt'; - final String headersUrl = '$prefixUrl/headers'; + final prefixUrl = 'http://${server.address.address}:${server.port}'; + final primaryUrl = '$prefixUrl/hello.txt'; + final secondaryUrl = '$prefixUrl/secondary.txt'; + final headersUrl = '$prefixUrl/headers'; testWidgets('loadRequest', (WidgetTester tester) async { - final Completer pageFinished = Completer(); + final pageFinished = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); await controller.setNavigationDelegate( NavigationDelegate(onPageFinished: (_) => pageFinished.complete()), ); @@ -58,9 +58,9 @@ Future main() async { }); testWidgets('runJavaScriptReturningResult', (WidgetTester tester) async { - final Completer pageFinished = Completer(); + final pageFinished = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.setNavigationDelegate( NavigationDelegate(onPageFinished: (_) => pageFinished.complete()), @@ -71,20 +71,15 @@ Future main() async { await pageFinished.future; - await expectLater( - controller.runJavaScriptReturningResult('1 + 1'), - completion(2), - ); + await expectLater(controller.runJavaScriptReturningResult('1 + 1'), completion(2)); }); testWidgets('loadRequest with headers', (WidgetTester tester) async { - final Map headers = { - 'test_header': 'flutter_test_header', - }; + final headers = {'test_header': 'flutter_test_header'}; - final StreamController pageLoads = StreamController(); + final pageLoads = StreamController(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.setNavigationDelegate( NavigationDelegate(onPageFinished: (String url) => pageLoads.add(url)), @@ -96,23 +91,21 @@ Future main() async { await pageLoads.stream.firstWhere((String url) => url == headersUrl); - final String content = - await controller.runJavaScriptReturningResult( - 'document.documentElement.innerText', - ) + final content = + await controller.runJavaScriptReturningResult('document.documentElement.innerText') as String; expect(content.contains('flutter_test_header'), isTrue); }); testWidgets('JavascriptChannel', (WidgetTester tester) async { - final Completer pageFinished = Completer(); - final WebViewController controller = WebViewController(); + final pageFinished = Completer(); + final controller = WebViewController(); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.setNavigationDelegate( NavigationDelegate(onPageFinished: (_) => pageFinished.complete()), ); - final Completer channelCompleter = Completer(); + final channelCompleter = Completer(); await controller.addJavaScriptChannel( 'Echo', onMessageReceived: (JavaScriptMessage message) { @@ -120,9 +113,7 @@ Future main() async { }, ); - await controller.loadHtmlString( - 'data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+', - ); + await controller.loadHtmlString('data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+'); await tester.pumpWidget(WebViewWidget(controller: controller)); @@ -133,11 +124,11 @@ Future main() async { }); testWidgets('resize webview', (WidgetTester tester) async { - final Completer initialResizeCompleter = Completer(); - final Completer buttonTapResizeCompleter = Completer(); - final Completer onPageFinished = Completer(); + final initialResizeCompleter = Completer(); + final buttonTapResizeCompleter = Completer(); + final onPageFinished = Completer(); - bool resizeButtonTapped = false; + var resizeButtonTapped = false; await tester.pumpWidget( ResizableWebView( onResize: () { @@ -153,10 +144,7 @@ Future main() async { await onPageFinished.future; // Wait for a potential call to resize after page is loaded. - await initialResizeCompleter.future.timeout( - const Duration(seconds: 3), - onTimeout: () => null, - ); + await initialResizeCompleter.future.timeout(const Duration(seconds: 3), onTimeout: () => null); resizeButtonTapped = true; @@ -167,9 +155,9 @@ Future main() async { }); testWidgets('set custom userAgent', (WidgetTester tester) async { - final Completer pageFinished = Completer(); + final pageFinished = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.setNavigationDelegate( NavigationDelegate(onPageFinished: (_) => pageFinished.complete()), @@ -186,7 +174,7 @@ Future main() async { }); testWidgets('getTitle', (WidgetTester tester) async { - const String getTitleTest = ''' + const getTitleTest = ''' Some title @@ -194,12 +182,10 @@ Future main() async { '''; - final String getTitleTestBase64 = base64Encode( - const Utf8Encoder().convert(getTitleTest), - ); - final Completer pageLoaded = Completer(); + final String getTitleTestBase64 = base64Encode(const Utf8Encoder().convert(getTitleTest)); + final pageLoaded = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.setNavigationDelegate( NavigationDelegate(onPageFinished: (_) => pageLoaded.complete()), @@ -224,7 +210,7 @@ Future main() async { group('Programmatic Scroll', () { testWidgets('setAndGetScrollPosition', (WidgetTester tester) async { - const String scrollTestPage = ''' + const scrollTestPage = ''' @@ -245,12 +231,10 @@ Future main() async { '''; - final String scrollTestPageBase64 = base64Encode( - const Utf8Encoder().convert(scrollTestPage), - ); + final String scrollTestPageBase64 = base64Encode(const Utf8Encoder().convert(scrollTestPage)); - final Completer pageLoaded = Completer(); - final WebViewController controller = WebViewController(); + final pageLoaded = Completer(); + final controller = WebViewController(); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.setNavigationDelegate( NavigationDelegate(onPageFinished: (_) => pageLoaded.complete()), @@ -268,8 +252,8 @@ Future main() async { Offset scrollPos = await controller.getScrollPosition(); // Check scrollTo() - const int X_SCROLL = 123; - const int Y_SCROLL = 321; + const X_SCROLL = 123; + const Y_SCROLL = 321; // Get the initial position; this ensures that scrollTo is actually // changing something, but also gives the native view's scroll position // time to settle. @@ -281,11 +265,7 @@ Future main() async { // keeps the test stable on slower software-GL rendering (e.g. emulators). Future pollScrollPosition(int expectedX, int expectedY) async { Offset pos = await controller.getScrollPosition(); - for ( - int i = 0; - i < 20 && (pos.dx != expectedX || pos.dy != expectedY); - i++ - ) { + for (var i = 0; i < 20 && (pos.dx != expectedX || pos.dy != expectedY); i++) { await Future.delayed(const Duration(milliseconds: 100)); pos = await controller.getScrollPosition(); } @@ -306,15 +286,15 @@ Future main() async { }); group('NavigationDelegate', () { - const String blankPage = ''; - final String blankPageEncoded = + const blankPage = ''; + final blankPageEncoded = 'data:text/html;charset=utf-8;base64,' '${base64Encode(const Utf8Encoder().convert(blankPage))}'; testWidgets('can allow requests', (WidgetTester tester) async { - Completer pageLoaded = Completer(); + var pageLoaded = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.setNavigationDelegate( NavigationDelegate( @@ -342,10 +322,9 @@ Future main() async { }); testWidgets('onWebResourceError', (WidgetTester tester) async { - final Completer errorCompleter = - Completer(); + final errorCompleter = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.setNavigationDelegate( NavigationDelegate( @@ -362,14 +341,11 @@ Future main() async { expect(error, isNotNull); }); - testWidgets('onWebResourceError is not called with valid url', ( - WidgetTester tester, - ) async { - final Completer errorCompleter = - Completer(); - final Completer pageFinishCompleter = Completer(); + testWidgets('onWebResourceError is not called with valid url', (WidgetTester tester) async { + final errorCompleter = Completer(); + final pageFinishCompleter = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.setNavigationDelegate( NavigationDelegate( @@ -390,9 +366,9 @@ Future main() async { }); testWidgets('can block requests', (WidgetTester tester) async { - Completer pageLoaded = Completer(); + var pageLoaded = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.setNavigationDelegate( NavigationDelegate( @@ -412,26 +388,20 @@ Future main() async { await pageLoaded.future; // Wait for initial page load. pageLoaded = Completer(); - await controller.runJavaScript( - 'location.href = "https://www.youtube.com/"', - ); + await controller.runJavaScript('location.href = "https://www.youtube.com/"'); // There should never be any second page load, since our new URL is // blocked. Still wait for a potential page change for some time in order // to give the test a chance to fail. - await pageLoaded.future.timeout( - const Duration(milliseconds: 500), - onTimeout: () => '', - ); + await pageLoaded.future.timeout(const Duration(milliseconds: 500), onTimeout: () => ''); final String? currentUrl = await controller.currentUrl(); expect(currentUrl, isNot(contains('youtube.com'))); }); testWidgets('onHttpError', (WidgetTester tester) async { - final Completer errorCompleter = - Completer(); + final errorCompleter = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited( controller.setNavigationDelegate( @@ -456,7 +426,7 @@ Future main() async { testWidgets('onHttpError is not called when no HTTP error is received', ( WidgetTester tester, ) async { - const String testPage = ''' + const testPage = ''' @@ -464,11 +434,10 @@ Future main() async { '''; - final Completer errorCompleter = - Completer(); - final Completer pageFinishCompleter = Completer(); + final errorCompleter = Completer(); + final pageFinishCompleter = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited( controller.setNavigationDelegate( @@ -490,9 +459,9 @@ Future main() async { }); testWidgets('supports asynchronous decisions', (WidgetTester tester) async { - Completer pageLoaded = Completer(); + var pageLoaded = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.setNavigationDelegate( NavigationDelegate( @@ -523,10 +492,10 @@ Future main() async { }); testWidgets('can receive url changes', (WidgetTester tester) async { - final Completer pageLoaded = Completer(); + final pageLoaded = Completer(); - final WebViewController controller = WebViewController(); - final Completer urlChangeCompleter = Completer(); + final controller = WebViewController(); + final urlChangeCompleter = Completer(); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.setNavigationDelegate( NavigationDelegate(onPageFinished: (_) => pageLoaded.complete()), @@ -549,16 +518,12 @@ Future main() async { await expectLater(urlChangeCompleter.future, completion(primaryUrl)); }); - testWidgets('can receive updates to history state', ( - WidgetTester tester, - ) async { - final Completer pageLoaded = Completer(); + testWidgets('can receive updates to history state', (WidgetTester tester) async { + final pageLoaded = Completer(); - final NavigationDelegate navigationDelegate = NavigationDelegate( - onPageFinished: (_) => pageLoaded.complete(), - ); + final navigationDelegate = NavigationDelegate(onPageFinished: (_) => pageLoaded.complete()); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.setNavigationDelegate(navigationDelegate); await controller.loadRequest(Uri.parse(primaryUrl)); @@ -567,7 +532,7 @@ Future main() async { await pageLoaded.future; - final Completer urlChangeCompleter = Completer(); + final urlChangeCompleter = Completer(); await controller.setNavigationDelegate( NavigationDelegate( onUrlChange: (UrlChange change) { @@ -576,18 +541,16 @@ Future main() async { ), ); - await controller.runJavaScript( - 'window.history.pushState({}, "", "secondary.txt");', - ); + await controller.runJavaScript('window.history.pushState({}, "", "secondary.txt");'); await expectLater(urlChangeCompleter.future, completion(secondaryUrl)); }); }); testWidgets('clearLocalStorage', (WidgetTester tester) async { - Completer pageLoadCompleter = Completer(); + var pageLoadCompleter = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); await controller.setJavaScriptMode(JavaScriptMode.unrestricted); await controller.setNavigationDelegate( NavigationDelegate(onPageFinished: (_) => pageLoadCompleter.complete()), @@ -600,11 +563,8 @@ Future main() async { pageLoadCompleter = Completer(); await controller.runJavaScript('localStorage.setItem("myCat", "Tom");'); - final String myCatItem = - await controller.runJavaScriptReturningResult( - 'localStorage.getItem("myCat");', - ) - as String; + final myCatItem = + await controller.runJavaScriptReturningResult('localStorage.getItem("myCat");') as String; expect(myCatItem, 'Tom'); await controller.clearLocalStorage(); @@ -621,11 +581,7 @@ Future main() async { } class ResizableWebView extends StatefulWidget { - const ResizableWebView({ - super.key, - required this.onResize, - required this.onPageFinished, - }); + const ResizableWebView({super.key, required this.onResize, required this.onPageFinished}); final VoidCallback onResize; final VoidCallback onPageFinished; @@ -637,9 +593,7 @@ class ResizableWebView extends StatefulWidget { class ResizableWebViewState extends State { late final WebViewController controller = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) - ..setNavigationDelegate( - NavigationDelegate(onPageFinished: (_) => widget.onPageFinished()), - ) + ..setNavigationDelegate(NavigationDelegate(onPageFinished: (_) => widget.onPageFinished())) ..addJavaScriptChannel( 'Resize', onMessageReceived: (_) { diff --git a/packages/webview_flutter/example/lib/main.dart b/packages/webview_flutter/example/lib/main.dart index 7899aa526..51f13510e 100644 --- a/packages/webview_flutter/example/lib/main.dart +++ b/packages/webview_flutter/example/lib/main.dart @@ -155,8 +155,7 @@ class _WebViewExampleState extends State { late final PlatformWebViewControllerCreationParams params; params = const PlatformWebViewControllerCreationParams(); - final WebViewController controller = - WebViewController.fromPlatformCreationParams(params); + final controller = WebViewController.fromPlatformCreationParams(params); // #enddocregion platform_features controller @@ -205,9 +204,7 @@ Page resource error: ..addJavaScriptChannel( 'Toaster', onMessageReceived: (JavaScriptMessage message) { - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text(message.message))); + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message.message))); }, ) ..loadRequest(Uri.parse('https://flutter.dev')); @@ -242,9 +239,7 @@ Page resource error: onPressed: () async { final String? url = await _controller.currentUrl(); if (mounted) { - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text('Favorited $url'))); + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Favorited $url'))); } }, child: const Icon(Icons.favorite), @@ -252,10 +247,8 @@ Page resource error: } Future openDialog(HttpAuthRequest httpRequest) async { - final TextEditingController usernameTextController = - TextEditingController(); - final TextEditingController passwordTextController = - TextEditingController(); + final usernameTextController = TextEditingController(); + final passwordTextController = TextEditingController(); return showDialog( context: context, @@ -390,14 +383,8 @@ class SampleMenu extends StatelessWidget { value: MenuOptions.addToCache, child: Text('Add to cache'), ), - const PopupMenuItem( - value: MenuOptions.listCache, - child: Text('List cache'), - ), - const PopupMenuItem( - value: MenuOptions.clearCache, - child: Text('Clear cache'), - ), + const PopupMenuItem(value: MenuOptions.listCache, child: Text('List cache')), + const PopupMenuItem(value: MenuOptions.clearCache, child: Text('Clear cache')), const PopupMenuItem( value: MenuOptions.navigationDelegate, child: Text('Navigation Delegate example'), @@ -423,14 +410,8 @@ class SampleMenu extends StatelessWidget { value: MenuOptions.transparentBackground, child: Text('Transparent background example'), ), - const PopupMenuItem( - value: MenuOptions.setCookie, - child: Text('Set cookie'), - ), - const PopupMenuItem( - value: MenuOptions.logExample, - child: Text('Log example'), - ), + const PopupMenuItem(value: MenuOptions.setCookie, child: Text('Set cookie')), + const PopupMenuItem(value: MenuOptions.logExample, child: Text('Log example')), const PopupMenuItem( value: MenuOptions.basicAuthentication, child: Text('Basic Authentication Example'), @@ -452,9 +433,8 @@ class SampleMenu extends StatelessWidget { } Future _onListCookies(BuildContext context) async { - final String cookies = - await webViewController.runJavaScriptReturningResult('document.cookie') - as String; + final cookies = + await webViewController.runJavaScriptReturningResult('document.cookie') as String; if (context.mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( @@ -473,9 +453,9 @@ class SampleMenu extends StatelessWidget { 'caches.open("test_caches_entry"); localStorage["test_localStorage"] = "dummy_entry";', ); if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Added a test entry to cache.')), - ); + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('Added a test entry to cache.'))); } } @@ -492,46 +472,31 @@ class SampleMenu extends StatelessWidget { await webViewController.clearCache(); await webViewController.clearLocalStorage(); if (context.mounted) { - ScaffoldMessenger.of( - context, - ).showSnackBar(const SnackBar(content: Text('Cache cleared.'))); + ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Cache cleared.'))); } } Future _onClearCookies(BuildContext context) async { final bool hadCookies = await cookieManager.clearCookies(); - String message = 'There were cookies. Now, they are gone!'; + var message = 'There were cookies. Now, they are gone!'; if (!hadCookies) { message = 'There are no cookies.'; } if (context.mounted) { - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text(message))); + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message))); } } Future _onNavigationDelegateExample() { - final String contentBase64 = base64Encode( - const Utf8Encoder().convert(kNavigationExamplePage), - ); - return webViewController.loadRequest( - Uri.parse('data:text/html;base64,$contentBase64'), - ); + final String contentBase64 = base64Encode(const Utf8Encoder().convert(kNavigationExamplePage)); + return webViewController.loadRequest(Uri.parse('data:text/html;base64,$contentBase64')); } Future _onSetCookie() async { await cookieManager.setCookie( - const WebViewCookie( - name: 'foo', - value: 'bar', - domain: 'httpbin.org', - path: '/anything', - ), - ); - await webViewController.loadRequest( - Uri.parse('https://httpbin.org/anything'), + const WebViewCookie(name: 'foo', value: 'bar', domain: 'httpbin.org', path: '/anything'), ); + await webViewController.loadRequest(Uri.parse('https://httpbin.org/anything')); } Future _onDoPostRequest() { @@ -561,15 +526,11 @@ class SampleMenu extends StatelessWidget { } Future _onJavaScriptAlertExample(BuildContext context) { - webViewController.setOnJavaScriptAlertDialog(( - JavaScriptAlertDialogRequest request, - ) async { + webViewController.setOnJavaScriptAlertDialog((JavaScriptAlertDialogRequest request) async { await _showAlert(context, request.message); }); - webViewController.setOnJavaScriptConfirmDialog(( - JavaScriptConfirmDialogRequest request, - ) async { + webViewController.setOnJavaScriptConfirmDialog((JavaScriptConfirmDialogRequest request) async { final bool result = await _showConfirm(context, request.message); return result; }); @@ -577,11 +538,7 @@ class SampleMenu extends StatelessWidget { webViewController.setOnJavaScriptTextInputDialog(( JavaScriptTextInputDialogRequest request, ) async { - final String result = await _showTextInput( - context, - request.message, - request.defaultText, - ); + final String result = await _showTextInput(context, request.message, request.defaultText); return result; }); @@ -593,9 +550,7 @@ class SampleMenu extends StatelessWidget { return Container(); } final List cookieList = cookies.split(';'); - final Iterable cookieWidgets = cookieList.map( - (String cookie) => Text(cookie), - ); + final Iterable cookieWidgets = cookieList.map((String cookie) => Text(cookie)); return Column( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, @@ -605,9 +560,7 @@ class SampleMenu extends StatelessWidget { static Future _prepareLocalFile() async { final String tmpDir = (await getTemporaryDirectory()).path; - final File indexFile = File( - {tmpDir, 'www', 'index.html'}.join(Platform.pathSeparator), - ); + final indexFile = File({tmpDir, 'www', 'index.html'}.join(Platform.pathSeparator)); await indexFile.create(recursive: true); await indexFile.writeAsString(kLocalExamplePage); @@ -616,19 +569,15 @@ class SampleMenu extends StatelessWidget { } Future _onLogExample() { - webViewController.setOnConsoleMessage(( - JavaScriptConsoleMessage consoleMessage, - ) { - debugPrint( - '== JS == ${consoleMessage.level.name}: ${consoleMessage.message}', - ); + webViewController.setOnConsoleMessage((JavaScriptConsoleMessage consoleMessage) { + debugPrint('== JS == ${consoleMessage.level.name}: ${consoleMessage.message}'); }); return webViewController.loadHtmlString(kLogExamplePage); } Future _promptForUrl(BuildContext context) { - final TextEditingController urlTextController = TextEditingController(); + final urlTextController = TextEditingController(); return showDialog( context: context, @@ -704,11 +653,7 @@ class SampleMenu extends StatelessWidget { false; } - Future _showTextInput( - BuildContext context, - String message, - String? defaultText, - ) async { + Future _showTextInput(BuildContext context, String message, String? defaultText) async { return await showDialog( context: context, builder: (BuildContext ctx) { @@ -745,9 +690,9 @@ class NavigationControls extends StatelessWidget { await webViewController.goBack(); } else { if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('No back history item')), - ); + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('No back history item'))); } } }, @@ -759,17 +704,14 @@ class NavigationControls extends StatelessWidget { await webViewController.goForward(); } else { if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('No forward history item')), - ); + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('No forward history item'))); } } }, ), - IconButton( - icon: const Icon(Icons.replay), - onPressed: () => webViewController.reload(), - ), + IconButton(icon: const Icon(Icons.replay), onPressed: () => webViewController.reload()), ], ); } diff --git a/packages/webview_flutter/lib/src/tizen_webview.dart b/packages/webview_flutter/lib/src/tizen_webview.dart index ca3a0758b..3ee1a0232 100644 --- a/packages/webview_flutter/lib/src/tizen_webview.dart +++ b/packages/webview_flutter/lib/src/tizen_webview.dart @@ -33,22 +33,18 @@ class TizenWebView { Future _onMethodCall(MethodCall call) async { switch (call.method) { case 'javaScriptChannelMessage': - final Map arguments = - (call.arguments as Map).cast(); - final String channel = arguments['channel']! as String; - final String message = arguments['message']! as String; + final Map arguments = (call.arguments as Map) + .cast(); + final channel = arguments['channel']! as String; + final message = arguments['message']! as String; if (_javaScriptChannelParams.containsKey(channel)) { - _javaScriptChannelParams[channel]?.onMessageReceived( - JavaScriptMessage(message: message), - ); + _javaScriptChannelParams[channel]?.onMessageReceived(JavaScriptMessage(message: message)); } return true; } - throw MissingPluginException( - '${call.method} was invoked but has no handler', - ); + throw MissingPluginException('${call.method} was invoked but has no handler'); } Future _invokeChannelMethod(String method, [dynamic arguments]) async { @@ -64,9 +60,7 @@ class TizenWebView { void onCreate(int viewId, bool enginePolicy) { _isCreated = true; _viewId = viewId; - _tizenWebViewChannel = MethodChannel( - kTizenWebViewChannelName + viewId.toString(), - ); + _tizenWebViewChannel = MethodChannel(kTizenWebViewChannelName + viewId.toString()); _tizenWebViewChannel.setMethodCallHandler(_onMethodCall); _invokeChannelMethod('setEnginePolicy', enginePolicy); @@ -76,10 +70,7 @@ class TizenWebView { /// Applies the requested settings before [TizenView] is created. Future _callPendingMethodCalls() async { if (hasNavigationDelegate) { - await _invokeChannelMethod( - 'hasNavigationDelegate', - hasNavigationDelegate, - ); + await _invokeChannelMethod('hasNavigationDelegate', hasNavigationDelegate); } for (final (String method, dynamic arguments) in _pendingMethodCalls) { @@ -108,22 +99,17 @@ class TizenWebView { /// Makes a specific HTTP request ands loads the response in the webview. Future loadRequest(String uri) { - return _invokeChannelMethod('loadRequest', { - 'url': uri, - }); + return _invokeChannelMethod('loadRequest', {'url': uri}); } /// Makes a specific HTTP request with params ands loads the response in the webview. Future loadRequestWithParams(LoadRequestParams params) { - return _invokeChannelMethod( - 'loadRequestWithParams', - { - 'url': params.uri.toString(), - 'body': params.body, - 'method': params.method.index, - 'headers': params.headers, - }, - ); + return _invokeChannelMethod('loadRequestWithParams', { + 'url': params.uri.toString(), + 'body': params.body, + 'method': params.method.index, + 'headers': params.headers, + }); } /// Accessor to the current URL that the WebView is displaying. @@ -152,8 +138,7 @@ class TizenWebView { Future clearCache() => _invokeChannelMethod('clearCache'); /// Clears the local storage used by the [WebView]. - Future clearLocalStorage() => - _invokeChannelMethod('clearLocalStorage'); + Future clearLocalStorage() => _invokeChannelMethod('clearLocalStorage'); /// Sets the JavaScript execution mode to be used by the webview. Future setJavaScriptMode(int javaScriptMode) => @@ -172,10 +157,9 @@ class TizenWebView { /// Returns the scroll position of this view set by [scrollTo]. Future getScrollPosition() async { - final Map? position = - (await _invokeChannelMethod>( - 'getScrollPosition', - ))?.cast(); + final Map? position = (await _invokeChannelMethod>( + 'getScrollPosition', + ))?.cast(); if (position == null) { return Offset.zero; } @@ -187,16 +171,10 @@ class TizenWebView { _invokeChannelMethod('backgroundColor', color.value); /// Adds a new JavaScript channel to the set of enabled channels. - Future addJavaScriptChannel( - JavaScriptChannelParams javaScriptChannelParams, - ) { - _javaScriptChannelParams[javaScriptChannelParams.name] = - javaScriptChannelParams; - - return _invokeChannelMethod( - 'addJavaScriptChannel', - javaScriptChannelParams.name, - ); + Future addJavaScriptChannel(JavaScriptChannelParams javaScriptChannelParams) { + _javaScriptChannelParams[javaScriptChannelParams.name] = javaScriptChannelParams; + + return _invokeChannelMethod('addJavaScriptChannel', javaScriptChannelParams.name); } /// Runs the given JavaScript in the context of the current page. @@ -231,12 +209,10 @@ class TizenWebView { /// Sets whether the WebView should support zooming using its on-screen zoom /// controls and gestures. - Future setSupportZoom(bool support) => - _invokeChannelMethod('enableZoom', support); + Future setSupportZoom(bool support) => _invokeChannelMethod('enableZoom', support); /// Sets the value selected by the user input - Future javaScriptAlertReply() => - _invokeChannelMethod('javaScriptAlertReply'); + Future javaScriptAlertReply() => _invokeChannelMethod('javaScriptAlertReply'); /// Sets the value selected by the user input Future javaScriptConfirmReply(bool result) => diff --git a/packages/webview_flutter/lib/src/tizen_webview_controller.dart b/packages/webview_flutter/lib/src/tizen_webview_controller.dart index b6909e1bc..ae6c108ef 100644 --- a/packages/webview_flutter/lib/src/tizen_webview_controller.dart +++ b/packages/webview_flutter/lib/src/tizen_webview_controller.dart @@ -18,15 +18,13 @@ const String kTizenNavigationDelegateChannelName = 'plugins.flutter.io/tizen_webview_navigation_delegate_'; /// The channel name of [TizenWebViewController]. -const String kTizenWebViewControllerChannelName = - 'plugins.flutter.io/tizen_webview_controller_'; +const String kTizenWebViewControllerChannelName = 'plugins.flutter.io/tizen_webview_controller_'; /// The extension of WebViewController class for the Tizen. extension TizenWebViewControllerExtension on WebViewController { /// Set to engine policy. set tizenEnginePolicy(bool enginePolicy) { - final TizenWebViewController controller = - platform as TizenWebViewController; + final controller = platform as TizenWebViewController; controller._enginePolicy = enginePolicy; } } @@ -34,21 +32,16 @@ extension TizenWebViewControllerExtension on WebViewController { /// An implementation of [PlatformWebViewController] using the Tizen WebView API. class TizenWebViewController extends PlatformWebViewController { /// Constructs a [TizenWebViewController]. - TizenWebViewController(super.params) - : _webview = TizenWebView(), - super.implementation(); + TizenWebViewController(super.params) : _webview = TizenWebView(), super.implementation(); final TizenWebView _webview; late TizenNavigationDelegate _tizenNavigationDelegate; void Function(JavaScriptConsoleMessage consoleMessage)? _onConsoleLogCallback; - Future Function(JavaScriptAlertDialogRequest request)? - _onJavaScriptAlert; - Future Function(JavaScriptConfirmDialogRequest request)? - _onJavaScriptConfirm; - Future Function(JavaScriptTextInputDialogRequest request)? - _onJavaScriptPrompt; + Future Function(JavaScriptAlertDialogRequest request)? _onJavaScriptAlert; + Future Function(JavaScriptConfirmDialogRequest request)? _onJavaScriptConfirm; + Future Function(JavaScriptTextInputDialogRequest request)? _onJavaScriptPrompt; late final MethodChannel _webviewControllerChannel; @@ -60,8 +53,8 @@ class TizenWebViewController extends PlatformWebViewController { kTizenWebViewControllerChannelName + viewId.toString(), ); _webviewControllerChannel.setMethodCallHandler((MethodCall call) async { - final Map arguments = - (call.arguments as Map).cast(); + final Map arguments = (call.arguments as Map) + .cast(); switch (call.method) { case 'onConsoleMessage': JavaScriptLogLevel level = JavaScriptLogLevel.log; @@ -80,59 +73,50 @@ class TizenWebViewController extends PlatformWebViewController { if (_onConsoleLogCallback != null) { _onConsoleLogCallback!( - JavaScriptConsoleMessage( - level: level, - message: arguments['message']! as String, - ), + JavaScriptConsoleMessage(level: level, message: arguments['message']! as String), ); } return null; case 'onJavaScriptAlert': - final Future Function(JavaScriptAlertDialogRequest)? callback = - _onJavaScriptAlert; + final Future Function(JavaScriptAlertDialogRequest)? callback = _onJavaScriptAlert; if (callback != null) { - final JavaScriptAlertDialogRequest request = - JavaScriptAlertDialogRequest( - message: arguments['message']! as String, - url: arguments['url']! as String, - ); + final request = JavaScriptAlertDialogRequest( + message: arguments['message']! as String, + url: arguments['url']! as String, + ); await callback.call(request); await _webview.javaScriptAlertReply(); } return null; case 'onJavaScriptConfirm': - final Future Function(JavaScriptConfirmDialogRequest)? - callback = _onJavaScriptConfirm; + final Future Function(JavaScriptConfirmDialogRequest)? callback = + _onJavaScriptConfirm; if (callback != null) { - final JavaScriptConfirmDialogRequest request = - JavaScriptConfirmDialogRequest( - message: arguments['message']! as String, - url: arguments['url']! as String, - ); + final request = JavaScriptConfirmDialogRequest( + message: arguments['message']! as String, + url: arguments['url']! as String, + ); final bool result = await callback.call(request); await _webview.javaScriptConfirmReply(result); } return null; case 'onJavaScriptPrompt': - final Future Function(JavaScriptTextInputDialogRequest)? - callback = _onJavaScriptPrompt; + final Future Function(JavaScriptTextInputDialogRequest)? callback = + _onJavaScriptPrompt; if (callback != null) { - final JavaScriptTextInputDialogRequest request = - JavaScriptTextInputDialogRequest( - message: arguments['message']! as String, - url: arguments['url']! as String, - defaultText: arguments['defaultText']! as String, - ); + final request = JavaScriptTextInputDialogRequest( + message: arguments['message']! as String, + url: arguments['url']! as String, + defaultText: arguments['defaultText']! as String, + ); final String result = await callback.call(request); await _webview.javaScriptPromptReply(result); } return null; } - throw MissingPluginException( - '${call.method} was invoked but has no handler', - ); + throw MissingPluginException('${call.method} was invoked but has no handler'); }); } @@ -166,9 +150,7 @@ class TizenWebViewController extends PlatformWebViewController { @override Future loadRequest(LoadRequestParams params) { if (!params.uri.hasScheme) { - throw ArgumentError( - 'LoadRequestParams#uri is required to have a scheme.', - ); + throw ArgumentError('LoadRequestParams#uri is required to have a scheme.'); } switch (params.method) { case LoadRequestMethod.get: @@ -221,9 +203,7 @@ class TizenWebViewController extends PlatformWebViewController { Future clearLocalStorage() => _webview.clearLocalStorage(); @override - Future setPlatformNavigationDelegate( - covariant TizenNavigationDelegate handler, - ) async { + Future setPlatformNavigationDelegate(covariant TizenNavigationDelegate handler) async { _tizenNavigationDelegate = handler; if (_webview.hasNavigationDelegate) { _tizenNavigationDelegate.createNavigationDelegateChannel(_webview.viewId); @@ -233,17 +213,15 @@ class TizenWebViewController extends PlatformWebViewController { } @override - Future runJavaScript(String javaScript) => - _webview.runJavaScript(javaScript); + Future runJavaScript(String javaScript) => _webview.runJavaScript(javaScript); @override Future runJavaScriptReturningResult(String javaScript) => _webview.runJavaScriptReturningResult(javaScript); @override - Future addJavaScriptChannel( - JavaScriptChannelParams javaScriptChannelParams, - ) => _webview.addJavaScriptChannel(javaScriptChannelParams); + Future addJavaScriptChannel(JavaScriptChannelParams javaScriptChannelParams) => + _webview.addJavaScriptChannel(javaScriptChannelParams); @override Future removeJavaScriptChannel(String javaScriptChannelName) async { @@ -269,21 +247,18 @@ class TizenWebViewController extends PlatformWebViewController { Future enableZoom(bool enabled) => _webview.setSupportZoom(enabled); @override - Future setBackgroundColor(Color color) => - _webview.setBackgroundColor(color); + Future setBackgroundColor(Color color) => _webview.setBackgroundColor(color); @override Future setJavaScriptMode(JavaScriptMode javaScriptMode) => _webview.setJavaScriptMode(javaScriptMode.index); @override - Future setUserAgent(String? userAgent) => - _webview.setUserAgent(userAgent); + Future setUserAgent(String? userAgent) => _webview.setUserAgent(userAgent); @override Future setOnScrollPositionChange( - void Function(ScrollPositionChange scrollPositionChange)? - onScrollPositionChange, + void Function(ScrollPositionChange scrollPositionChange)? onScrollPositionChange, ) async { throw UnimplementedError( 'This version of `TizenWebViewController` currently has no ' @@ -315,24 +290,21 @@ class TizenWebViewController extends PlatformWebViewController { @override Future setOnJavaScriptAlertDialog( - Future Function(JavaScriptAlertDialogRequest request) - onJavaScriptAlertDialog, + Future Function(JavaScriptAlertDialogRequest request) onJavaScriptAlertDialog, ) async { _onJavaScriptAlert = onJavaScriptAlertDialog; } @override Future setOnJavaScriptConfirmDialog( - Future Function(JavaScriptConfirmDialogRequest request) - onJavaScriptConfirmDialog, + Future Function(JavaScriptConfirmDialogRequest request) onJavaScriptConfirmDialog, ) async { _onJavaScriptConfirm = onJavaScriptConfirmDialog; } @override Future setOnJavaScriptTextInputDialog( - Future Function(JavaScriptTextInputDialogRequest request) - onJavaScriptTextInputDialog, + Future Function(JavaScriptTextInputDialogRequest request) onJavaScriptTextInputDialog, ) async { _onJavaScriptPrompt = onJavaScriptTextInputDialog; } @@ -370,8 +342,7 @@ class TizenWebViewWidget extends PlatformWebViewWidget { key: params.key, viewType: 'plugins.flutter.io/webview', onPlatformViewCreated: (int id) { - final TizenWebViewController controller = - params.controller as TizenWebViewController; + final controller = params.controller as TizenWebViewController; controller.onCreate(id); }, layoutDirection: params.layoutDirection, @@ -453,9 +424,7 @@ class TizenWebResourceError extends WebResourceError { return WebResourceErrorType.authentication; } - throw ArgumentError( - 'Could not find a WebResourceErrorType for errorCode: $errorCode', - ); + throw ArgumentError('Could not find a WebResourceErrorType for errorCode: $errorCode'); } } @@ -480,8 +449,8 @@ class TizenNavigationDelegate extends PlatformNavigationDelegate { kTizenNavigationDelegateChannelName + viewId.toString(), ); _navigationDelegateChannel.setMethodCallHandler((MethodCall call) async { - final Map arguments = - (call.arguments as Map).cast(); + final Map arguments = (call.arguments as Map) + .cast(); switch (call.method) { case 'navigationRequest': @@ -537,16 +506,11 @@ class TizenNavigationDelegate extends PlatformNavigationDelegate { return null; } - throw MissingPluginException( - '${call.method} was invoked but has no handler', - ); + throw MissingPluginException('${call.method} was invoked but has no handler'); }); } - Future _handleNavigation( - String url, { - required bool isForMainFrame, - }) async { + Future _handleNavigation(String url, {required bool isForMainFrame}) async { final NavigationRequestCallback? onNavigationRequest = _onNavigationRequest; if (onNavigationRequest == null) { @@ -557,8 +521,7 @@ class TizenNavigationDelegate extends PlatformNavigationDelegate { NavigationRequest(url: url, isMainFrame: isForMainFrame), ); - if (returnValue is NavigationDecision && - returnValue == NavigationDecision.navigate) { + if (returnValue is NavigationDecision && returnValue == NavigationDecision.navigate) { return true; } else if (returnValue is Future) { return returnValue.then((NavigationDecision shouldLoadUrl) { @@ -572,9 +535,7 @@ class TizenNavigationDelegate extends PlatformNavigationDelegate { } @override - Future setOnNavigationRequest( - NavigationRequestCallback onNavigationRequest, - ) async { + Future setOnNavigationRequest(NavigationRequestCallback onNavigationRequest) async { _onNavigationRequest = onNavigationRequest; } @@ -599,9 +560,7 @@ class TizenNavigationDelegate extends PlatformNavigationDelegate { } @override - Future setOnWebResourceError( - WebResourceErrorCallback onWebResourceError, - ) async { + Future setOnWebResourceError(WebResourceErrorCallback onWebResourceError) async { _onWebResourceError = onWebResourceError; } @@ -611,9 +570,7 @@ class TizenNavigationDelegate extends PlatformNavigationDelegate { } @override - Future setOnHttpAuthRequest( - HttpAuthRequestCallback onHttpAuthRequest, - ) async { + Future setOnHttpAuthRequest(HttpAuthRequestCallback onHttpAuthRequest) async { throw UnimplementedError( 'This version of `TizenNavigationDelegate` currently has no ' 'implementation for `setOnHttpAuthRequest`', diff --git a/packages/webview_flutter/lib/src/tizen_webview_cookie_manager.dart b/packages/webview_flutter/lib/src/tizen_webview_cookie_manager.dart index e34c861c7..c924f511a 100644 --- a/packages/webview_flutter/lib/src/tizen_webview_cookie_manager.dart +++ b/packages/webview_flutter/lib/src/tizen_webview_cookie_manager.dart @@ -18,16 +18,13 @@ class TizenWebViewCookieManager extends PlatformWebViewCookieManager { @override Future clearCookies() async { - return await _cookieManagerChannel.invokeMethod('clearCookies') ?? - false; + return await _cookieManagerChannel.invokeMethod('clearCookies') ?? false; } @override Future setCookie(WebViewCookie cookie) async { if (!_isValidPath(cookie.path)) { - throw ArgumentError( - 'The path property for the provided cookie was not given a legal value.', - ); + throw ArgumentError('The path property for the provided cookie was not given a legal value.'); } throw UnimplementedError( 'This version of `TizenWebViewCookieManager` currently has no ' diff --git a/packages/webview_flutter/lib/src/tizen_webview_platform.dart b/packages/webview_flutter/lib/src/tizen_webview_platform.dart index f64c97747..c94658493 100644 --- a/packages/webview_flutter/lib/src/tizen_webview_platform.dart +++ b/packages/webview_flutter/lib/src/tizen_webview_platform.dart @@ -25,9 +25,7 @@ class TizenWebViewPlatform extends WebViewPlatform { } @override - PlatformWebViewWidget createPlatformWebViewWidget( - PlatformWebViewWidgetCreationParams params, - ) { + PlatformWebViewWidget createPlatformWebViewWidget(PlatformWebViewWidgetCreationParams params) { return TizenWebViewWidget(params); } diff --git a/packages/webview_flutter_lwe/CHANGELOG.md b/packages/webview_flutter_lwe/CHANGELOG.md index d0529344e..7a1f4dff3 100644 --- a/packages/webview_flutter_lwe/CHANGELOG.md +++ b/packages/webview_flutter_lwe/CHANGELOG.md @@ -1,3 +1,8 @@ +## NEXT + +* Omit obvious local variable types. +* Reformat with a line length of 100. + ## 0.5.6 * Update webview_flutter to 4.14.1. diff --git a/packages/webview_flutter_lwe/example/integration_test/webview_flutter_test.dart b/packages/webview_flutter_lwe/example/integration_test/webview_flutter_test.dart index 131b47a14..a4fcccb81 100644 --- a/packages/webview_flutter_lwe/example/integration_test/webview_flutter_test.dart +++ b/packages/webview_flutter_lwe/example/integration_test/webview_flutter_test.dart @@ -38,15 +38,15 @@ Future main() async { request.response.close(); }), ); - final String prefixUrl = 'http://${server.address.address}:${server.port}'; - final String primaryUrl = '$prefixUrl/hello.txt'; - final String secondaryUrl = '$prefixUrl/secondary.txt'; - final String cookieUrl = '$prefixUrl/cookie'; + final prefixUrl = 'http://${server.address.address}:${server.port}'; + final primaryUrl = '$prefixUrl/hello.txt'; + final secondaryUrl = '$prefixUrl/secondary.txt'; + final cookieUrl = '$prefixUrl/cookie'; testWidgets('loadRequest', (WidgetTester tester) async { - final Completer pageFinished = Completer(); + final pageFinished = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); unawaited( controller.setNavigationDelegate( NavigationDelegate(onPageFinished: (_) => pageFinished.complete()), @@ -63,9 +63,9 @@ Future main() async { }); testWidgets('getCookies', (WidgetTester tester) async { - final Completer pageFinished = Completer(); + final pageFinished = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); unawaited( controller.setNavigationDelegate( NavigationDelegate(onPageFinished: (_) => pageFinished.complete()), @@ -87,9 +87,9 @@ Future main() async { }); testWidgets('runJavaScriptReturningResult', (WidgetTester tester) async { - final Completer pageFinished = Completer(); + final pageFinished = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited( controller.setNavigationDelegate( @@ -102,15 +102,12 @@ Future main() async { await pageFinished.future; - await expectLater( - controller.runJavaScriptReturningResult('1 + 1'), - completion(2), - ); + await expectLater(controller.runJavaScriptReturningResult('1 + 1'), completion(2)); }); testWidgets('JavascriptChannel', (WidgetTester tester) async { - final Completer pageFinished = Completer(); - final WebViewController controller = WebViewController(); + final pageFinished = Completer(); + final controller = WebViewController(); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited( controller.setNavigationDelegate( @@ -118,7 +115,7 @@ Future main() async { ), ); - final Completer channelCompleter = Completer(); + final channelCompleter = Completer(); await controller.addJavaScriptChannel( 'Echo', onMessageReceived: (JavaScriptMessage message) { @@ -126,9 +123,7 @@ Future main() async { }, ); - await controller.loadHtmlString( - 'data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+', - ); + await controller.loadHtmlString('data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+'); await tester.pumpWidget(WebViewWidget(controller: controller)); @@ -139,11 +134,11 @@ Future main() async { }); testWidgets('resize webview', (WidgetTester tester) async { - final Completer initialResizeCompleter = Completer(); - final Completer buttonTapResizeCompleter = Completer(); - final Completer onPageFinished = Completer(); + final initialResizeCompleter = Completer(); + final buttonTapResizeCompleter = Completer(); + final onPageFinished = Completer(); - bool resizeButtonTapped = false; + var resizeButtonTapped = false; await tester.pumpWidget( ResizableWebView( onResize: () { @@ -159,10 +154,7 @@ Future main() async { await onPageFinished.future; // Wait for a potential call to resize after page is loaded. - await initialResizeCompleter.future.timeout( - const Duration(seconds: 3), - onTimeout: () => null, - ); + await initialResizeCompleter.future.timeout(const Duration(seconds: 3), onTimeout: () => null); resizeButtonTapped = true; @@ -173,9 +165,9 @@ Future main() async { }); testWidgets('set custom userAgent', (WidgetTester tester) async { - final Completer pageFinished = Completer(); + final pageFinished = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited( controller.setNavigationDelegate( @@ -194,7 +186,7 @@ Future main() async { }); testWidgets('getTitle', (WidgetTester tester) async { - const String getTitleTest = ''' + const getTitleTest = ''' Some title @@ -202,12 +194,10 @@ Future main() async { '''; - final String getTitleTestBase64 = base64Encode( - const Utf8Encoder().convert(getTitleTest), - ); - final Completer pageLoaded = Completer(); + final String getTitleTestBase64 = base64Encode(const Utf8Encoder().convert(getTitleTest)); + final pageLoaded = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited( controller.setNavigationDelegate( @@ -215,9 +205,7 @@ Future main() async { ), ); unawaited( - controller.loadRequest( - Uri.parse('data:text/html;charset=utf-8;base64,$getTitleTestBase64'), - ), + controller.loadRequest(Uri.parse('data:text/html;charset=utf-8;base64,$getTitleTestBase64')), ); await tester.pumpWidget(WebViewWidget(controller: controller)); @@ -236,7 +224,7 @@ Future main() async { group('Programmatic Scroll', () { testWidgets('setAndGetScrollPosition', (WidgetTester tester) async { - const String scrollTestPage = ''' + const scrollTestPage = ''' @@ -257,12 +245,10 @@ Future main() async { '''; - final String scrollTestPageBase64 = base64Encode( - const Utf8Encoder().convert(scrollTestPage), - ); + final String scrollTestPageBase64 = base64Encode(const Utf8Encoder().convert(scrollTestPage)); - final Completer pageLoaded = Completer(); - final WebViewController controller = WebViewController(); + final pageLoaded = Completer(); + final controller = WebViewController(); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited( controller.setNavigationDelegate( @@ -271,9 +257,7 @@ Future main() async { ); unawaited( controller.loadRequest( - Uri.parse( - 'data:text/html;charset=utf-8;base64,$scrollTestPageBase64', - ), + Uri.parse('data:text/html;charset=utf-8;base64,$scrollTestPageBase64'), ), ); @@ -286,8 +270,8 @@ Future main() async { Offset scrollPos = await controller.getScrollPosition(); // Check scrollTo() - const int X_SCROLL = 123; - const int Y_SCROLL = 321; + const X_SCROLL = 123; + const Y_SCROLL = 321; // Get the initial position; this ensures that scrollTo is actually // changing something, but also gives the native view's scroll position // time to settle. @@ -308,15 +292,15 @@ Future main() async { }); group('NavigationDelegate', () { - const String blankPage = ''; - final String blankPageEncoded = + const blankPage = ''; + final blankPageEncoded = 'data:text/html;charset=utf-8;base64,' '${base64Encode(const Utf8Encoder().convert(blankPage))}'; testWidgets('can allow requests', (WidgetTester tester) async { - Completer pageLoaded = Completer(); + var pageLoaded = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited( controller.setNavigationDelegate( @@ -346,10 +330,9 @@ Future main() async { }); testWidgets('onWebResourceError', (WidgetTester tester) async { - final Completer errorCompleter = - Completer(); + final errorCompleter = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited( controller.setNavigationDelegate( @@ -360,9 +343,7 @@ Future main() async { ), ), ); - unawaited( - controller.loadRequest(Uri.parse('https://www.notawebsite..com')), - ); + unawaited(controller.loadRequest(Uri.parse('https://www.notawebsite..com'))); await tester.pumpWidget(WebViewWidget(controller: controller)); @@ -370,14 +351,11 @@ Future main() async { expect(error, isNotNull); }); - testWidgets('onWebResourceError is not called with valid url', ( - WidgetTester tester, - ) async { - final Completer errorCompleter = - Completer(); - final Completer pageFinishCompleter = Completer(); + testWidgets('onWebResourceError is not called with valid url', (WidgetTester tester) async { + final errorCompleter = Completer(); + final pageFinishCompleter = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited( controller.setNavigationDelegate( @@ -402,9 +380,9 @@ Future main() async { }); testWidgets('can block requests', (WidgetTester tester) async { - Completer pageLoaded = Completer(); + var pageLoaded = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited( controller.setNavigationDelegate( @@ -426,25 +404,20 @@ Future main() async { await pageLoaded.future; // Wait for initial page load. pageLoaded = Completer(); - await controller.runJavaScript( - 'location.href = "https://www.youtube.com/"', - ); + await controller.runJavaScript('location.href = "https://www.youtube.com/"'); // There should never be any second page load, since our new URL is // blocked. Still wait for a potential page change for some time in order // to give the test a chance to fail. - await pageLoaded.future.timeout( - const Duration(milliseconds: 500), - onTimeout: () => '', - ); + await pageLoaded.future.timeout(const Duration(milliseconds: 500), onTimeout: () => ''); final String? currentUrl = await controller.currentUrl(); expect(currentUrl, isNot(contains('youtube.com'))); }); testWidgets('supports asynchronous decisions', (WidgetTester tester) async { - Completer pageLoaded = Completer(); + var pageLoaded = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited( controller.setNavigationDelegate( @@ -477,9 +450,9 @@ Future main() async { }); testWidgets('can receive url changes', (WidgetTester tester) async { - final Completer pageLoaded = Completer(); + final pageLoaded = Completer(); - final WebViewController controller = WebViewController(); + final controller = WebViewController(); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited( controller.setNavigationDelegate( @@ -492,7 +465,7 @@ Future main() async { await pageLoaded.future; - final Completer urlChangeCompleter = Completer(); + final urlChangeCompleter = Completer(); await controller.setNavigationDelegate( NavigationDelegate( onUrlChange: (UrlChange change) { @@ -509,11 +482,7 @@ Future main() async { } class ResizableWebView extends StatefulWidget { - const ResizableWebView({ - super.key, - required this.onResize, - required this.onPageFinished, - }); + const ResizableWebView({super.key, required this.onResize, required this.onPageFinished}); final VoidCallback onResize; final VoidCallback onPageFinished; @@ -525,9 +494,7 @@ class ResizableWebView extends StatefulWidget { class ResizableWebViewState extends State { late final WebViewController controller = WebViewController() ..setJavaScriptMode(JavaScriptMode.unrestricted) - ..setNavigationDelegate( - NavigationDelegate(onPageFinished: (_) => widget.onPageFinished()), - ) + ..setNavigationDelegate(NavigationDelegate(onPageFinished: (_) => widget.onPageFinished())) ..addJavaScriptChannel( 'Resize', onMessageReceived: (_) { diff --git a/packages/webview_flutter_lwe/example/lib/main.dart b/packages/webview_flutter_lwe/example/lib/main.dart index 4e4f242e9..0ab47f525 100644 --- a/packages/webview_flutter_lwe/example/lib/main.dart +++ b/packages/webview_flutter_lwe/example/lib/main.dart @@ -118,8 +118,7 @@ class _WebViewExampleState extends State { late final PlatformWebViewControllerCreationParams params; params = const PlatformWebViewControllerCreationParams(); - final WebViewController controller = - WebViewController.fromPlatformCreationParams(params); + final controller = WebViewController.fromPlatformCreationParams(params); // #enddocregion platform_features controller @@ -170,9 +169,7 @@ Page resource error: ..addJavaScriptChannel( 'Toaster', onMessageReceived: (JavaScriptMessage message) { - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text(message.message))); + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message.message))); }, ) ..loadRequest(Uri.parse('https://flutter.dev')); @@ -207,9 +204,7 @@ Page resource error: onPressed: () async { final String? url = await _controller.currentUrl(); if (mounted) { - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text('Favorited $url'))); + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Favorited $url'))); } }, child: const Icon(Icons.favorite), @@ -217,10 +212,8 @@ Page resource error: } Future openDialog(HttpAuthRequest httpRequest) async { - final TextEditingController usernameTextController = - TextEditingController(); - final TextEditingController passwordTextController = - TextEditingController(); + final usernameTextController = TextEditingController(); + final passwordTextController = TextEditingController(); return showDialog( context: context, @@ -352,14 +345,8 @@ class SampleMenu extends StatelessWidget { value: MenuOptions.addToCache, child: Text('Add to cache'), ), - const PopupMenuItem( - value: MenuOptions.listCache, - child: Text('List cache'), - ), - const PopupMenuItem( - value: MenuOptions.clearCache, - child: Text('Clear cache'), - ), + const PopupMenuItem(value: MenuOptions.listCache, child: Text('List cache')), + const PopupMenuItem(value: MenuOptions.clearCache, child: Text('Clear cache')), const PopupMenuItem( value: MenuOptions.navigationDelegate, child: Text('Navigation Delegate example'), @@ -385,14 +372,8 @@ class SampleMenu extends StatelessWidget { value: MenuOptions.transparentBackground, child: Text('Transparent background example'), ), - const PopupMenuItem( - value: MenuOptions.setCookie, - child: Text('Set cookie'), - ), - const PopupMenuItem( - value: MenuOptions.logExample, - child: Text('Log example'), - ), + const PopupMenuItem(value: MenuOptions.setCookie, child: Text('Set cookie')), + const PopupMenuItem(value: MenuOptions.logExample, child: Text('Log example')), const PopupMenuItem( value: MenuOptions.basicAuthentication, child: Text('Basic Authentication Example'), @@ -410,9 +391,7 @@ class SampleMenu extends StatelessWidget { } Future _onListCookies(BuildContext context) async { - final Uri? domain = Uri.tryParse( - (await webViewController.currentUrl()) ?? '', - ); + final Uri? domain = Uri.tryParse((await webViewController.currentUrl()) ?? ''); final List cookies; if (domain == null) { @@ -439,9 +418,9 @@ class SampleMenu extends StatelessWidget { 'caches.open("test_caches_entry"); localStorage["test_localStorage"] = "dummy_entry";', ); if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Added a test entry to cache.')), - ); + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('Added a test entry to cache.'))); } } @@ -459,46 +438,31 @@ class SampleMenu extends StatelessWidget { // This is unimplemented in webview_flutter_lwe. // await webViewController.clearLocalStorage(); if (context.mounted) { - ScaffoldMessenger.of( - context, - ).showSnackBar(const SnackBar(content: Text('Cache cleared.'))); + ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Cache cleared.'))); } } Future _onClearCookies(BuildContext context) async { final bool hadCookies = await cookieManager.clearCookies(); - String message = 'There were cookies. Now, they are gone!'; + var message = 'There were cookies. Now, they are gone!'; if (!hadCookies) { message = 'There are no cookies.'; } if (context.mounted) { - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text(message))); + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message))); } } Future _onNavigationDelegateExample() { - final String contentBase64 = base64Encode( - const Utf8Encoder().convert(kNavigationExamplePage), - ); - return webViewController.loadRequest( - Uri.parse('data:text/html;base64,$contentBase64'), - ); + final String contentBase64 = base64Encode(const Utf8Encoder().convert(kNavigationExamplePage)); + return webViewController.loadRequest(Uri.parse('data:text/html;base64,$contentBase64')); } Future _onSetCookie() async { await cookieManager.setCookie( - const WebViewCookie( - name: 'foo', - value: 'bar', - domain: 'httpbin.org', - path: '/anything', - ), - ); - await webViewController.loadRequest( - Uri.parse('https://httpbin.org/anything'), + const WebViewCookie(name: 'foo', value: 'bar', domain: 'httpbin.org', path: '/anything'), ); + await webViewController.loadRequest(Uri.parse('https://httpbin.org/anything')); } Future _onDoPostRequest() { @@ -544,9 +508,7 @@ class SampleMenu extends StatelessWidget { static Future _prepareLocalFile() async { final String tmpDir = (await getTemporaryDirectory()).path; - final File indexFile = File( - {tmpDir, 'www', 'index.html'}.join(Platform.pathSeparator), - ); + final indexFile = File({tmpDir, 'www', 'index.html'}.join(Platform.pathSeparator)); await indexFile.create(recursive: true); await indexFile.writeAsString(kLocalExamplePage); @@ -555,19 +517,15 @@ class SampleMenu extends StatelessWidget { } Future _onLogExample() { - webViewController.setOnConsoleMessage(( - JavaScriptConsoleMessage consoleMessage, - ) { - debugPrint( - '== JS == ${consoleMessage.level.name}: ${consoleMessage.message}', - ); + webViewController.setOnConsoleMessage((JavaScriptConsoleMessage consoleMessage) { + debugPrint('== JS == ${consoleMessage.level.name}: ${consoleMessage.message}'); }); return webViewController.loadHtmlString(kLogExamplePage); } Future _promptForUrl(BuildContext context) { - final TextEditingController urlTextController = TextEditingController(); + final urlTextController = TextEditingController(); return showDialog( context: context, @@ -615,9 +573,9 @@ class NavigationControls extends StatelessWidget { await webViewController.goBack(); } else { if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('No back history item')), - ); + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('No back history item'))); } } }, @@ -629,17 +587,14 @@ class NavigationControls extends StatelessWidget { await webViewController.goForward(); } else { if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('No forward history item')), - ); + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('No forward history item'))); } } }, ), - IconButton( - icon: const Icon(Icons.replay), - onPressed: () => webViewController.reload(), - ), + IconButton(icon: const Icon(Icons.replay), onPressed: () => webViewController.reload()), ], ); } diff --git a/packages/webview_flutter_lwe/lib/src/lwe_webview.dart b/packages/webview_flutter_lwe/lib/src/lwe_webview.dart index 112edab07..ab0d52345 100644 --- a/packages/webview_flutter_lwe/lib/src/lwe_webview.dart +++ b/packages/webview_flutter_lwe/lib/src/lwe_webview.dart @@ -29,22 +29,18 @@ class LweWebView { Future _onMethodCall(MethodCall call) async { switch (call.method) { case 'javaScriptChannelMessage': - final Map arguments = - (call.arguments as Map).cast(); - final String channel = arguments['channel']! as String; - final String message = arguments['message']! as String; + final Map arguments = (call.arguments as Map) + .cast(); + final channel = arguments['channel']! as String; + final message = arguments['message']! as String; if (_javaScriptChannelParams.containsKey(channel)) { - _javaScriptChannelParams[channel]?.onMessageReceived( - JavaScriptMessage(message: message), - ); + _javaScriptChannelParams[channel]?.onMessageReceived(JavaScriptMessage(message: message)); } return true; } - throw MissingPluginException( - '${call.method} was invoked but has no handler', - ); + throw MissingPluginException('${call.method} was invoked but has no handler'); } Future _invokeChannelMethod(String method, [dynamic arguments]) async { @@ -59,9 +55,7 @@ class LweWebView { /// Called when [TizenView] is created. Invokes the requested method call before [LweWebView] is created. void onCreate(int viewId) { _isCreated = true; - _lweWebViewChannel = MethodChannel( - kLweWebViewChannelName + viewId.toString(), - ); + _lweWebViewChannel = MethodChannel(kLweWebViewChannelName + viewId.toString()); _lweWebViewChannel.setMethodCallHandler(_onMethodCall); _callPendingMethodCalls(); @@ -70,10 +64,7 @@ class LweWebView { /// Applies the requested settings before [TizenView] is created. Future _callPendingMethodCalls() async { if (hasNavigationDelegate) { - await _invokeChannelMethod( - 'hasNavigationDelegate', - hasNavigationDelegate, - ); + await _invokeChannelMethod('hasNavigationDelegate', hasNavigationDelegate); } for (final (String method, dynamic arguments) in _pendingMethodCalls) { @@ -102,9 +93,7 @@ class LweWebView { /// Makes a specific HTTP request ands loads the response in the webview. Future loadRequest(String uri) { - return _invokeChannelMethod('loadRequest', { - 'url': uri, - }); + return _invokeChannelMethod('loadRequest', {'url': uri}); } /// Accessor to the current URL that the WebView is displaying. @@ -149,10 +138,9 @@ class LweWebView { /// Returns the current scroll position of this view. Future getScrollPosition() async { - final Map? position = - (await _invokeChannelMethod>( - 'getScrollPosition', - ))?.cast(); + final Map? position = (await _invokeChannelMethod>( + 'getScrollPosition', + ))?.cast(); if (position == null) { return Offset.zero; } @@ -164,42 +152,29 @@ class LweWebView { _invokeChannelMethod('backgroundColor', color.value); /// Adds a new JavaScript channel to the set of enabled channels. - Future addJavaScriptChannel( - JavaScriptChannelParams javaScriptChannelParams, - ) { + Future addJavaScriptChannel(JavaScriptChannelParams javaScriptChannelParams) { // When JavaScript channel with the same name exists make sure to remove it // before registering the new channel. if (_javaScriptChannelParams.containsKey(javaScriptChannelParams.name)) { - _invokeChannelMethod( - 'removeJavaScriptChannel', - javaScriptChannelParams.name, - ); + _invokeChannelMethod('removeJavaScriptChannel', javaScriptChannelParams.name); } - _javaScriptChannelParams[javaScriptChannelParams.name] = - javaScriptChannelParams; + _javaScriptChannelParams[javaScriptChannelParams.name] = javaScriptChannelParams; - return _invokeChannelMethod( - 'addJavaScriptChannel', - javaScriptChannelParams.name, - ); + return _invokeChannelMethod('addJavaScriptChannel', javaScriptChannelParams.name); } /// Removes the JavaScript channel with the matching name from the set of /// enabled channels. Future removeJavaScriptChannel(String javaScriptChannelName) async { - final JavaScriptChannelParams? params = - _javaScriptChannelParams[javaScriptChannelName]; + final JavaScriptChannelParams? params = _javaScriptChannelParams[javaScriptChannelName]; if (params == null) { return; } _javaScriptChannelParams.remove(javaScriptChannelName); - return _invokeChannelMethod( - 'removeJavaScriptChannel', - javaScriptChannelName, - ); + return _invokeChannelMethod('removeJavaScriptChannel', javaScriptChannelName); } /// Runs the given JavaScript in the context of the current page. diff --git a/packages/webview_flutter_lwe/lib/src/lwe_webview_controller.dart b/packages/webview_flutter_lwe/lib/src/lwe_webview_controller.dart index 91fb54fa9..350f80aa5 100644 --- a/packages/webview_flutter_lwe/lib/src/lwe_webview_controller.dart +++ b/packages/webview_flutter_lwe/lib/src/lwe_webview_controller.dart @@ -19,9 +19,7 @@ const String kLweNavigationDelegateChannelName = /// An implementation of [PlatformWebViewController] using the Lightweight Web Engine. class LweWebViewController extends PlatformWebViewController { /// Constructs a [LweWebViewController]. - LweWebViewController(super.params) - : _webview = LweWebView(), - super.implementation(); + LweWebViewController(super.params) : _webview = LweWebView(), super.implementation(); final LweWebView _webview; late LweNavigationDelegate _lweNavigationDelegate; @@ -57,9 +55,7 @@ class LweWebViewController extends PlatformWebViewController { @override Future loadRequest(LoadRequestParams params) { if (!params.uri.hasScheme) { - throw ArgumentError( - 'LoadRequestParams#uri is required to have a scheme.', - ); + throw ArgumentError('LoadRequestParams#uri is required to have a scheme.'); } switch (params.method) { @@ -135,13 +131,10 @@ class LweWebViewController extends PlatformWebViewController { } @override - Future setBackgroundColor(Color color) => - _webview.setBackgroundColor(color); + Future setBackgroundColor(Color color) => _webview.setBackgroundColor(color); @override - Future setPlatformNavigationDelegate( - covariant LweNavigationDelegate handler, - ) async { + Future setPlatformNavigationDelegate(covariant LweNavigationDelegate handler) async { _lweNavigationDelegate = handler; _webview.hasNavigationDelegate = true; // If the view has already been created, the previous delegate's method @@ -156,30 +149,26 @@ class LweWebViewController extends PlatformWebViewController { } @override - Future addJavaScriptChannel( - JavaScriptChannelParams javaScriptChannelParams, - ) => _webview.addJavaScriptChannel(javaScriptChannelParams); + Future addJavaScriptChannel(JavaScriptChannelParams javaScriptChannelParams) => + _webview.addJavaScriptChannel(javaScriptChannelParams); @override Future removeJavaScriptChannel(String javaScriptChannelName) => _webview.removeJavaScriptChannel(javaScriptChannelName); @override - Future runJavaScript(String javaScript) => - _webview.runJavaScript(javaScript); + Future runJavaScript(String javaScript) => _webview.runJavaScript(javaScript); @override Future runJavaScriptReturningResult(String javaScript) => _webview.runJavaScriptReturningResult(javaScript); @override - Future setUserAgent(String? userAgent) => - _webview.setUserAgent(userAgent); + Future setUserAgent(String? userAgent) => _webview.setUserAgent(userAgent); @override Future setOnScrollPositionChange( - void Function(ScrollPositionChange scrollPositionChange)? - onScrollPositionChange, + void Function(ScrollPositionChange scrollPositionChange)? onScrollPositionChange, ) async { throw UnimplementedError( 'This version of `LweWebViewController` currently has no ' @@ -214,8 +203,7 @@ class LweWebViewController extends PlatformWebViewController { @override Future setOnJavaScriptAlertDialog( - Future Function(JavaScriptAlertDialogRequest request) - onJavaScriptAlertDialog, + Future Function(JavaScriptAlertDialogRequest request) onJavaScriptAlertDialog, ) async { throw UnimplementedError( 'This version of `LweWebViewController` currently has no ' @@ -225,8 +213,7 @@ class LweWebViewController extends PlatformWebViewController { @override Future setOnJavaScriptConfirmDialog( - Future Function(JavaScriptConfirmDialogRequest request) - onJavaScriptConfirmDialog, + Future Function(JavaScriptConfirmDialogRequest request) onJavaScriptConfirmDialog, ) async { throw UnimplementedError( 'This version of `LweWebViewController` currently has no ' @@ -236,8 +223,7 @@ class LweWebViewController extends PlatformWebViewController { @override Future setOnJavaScriptTextInputDialog( - Future Function(JavaScriptTextInputDialogRequest request) - onJavaScriptTextInputDialog, + Future Function(JavaScriptTextInputDialogRequest request) onJavaScriptTextInputDialog, ) async { throw UnimplementedError( 'This version of `LweWebViewController` currently has no ' @@ -278,8 +264,7 @@ class LweWebViewWidget extends PlatformWebViewWidget { key: params.key, viewType: 'plugins.flutter.io/webview', onPlatformViewCreated: (int id) { - final LweWebViewController controller = - params.controller as LweWebViewController; + final controller = params.controller as LweWebViewController; controller.onCreate(id); }, layoutDirection: params.layoutDirection, @@ -381,9 +366,7 @@ class LweWebResourceError extends WebResourceError { return WebResourceErrorType.tooManyRequests; } - throw ArgumentError( - 'Could not find a WebResourceErrorType for errorCode: $errorCode', - ); + throw ArgumentError('Could not find a WebResourceErrorType for errorCode: $errorCode'); } } @@ -412,8 +395,8 @@ class LweNavigationDelegate extends PlatformNavigationDelegate { kLweNavigationDelegateChannelName + viewId.toString(), ); _navigationDelegateChannel.setMethodCallHandler((MethodCall call) async { - final Map arguments = - (call.arguments as Map).cast(); + final Map arguments = (call.arguments as Map) + .cast(); switch (call.method) { case 'navigationRequest': @@ -455,16 +438,11 @@ class LweNavigationDelegate extends PlatformNavigationDelegate { return null; } - throw MissingPluginException( - '${call.method} was invoked but has no handler', - ); + throw MissingPluginException('${call.method} was invoked but has no handler'); }); } - Future _handleNavigation( - String url, { - required bool isForMainFrame, - }) async { + Future _handleNavigation(String url, {required bool isForMainFrame}) async { final NavigationRequestCallback? onNavigationRequest = _onNavigationRequest; if (onNavigationRequest == null) { @@ -475,8 +453,7 @@ class LweNavigationDelegate extends PlatformNavigationDelegate { NavigationRequest(url: url, isMainFrame: isForMainFrame), ); - if (returnValue is NavigationDecision && - returnValue == NavigationDecision.navigate) { + if (returnValue is NavigationDecision && returnValue == NavigationDecision.navigate) { return true; } else if (returnValue is Future) { return returnValue.then((NavigationDecision shouldLoadUrl) { @@ -490,9 +467,7 @@ class LweNavigationDelegate extends PlatformNavigationDelegate { } @override - Future setOnNavigationRequest( - NavigationRequestCallback onNavigationRequest, - ) async { + Future setOnNavigationRequest(NavigationRequestCallback onNavigationRequest) async { _onNavigationRequest = onNavigationRequest; } @@ -520,9 +495,7 @@ class LweNavigationDelegate extends PlatformNavigationDelegate { } @override - Future setOnWebResourceError( - WebResourceErrorCallback onWebResourceError, - ) async { + Future setOnWebResourceError(WebResourceErrorCallback onWebResourceError) async { _onWebResourceError = onWebResourceError; } @@ -532,9 +505,7 @@ class LweNavigationDelegate extends PlatformNavigationDelegate { } @override - Future setOnHttpAuthRequest( - HttpAuthRequestCallback onHttpAuthRequest, - ) async { + Future setOnHttpAuthRequest(HttpAuthRequestCallback onHttpAuthRequest) async { throw UnimplementedError( 'This version of `LweNavigationDelegate` currently has no ' 'implementation for `setOnHttpAuthRequest`', diff --git a/packages/webview_flutter_lwe/lib/src/lwe_webview_cookie_manager.dart b/packages/webview_flutter_lwe/lib/src/lwe_webview_cookie_manager.dart index 195a83fca..f7b74d94a 100644 --- a/packages/webview_flutter_lwe/lib/src/lwe_webview_cookie_manager.dart +++ b/packages/webview_flutter_lwe/lib/src/lwe_webview_cookie_manager.dart @@ -18,8 +18,7 @@ class LweWebViewCookieManager extends PlatformWebViewCookieManager { @override Future clearCookies() async { - return await _cookieManagerChannel.invokeMethod('clearCookies') ?? - false; + return await _cookieManagerChannel.invokeMethod('clearCookies') ?? false; } @override @@ -49,9 +48,7 @@ class LweWebViewCookieManager extends PlatformWebViewCookieManager { @override Future setCookie(WebViewCookie cookie) async { if (!_isValidPath(cookie.path)) { - throw ArgumentError( - 'The path property for the provided cookie was not given a legal value.', - ); + throw ArgumentError('The path property for the provided cookie was not given a legal value.'); } throw UnimplementedError( 'This version of `LweWebViewCookieManager` currently has no ' diff --git a/packages/webview_flutter_lwe/lib/src/lwe_webview_platform.dart b/packages/webview_flutter_lwe/lib/src/lwe_webview_platform.dart index a2d30eaaa..677b924f3 100644 --- a/packages/webview_flutter_lwe/lib/src/lwe_webview_platform.dart +++ b/packages/webview_flutter_lwe/lib/src/lwe_webview_platform.dart @@ -25,9 +25,7 @@ class LweWebViewPlatform extends WebViewPlatform { } @override - PlatformWebViewWidget createPlatformWebViewWidget( - PlatformWebViewWidgetCreationParams params, - ) { + PlatformWebViewWidget createPlatformWebViewWidget(PlatformWebViewWidgetCreationParams params) { return LweWebViewWidget(params); } diff --git a/tools/lib/src/build_examples_command.dart b/tools/lib/src/build_examples_command.dart index a9fa71def..e94d2356c 100644 --- a/tools/lib/src/build_examples_command.dart +++ b/tools/lib/src/build_examples_command.dart @@ -19,9 +19,9 @@ class BuildExamplesCommand extends PackageLoopingCommand { @override Future runForPackage(RepositoryPackage package) async { - final List errors = []; + final errors = []; - bool builtSomething = false; + var builtSomething = false; for (final RepositoryPackage example in package.getExamples()) { int exitCode = await processRunner.runAndStream( 'flutter-tizen', @@ -56,8 +56,6 @@ class BuildExamplesCommand extends PackageLoopingCommand { errors.add('No examples found'); } - return errors.isEmpty - ? PackageResult.success() - : PackageResult.fail(errors); + return errors.isEmpty ? PackageResult.success() : PackageResult.fail(errors); } } diff --git a/tools/lib/src/device.dart b/tools/lib/src/device.dart index 9457853e6..14b4a8e32 100644 --- a/tools/lib/src/device.dart +++ b/tools/lib/src/device.dart @@ -25,8 +25,8 @@ class Device { this.profile, { required TizenSdk tizenSdk, ProcessRunner processRunner = const ProcessRunner(), - }) : _tizenSdk = tizenSdk, - _processRunner = processRunner; + }) : _tizenSdk = tizenSdk, + _processRunner = processRunner; /// Creates a new physical Tizen device reference. /// @@ -37,7 +37,7 @@ class Device { required TizenSdk tizenSdk, ProcessRunner processRunner = const ProcessRunner(), }) { - final Device device = Device._( + final device = Device._( name, profile, tizenSdk: tizenSdk, @@ -99,7 +99,7 @@ class Device { String? _findSerial() { final List deviceInfos = _tizenSdk.sdbDevices(); - for (final SdbDeviceInfo deviceInfo in deviceInfos) { + for (final deviceInfo in deviceInfos) { if (deviceInfo.name == name) { return deviceInfo.serial; } @@ -130,10 +130,9 @@ class Device { workingDirectory: workingDir, ); - bool timedOut = false; - final Stream streamLines = process.stdout - .transform(const Utf8Decoder()) - .transform(const LineSplitter()); + var timedOut = false; + final Stream streamLines = + process.stdout.transform(const Utf8Decoder()).transform(const LineSplitter()); final Future timedExitCode = process.exitCode.timeout( timeout, @@ -143,8 +142,8 @@ class Device { }, ); - String lastLine = ''; - final Completer completer = Completer(); + var lastLine = ''; + final completer = Completer(); streamLines.listen((String line) { lastLine = line; print(line); @@ -155,19 +154,16 @@ class Device { String? error; if (timedOut) { - error = - 'Timeout expired. The test may need more time to finish. ' + error = 'Timeout expired. The test may need more time to finish. ' 'If you expect the test to finish before timeout, check if the tests ' 'require device screen to be awake or if they require manually ' 'clicking the UI button for permissions.'; } else if (lastLine.contains('No tests ran')) { - error = - 'Missing integration tests (use --exclude if this is intentional).'; + error = 'Missing integration tests (use --exclude if this is intentional).'; } else if (lastLine.contains('No devices found')) { error = 'Device was disconnected during test.'; } else if (lastLine.contains('failed')) { - error = - 'flutter-tizen test integration_test failed, see the output ' + error = 'flutter-tizen test integration_test failed, see the output ' 'above for details.'; } else if (!lastLine.contains('passed')) { error = 'Could not parse the log output.'; @@ -187,7 +183,7 @@ class EmulatorDevice extends Device { required TizenSdk tizenSdk, ProcessRunner processRunner = const ProcessRunner(), }) { - final EmulatorDevice emulatorDevice = EmulatorDevice._( + final emulatorDevice = EmulatorDevice._( name, profile, tizenSdk: tizenSdk, @@ -229,10 +225,9 @@ class EmulatorDevice extends Device { throw ToolExit(result.exitCode); } - final List emulatorNames = - LineSplitter.split( - result.stdout as String, - ).map((String name) => name.trim()).toList(); + final List emulatorNames = LineSplitter.split( + result.stdout as String, + ).map((String name) => name.trim()).toList(); return emulatorNames.contains(name); } @@ -248,13 +243,16 @@ class EmulatorDevice extends Device { platform = '$profile-x86'; break; } - await _processRunner.runAndStream(_tizenSdk.emCli.path, [ - 'create', - '-n', - name, - '-p', - platform, - ], exitOnError: true); + await _processRunner.runAndStream( + _tizenSdk.emCli.path, + [ + 'create', + '-n', + name, + '-p', + platform, + ], + exitOnError: true); } /// Grants all privacy-related permissions to apps by default. @@ -265,7 +263,7 @@ class EmulatorDevice extends Device { return false; } final Map capability = _tizenSdk.sdbCapability(serial!); - final bool rooted = capability['rootonoff_support'] == 'enabled'; + final rooted = capability['rootonoff_support'] == 'enabled'; if (!rooted) { return false; } @@ -286,7 +284,7 @@ class EmulatorDevice extends Device { 'touch', '/opt/share/askuser_disable', ]); - final String stdout = result.stdout as String; + final stdout = result.stdout as String; if (result.exitCode != 0 || stdout.trim().isNotEmpty) { print('Error: running sdb shell command failed: $stdout'); return false; @@ -316,15 +314,18 @@ class EmulatorDevice extends Device { print('Device $name ($profile) is already launched.'); return; } - await _processRunner.runAndStream(_tizenSdk.emCli.path, [ - 'launch', - '-n', - name, - ], exitOnError: true); + await _processRunner.runAndStream( + _tizenSdk.emCli.path, + [ + 'launch', + '-n', + name, + ], + exitOnError: true); await _poll(() { final List deviceInfos = _tizenSdk.sdbDevices(); - for (final SdbDeviceInfo deviceInfo in deviceInfos) { + for (final deviceInfo in deviceInfos) { if (deviceInfo.name == name && deviceInfo.status == 'device') { return true; } @@ -352,7 +353,7 @@ class EmulatorDevice extends Device { await _poll(() { final List deviceInfos = _tizenSdk.sdbDevices(); - for (final SdbDeviceInfo deviceInfo in deviceInfos) { + for (final deviceInfo in deviceInfos) { if (deviceInfo.name == name) { return false; } @@ -368,7 +369,7 @@ class EmulatorDevice extends Device { Duration interval = const Duration(seconds: 1), Duration timeout = const Duration(minutes: 5), }) async { - final DateTime start = DateTime.now(); + final start = DateTime.now(); while (DateTime.now().difference(start) <= timeout) { if (await function()) { return; @@ -383,8 +384,8 @@ class EmulatorDevice extends Device { Directory workingDir, Duration timeout, ) async { - bool autoLaunched = false; - bool autoCreated = false; + var autoLaunched = false; + var autoCreated = false; try { if (!exists) { autoCreated = true; diff --git a/tools/lib/src/integration_test_command.dart b/tools/lib/src/integration_test_command.dart index bd4c0a9b8..3b90aef1f 100644 --- a/tools/lib/src/integration_test_command.dart +++ b/tools/lib/src/integration_test_command.dart @@ -88,8 +88,7 @@ class IntegrationTestCommand extends PackageLoopingCommand { final String name = 'integration-test'; @override - final String description = - 'Runs integration tests for plugin example apps.\n\n' + final String description = 'Runs integration tests for plugin example apps.\n\n' 'This command requires "flutter-tizen" to be in your path.'; @override @@ -122,8 +121,7 @@ class IntegrationTestCommand extends PackageLoopingCommand { throw ToolExit(exitCommandFoundErrors); } try { - final YamlMap yamlMap = - loadYaml(recipeFile.readAsStringSync()) as YamlMap; + final yamlMap = loadYaml(recipeFile.readAsStringSync()) as YamlMap; _recipe = Recipe.fromYaml(yamlMap); } on YamlException { print('Invalid YAML file.'); @@ -132,7 +130,7 @@ class IntegrationTestCommand extends PackageLoopingCommand { } late io.ProcessResult processResult; - for (int attempts = 0; attempts < 5; attempts++) { + for (var attempts = 0; attempts < 5; attempts++) { // This operation often fails with an exit code 128. processResult = await processRunner.run( 'flutter-tizen', @@ -160,11 +158,10 @@ class IntegrationTestCommand extends PackageLoopingCommand { yield* super.getTargetPackages(filterExcluded: filterExcluded); } else { final Recipe recipe = _recipe!; - final List packages = await super - .getTargetPackages(filterExcluded: filterExcluded) - .toList(); + final List packages = + await super.getTargetPackages(filterExcluded: filterExcluded).toList(); - for (final PackageEnumerationEntry package in packages) { + for (final package in packages) { final String packageName = package.package.displayName; if (!recipe.contains(packageName)) { continue; @@ -180,7 +177,7 @@ class IntegrationTestCommand extends PackageLoopingCommand { @override Future runForPackage(RepositoryPackage package) async { - List profiles = []; + var profiles = []; if (argResults!.wasParsed(_profilesArg)) { profiles = getStringListArg(_profilesArg) .map((String profile) => Profile.fromString(profile)) @@ -199,9 +196,8 @@ class IntegrationTestCommand extends PackageLoopingCommand { final List examples = package.getExamples().toList(); if (examples.isEmpty) { - return PackageResult.fail([ - 'Missing example directory (use --exclude if this is intentional).' - ]); + return PackageResult.fail( + ['Missing example directory (use --exclude if this is intentional).']); } io.ProcessResult processResult = await processRunner.run( @@ -210,31 +206,27 @@ class IntegrationTestCommand extends PackageLoopingCommand { workingDir: package.directory, ); if (processResult.exitCode != 0) { - return PackageResult.fail([ - 'Command pub get failed. Make sure the pubspec file in your project is valid.' - ]); + return PackageResult.fail( + ['Command pub get failed. Make sure the pubspec file in your project is valid.']); } // Number of test = examples * profiles - final List errors = []; - for (final RepositoryPackage example in examples) { + final errors = []; + for (final example in examples) { if (!example.pubspecFile.existsSync()) { errors.add('Missing pubspec file in ${example.path}.'); continue; } - final Directory integrationTestDir = - example.directory.childDirectory('integration_test'); - if (!integrationTestDir.existsSync() || - integrationTestDir.listSync().isEmpty) { + final Directory integrationTestDir = example.directory.childDirectory('integration_test'); + if (!integrationTestDir.existsSync() || integrationTestDir.listSync().isEmpty) { errors.add('Missing integration tests in ${example.path} ' '(use --exclude if this is intentional).'); continue; } - for (final Device device in devices) { - String? error = - await device.runIntegrationTest(example.directory, _timeout); + for (final device in devices) { + String? error = await device.runIntegrationTest(example.directory, _timeout); if (error != null) { // Tests may fail unexpectedly on a self-hosted runner. Try again. error = await device.runIntegrationTest(example.directory, _timeout); @@ -254,14 +246,12 @@ class IntegrationTestCommand extends PackageLoopingCommand { logWarning('Failed to clean ${package.displayName} after build.'); } - return errors.isEmpty - ? PackageResult.success() - : PackageResult.fail(errors); + return errors.isEmpty ? PackageResult.success() : PackageResult.fail(errors); } List _prepareNewEmulators(List profiles) { - final List emulators = []; - for (final Profile profile in profiles) { + final emulators = []; + for (final profile in profiles) { emulators.add( EmulatorDevice( '${profile.toString().replaceAll('.', '_')}-${io.pid}', @@ -279,17 +269,15 @@ class IntegrationTestCommand extends PackageLoopingCommand { /// /// If [profiles] is omitted or `null` is passed, returns all connected devices. List _findConnectedDevices([List? profiles]) { - final List devices = []; + final devices = []; final List deviceInfos = _tizenSdk.sdbDevices(); - for (final SdbDeviceInfo deviceInfo in deviceInfos) { - final Map capability = - _tizenSdk.sdbCapability(deviceInfo.serial); + for (final deviceInfo in deviceInfos) { + final Map capability = _tizenSdk.sdbCapability(deviceInfo.serial); final String? deviceType = capability['profile_name']; final String? version = capability['platform_version']; final String? cpuArch = capability['cpu_arch']; if (deviceType == null || version == null || cpuArch == null) { - throw Exception( - 'Cannot extract profile, Tizen version, or cpu arch from ' + throw Exception('Cannot extract profile, Tizen version, or cpu arch from ' 'target ${deviceInfo.serial}.\n' 'profile: $deviceType\n' 'Tizen version: $version\n' @@ -299,7 +287,7 @@ class IntegrationTestCommand extends PackageLoopingCommand { if (profiles != null && !profiles.contains(profile)) { continue; } - final Device device = cpuArch == 'x86' + final device = cpuArch == 'x86' ? Device.emulator( deviceInfo.name, profile, diff --git a/tools/lib/src/main.dart b/tools/lib/src/main.dart index e494597d5..aefd7a016 100644 --- a/tools/lib/src/main.dart +++ b/tools/lib/src/main.dart @@ -20,8 +20,7 @@ import 'publish_command.dart'; void main(List args) { const FileSystem fileSystem = LocalFileSystem(); - Directory packagesDir = - fileSystem.currentDirectory.childDirectory('packages'); + Directory packagesDir = fileSystem.currentDirectory.childDirectory('packages'); if (!packagesDir.existsSync()) { if (fileSystem.currentDirectory.basename == 'packages') { @@ -32,8 +31,7 @@ void main(List args) { } } - final CommandRunner commandRunner = CommandRunner( - './tools/tools_runner.sh', + final commandRunner = CommandRunner('./tools/tools_runner.sh', 'Productivity utils for hosting multiple plugins within one repository.') ..addCommand(AnalyzeCommand(packagesDir)) ..addCommand(BuildExamplesCommand(packagesDir)) @@ -43,7 +41,7 @@ void main(List args) { ..addCommand(PublishCommand(packagesDir)); commandRunner.run(args).catchError((Object e) { - final ToolExit toolExit = e as ToolExit; + final toolExit = e as ToolExit; int exitCode = toolExit.exitCode; // This should never happen; this check is here to guarantee that a ToolExit // never accidentally has code 0 thus causing CI to pass. diff --git a/tools/lib/src/process_runner_apis.dart b/tools/lib/src/process_runner_apis.dart index ebd84c96a..330e21cfc 100644 --- a/tools/lib/src/process_runner_apis.dart +++ b/tools/lib/src/process_runner_apis.dart @@ -41,8 +41,7 @@ extension Synchronous on ProcessRunner { stderrEncoding: stderrEncoding); if (result.exitCode != 0) { if (logOnError) { - final String error = - _getErrorString(executable, args, workingDir: workingDir); + final String error = _getErrorString(executable, args, workingDir: workingDir); print('$error Stderr:\n${result.stdout}'); } if (exitOnError) { @@ -53,9 +52,8 @@ extension Synchronous on ProcessRunner { } /// Copied from [ProcessRunner._getErrorString]. - String _getErrorString(String executable, List args, - {Directory? workingDir}) { - final String workdir = workingDir == null ? '' : ' in ${workingDir.path}'; + String _getErrorString(String executable, List args, {Directory? workingDir}) { + final workdir = workingDir == null ? '' : ' in ${workingDir.path}'; return 'ERROR: Unable to execute "$executable ${args.join(' ')}"$workdir.'; } } diff --git a/tools/lib/src/publish_command.dart b/tools/lib/src/publish_command.dart index 23f2f2ca0..436e24d5c 100644 --- a/tools/lib/src/publish_command.dart +++ b/tools/lib/src/publish_command.dart @@ -16,8 +16,7 @@ import 'package:flutter_plugin_tools/src/common/package_looping_command.dart'; import 'package:flutter_plugin_tools/src/common/process_runner.dart'; import 'package:flutter_plugin_tools/src/common/pub_version_finder.dart'; import 'package:flutter_plugin_tools/src/common/repository_package.dart'; -import 'package:flutter_plugin_tools/src/publish_command.dart' - as flutter_plugin_tools; +import 'package:flutter_plugin_tools/src/publish_command.dart' as flutter_plugin_tools; import 'package:http/http.dart' as http; import 'package:path/path.dart' as p; import 'package:platform/platform.dart'; @@ -55,8 +54,7 @@ class PublishCommand extends PackageLoopingCommand { ); argParser.addFlag( _dryRunFlag, - help: - 'Skips the real `pub publish` command and assumes the command is successful.\n' + help: 'Skips the real `pub publish` command and assumes the command is successful.\n' 'This does not run `pub publish --dry-run`.\n' 'If you want to run the command with `pub publish --dry-run`, use `--pub-publish-flags=--dry-run`', ); @@ -92,8 +90,7 @@ class PublishCommand extends PackageLoopingCommand { String get successSummaryMessage => 'published'; @override - String get failureListHeader => - 'The following packages had failures during publishing:'; + String get failureListHeader => 'The following packages had failures during publishing:'; @override Future initializeRun() async { @@ -112,22 +109,18 @@ class PublishCommand extends PackageLoopingCommand { if (getBoolArg(_allChangedFlag)) { final GitVersionFinder gitVersionFinder = await retrieveVersionFinder(); final String baseSha = await gitVersionFinder.getBaseSha(); - print( - 'Publishing all packages that have changed relative to "$baseSha"\n'); + print('Publishing all packages that have changed relative to "$baseSha"\n'); // final List changedPubspecs = // await gitVersionFinder.getChangedPubSpecs(); - final List changedPubspecs = changedFiles - .where((String file) => file.trim().endsWith('pubspec.yaml')) - .toList(); + final List changedPubspecs = + changedFiles.where((String file) => file.trim().endsWith('pubspec.yaml')).toList(); - for (final String pubspecPath in changedPubspecs) { + for (final pubspecPath in changedPubspecs) { // git outputs a relative, Posix-style path. final File pubspecFile = childFileWithSubcomponents( - packagesDir.fileSystem.directory((await gitDir).path), - p.posix.split(pubspecPath)); - yield PackageEnumerationEntry(RepositoryPackage(pubspecFile.parent), - excluded: false); + packagesDir.fileSystem.directory((await gitDir).path), p.posix.split(pubspecPath)); + yield PackageEnumerationEntry(RepositoryPackage(pubspecFile.parent), excluded: false); } } else { yield* getTargetPackages(filterExcluded: false); @@ -195,19 +188,14 @@ Safe to ignore if the package is deleted in this commit. Future _checkGitStatus(RepositoryPackage package) async { final io.ProcessResult statusResult = await (await gitDir).runCommand( - [ - 'status', - '--porcelain', - '--ignored', - package.directory.absolute.path - ], + ['status', '--porcelain', '--ignored', package.directory.absolute.path], throwOnError: false, ); if (statusResult.exitCode != 0) { return false; } - final String statusOutput = statusResult.stdout as String; + final statusOutput = statusResult.stdout as String; if (statusOutput.isNotEmpty) { printError( "There are files in the package directory that haven't been saved in git. Refusing to publish these files:\n\n" @@ -231,8 +219,7 @@ Safe to ignore if the package is deleted in this commit. workingDir: package.directory, ); if (pubGetResult.exitCode != 0) { - printError( - 'Pub get failed for ${package.directory.basename}, publishing failed.'); + printError('Pub get failed for ${package.directory.basename}, publishing failed.'); return false; } @@ -248,9 +235,8 @@ Safe to ignore if the package is deleted in this commit. ); publish.stdout.transform(utf8.decoder).listen((String data) => print(data)); publish.stderr.transform(utf8.decoder).listen((String data) => print(data)); - _stdinSubscription ??= _stdin - .transform(utf8.decoder) - .listen((String data) => publish.stdin.writeln(data)); + _stdinSubscription ??= + _stdin.transform(utf8.decoder).listen((String data) => publish.stdin.writeln(data)); final int result = await publish.exitCode; if (result != 0) { printError('Publishing ${package.directory.basename} failed.'); @@ -262,11 +248,9 @@ Safe to ignore if the package is deleted in this commit. } void _ensureValidPubCredential() { - final String credentialsPath = - _getCredentialsPath(platform: platform, path: path); + final String credentialsPath = _getCredentialsPath(platform: platform, path: path); final File credentialFile = packagesDir.fileSystem.file(credentialsPath); - if (credentialFile.existsSync() && - credentialFile.readAsStringSync().isNotEmpty) { + if (credentialFile.existsSync() && credentialFile.readAsStringSync().isNotEmpty) { return; } final String? credential = platform.environment[_pubCredentialName]; diff --git a/tools/lib/src/recipe.dart b/tools/lib/src/recipe.dart index 8fa4f2cdf..4be856877 100644 --- a/tools/lib/src/recipe.dart +++ b/tools/lib/src/recipe.dart @@ -13,14 +13,11 @@ class Recipe { /// Creates a [Recipe] instance by parsing [yamlMap]. factory Recipe.fromYaml(YamlMap yamlMap) { - final Map packages = - (yamlMap['plugins'] as YamlMap).cast(); - final Map> profilesPerPackage = - >{}; + final Map packages = (yamlMap['plugins'] as YamlMap).cast(); + final profilesPerPackage = >{}; for (final MapEntry package in packages.entries) { - profilesPerPackage[package.key] = package.value - .map((dynamic profile) => Profile.fromString(profile as String)) - .toList(); + profilesPerPackage[package.key] = + package.value.map((dynamic profile) => Profile.fromString(profile as String)).toList(); } return Recipe._(profilesPerPackage); } @@ -29,8 +26,7 @@ class Recipe { /// Returns `true` if [package] was specified in the recipe file but /// with an empty profile list. - bool isExcluded(String package) => - contains(package) && _profilesPerPackage[package]!.isEmpty; + bool isExcluded(String package) => contains(package) && _profilesPerPackage[package]!.isEmpty; /// Returns `true` if [package] was specified in the recipe file. bool contains(String package) => _profilesPerPackage.containsKey(package); diff --git a/tools/lib/src/tizen_sdk.dart b/tools/lib/src/tizen_sdk.dart index 5c9249304..fa3430584 100644 --- a/tools/lib/src/tizen_sdk.dart +++ b/tools/lib/src/tizen_sdk.dart @@ -95,8 +95,7 @@ class Profile { } final List segments = value.split('-'); final String typeString = segments[0].toLowerCase(); - final String? versionString = - segments.length >= 2 ? segments[1].trim() : null; + final String? versionString = segments.length >= 2 ? segments[1].trim() : null; DeviceType? matchingDeviceType; for (final DeviceType deviceType in DeviceType.values) { @@ -162,14 +161,11 @@ class TizenSdk { if (environment.containsKey(_kTizenSdk)) { tizenHomeDir = fileSystem.directory(environment[_kTizenSdk]); } else if (io.Platform.isLinux || io.Platform.isMacOS) { - tizenHomeDir = fileSystem - .directory(environment['HOME']) - .childDirectory('tizen-studio'); + tizenHomeDir = fileSystem.directory(environment['HOME']).childDirectory('tizen-studio'); } else if (io.Platform.isWindows) { if (environment.containsKey('SystemDrive')) { - tizenHomeDir = fileSystem - .directory(environment['SystemDrive']) - .childDirectory('tizen-studio'); + tizenHomeDir = + fileSystem.directory(environment['SystemDrive']).childDirectory('tizen-studio'); } } if (tizenHomeDir == null || !tizenHomeDir.existsSync()) { @@ -192,9 +188,8 @@ class TizenSdk { final Directory _sdkRoot; /// Cli tool for interacting with connected devices. - File get sdb => _sdkRoot - .childDirectory('tools') - .childFile(io.Platform.isWindows ? 'sdb.exe' : 'sdb'); + File get sdb => + _sdkRoot.childDirectory('tools').childFile(io.Platform.isWindows ? 'sdb.exe' : 'sdb'); /// Tizen SDK's emulator cli. File get emCli => _sdkRoot @@ -205,18 +200,16 @@ class TizenSdk { /// Returns information of all connected devices. List sdbDevices() { - final io.ProcessResult result = - _processRunner.runSync(sdb.path, ['devices']); + final io.ProcessResult result = _processRunner.runSync(sdb.path, ['devices']); if (result.exitCode != 0) { print('Error: running command `sdb devices` failed.'); throw ToolExit(result.exitCode); } - final List deviceInfos = []; - final List lines = - LineSplitter.split((result.stdout as String).trim()).toList(); + final deviceInfos = []; + final List lines = LineSplitter.split((result.stdout as String).trim()).toList(); - for (final String line in lines) { + for (final line in lines) { if (line.startsWith('List of devices')) { continue; } @@ -245,14 +238,12 @@ class TizenSdk { throw ToolExit(result.exitCode); } - final Map capabilities = {}; - final List lines = - LineSplitter.split((result.stdout as String).trim()).toList(); - for (final String line in lines) { + final capabilities = {}; + final List lines = LineSplitter.split((result.stdout as String).trim()).toList(); + for (final line in lines) { final int index = line.indexOf(':'); final String key = line.substring(0, index).trim(); - final String value = - index + 1 > line.length ? '' : line.substring(index + 1).trim(); + final String value = index + 1 > line.length ? '' : line.substring(index + 1).trim(); capabilities[key] = value; } return capabilities; @@ -263,7 +254,7 @@ class TizenSdk { /// /// Returns `null` if emulator [name] is not running. String? findEmulatorPid(String name) { - const ProcessRunner processRunner = ProcessRunner(); + const processRunner = ProcessRunner(); // TODO(HakkyuKim): Support Windows. final io.ProcessResult result = processRunner.runSync('ps', ['aux']); @@ -272,11 +263,10 @@ String? findEmulatorPid(String name) { throw ToolExit(result.exitCode); } - final List lines = LineSplitter.split(result.stdout as String) - .map((String line) => line.trim()) - .toList(); + final List lines = + LineSplitter.split(result.stdout as String).map((String line) => line.trim()).toList(); - for (final String line in lines) { + for (final line in lines) { if (line.contains('emulator-x86_64') && line.contains(name)) { return line.split(RegExp(r'\s+'))[1]; } diff --git a/tools/test/device_test.dart b/tools/test/device_test.dart index 68e1bc273..6cae051c0 100644 --- a/tools/test/device_test.dart +++ b/tools/test/device_test.dart @@ -29,7 +29,7 @@ void main() { late Completer completer; late TizenSdk tizenSdk; - const Duration timeoutLimit = Duration(seconds: 3); + const timeoutLimit = Duration(seconds: 3); setUp(() { processRunner = MockProcessRunner(); @@ -37,11 +37,11 @@ void main() { process = MockProcess(); controller = StreamController(); completer = Completer(); - when(() => process.stdout).thenAnswer((_) => - controller.stream.map>((String event) => event.codeUnits)); + when(() => process.stdout) + .thenAnswer((_) => controller.stream.map>((String event) => event.codeUnits)); when(() => process.exitCode).thenAnswer((_) => completer.future); - when(() => processRunner.start(any(), any(), - workingDirectory: any(named: 'workingDirectory'))) + when(() => + processRunner.start(any(), any(), workingDirectory: any(named: 'workingDirectory'))) .thenAnswer((_) => Future(() => process)); tizenSdk = MockTizenSdk(); when(() => tizenSdk.sdbDevices()).thenReturn([ diff --git a/tools/test/integration/device_test.dart b/tools/test/integration/device_test.dart index 9fb1cf244..5a6984d36 100644 --- a/tools/test/integration/device_test.dart +++ b/tools/test/integration/device_test.dart @@ -18,24 +18,20 @@ import 'package:test/test.dart'; Future _checkSystemRequirements(String emulatorName) async { final TizenSdk tizenSdk = TizenSdk.locateTizenSdk(); - io.ProcessResult result = await io.Process.run( - tizenSdk.emCli.absolute.path, ['list-platform']); + io.ProcessResult result = + await io.Process.run(tizenSdk.emCli.absolute.path, ['list-platform']); - final List platforms = LineSplitter.split(result.stdout as String) - .map((String token) => token.trim()) - .toList(); + final List platforms = + LineSplitter.split(result.stdout as String).map((String token) => token.trim()).toList(); if (!platforms.contains('mobile-6.0-x86')) { throw Exception('Tizen mobile-6.0 emulator package is not installed.'); } - result = - await io.Process.run(tizenSdk.emCli.absolute.path, ['list-vm']); - final List names = LineSplitter.split(result.stdout as String) - .map((String token) => token.trim()) - .toList(); + result = await io.Process.run(tizenSdk.emCli.absolute.path, ['list-vm']); + final List names = + LineSplitter.split(result.stdout as String).map((String token) => token.trim()).toList(); if (names.contains(emulatorName)) { - throw Exception( - 'Emulator name used for test already exists: $emulatorName. ' + throw Exception('Emulator name used for test already exists: $emulatorName. ' 'Emulator name is randomly generated for each test. ' 'Rerun the test to choose a different name.'); } @@ -47,11 +43,10 @@ Future _checkSystemRequirements(String emulatorName) async { } String _getRandomString(int length) { - const String chars = - 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890'; - final Random random = Random(); - return String.fromCharCodes(List.generate( - length, (_) => chars.codeUnitAt(random.nextInt(chars.length)))); + const chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890'; + final random = Random(); + return String.fromCharCodes( + List.generate(length, (_) => chars.codeUnitAt(random.nextInt(chars.length)))); } void main() { @@ -96,8 +91,7 @@ void main() { await io.Process.run('flutter-tizen', ['pub', 'get'], workingDirectory: testDataDir.parent.absolute.path); - final String? error = await device.runIntegrationTest( - testDataDir, const Duration(seconds: 60)); + final String? error = await device.runIntegrationTest(testDataDir, const Duration(seconds: 60)); await io.Process.run('flutter-tizen', ['clean'], workingDirectory: testDataDir.parent.absolute.path); @@ -106,7 +100,7 @@ void main() { tearDown(() async { final List deviceInfos = tizenSdk.sdbDevices(); - for (final SdbDeviceInfo deviceInfo in deviceInfos) { + for (final deviceInfo in deviceInfos) { if (device.name == deviceInfo.name) { final String? pid = findEmulatorPid(device.name); if (pid == null) { @@ -118,13 +112,11 @@ void main() { final io.ProcessResult result = await io.Process.run(tizenSdk.emCli.absolute.path, ['list-vm']); - final List names = LineSplitter.split(result.stdout as String) - .map((String token) => token.trim()) - .toList(); - for (final String name in names) { + final List names = + LineSplitter.split(result.stdout as String).map((String token) => token.trim()).toList(); + for (final name in names) { if (name == device.name) { - await io.Process.run(tizenSdk.emCli.absolute.path, - ['delete', '-n', device.name]); + await io.Process.run(tizenSdk.emCli.absolute.path, ['delete', '-n', device.name]); } } }); diff --git a/tools/test/integration_test_command_test.dart b/tools/test/integration_test_command_test.dart index 9d1a68d0c..9f9c0c484 100644 --- a/tools/test/integration_test_command_test.dart +++ b/tools/test/integration_test_command_test.dart @@ -33,10 +33,7 @@ void main() { // TODO(HakkyuKim): Relocate this step to setup functions for relevant groups // after subclassing [PackageLoopingCommand]. - packagesDir - .childDirectory('a') - .childFile('pubspec.yaml') - .createSync(recursive: true); + packagesDir.childDirectory('a').childFile('pubspec.yaml').createSync(recursive: true); }); group('conflicting options: ', () { @@ -65,8 +62,7 @@ void main() { ); }); - test('--generate-emulators requires either --profiles or --recipe', - () async { + test('--generate-emulators requires either --profiles or --recipe', () async { Error? commandError; final List output = await runCapturingPrint( commandRunner, @@ -115,8 +111,7 @@ void main() { }); test('handle invalid recipe files', () async { - final File recipeFile = packagesDir.childFile('recipe.yaml') - ..createSync(recursive: true); + final File recipeFile = packagesDir.childFile('recipe.yaml')..createSync(recursive: true); recipeFile.writeAsStringSync(''' plugins: a: [ @@ -145,8 +140,7 @@ plugins: }); test('handle empty list packages as excluded', () async { - final File recipeFile = packagesDir.childFile('recipe.yaml') - ..createSync(recursive: true); + final File recipeFile = packagesDir.childFile('recipe.yaml')..createSync(recursive: true); recipeFile.writeAsStringSync(''' plugins: a: [] diff --git a/tools/test/recipe_test.dart b/tools/test/recipe_test.dart index e01fd3f5d..599a60f53 100644 --- a/tools/test/recipe_test.dart +++ b/tools/test/recipe_test.dart @@ -20,7 +20,7 @@ plugins: }); test('correctly parses recipe', () { - final Recipe recipe = Recipe.fromYaml(loadYaml(yamlString) as YamlMap); + final recipe = Recipe.fromYaml(loadYaml(yamlString) as YamlMap); expect(recipe.contains('c'), true); expect(recipe.isExcluded('c'), true); diff --git a/tools/test/utils.dart b/tools/test/utils.dart index 3b3daa610..66f766e8d 100644 --- a/tools/test/utils.dart +++ b/tools/test/utils.dart @@ -16,16 +16,14 @@ Future> runCapturingPrint( Function(Error error)? errorHandler, Function(Exception error)? exceptionHandler, }) async { - final List prints = []; - final ZoneSpecification spec = ZoneSpecification( + final prints = []; + final spec = ZoneSpecification( print: (_, __, ___, String message) { prints.add(message); }, ); try { - await Zone.current - .fork(specification: spec) - .run>(() => runner.run(args)); + await Zone.current.fork(specification: spec).run>(() => runner.run(args)); } on Error catch (e) { if (errorHandler == null) { rethrow; From b249488f03624b91cb61bf530ce5ae33bd3d6451 Mon Sep 17 00:00:00 2001 From: JunsuChoi Date: Wed, 16 Sep 2026 17:21:38 +0900 Subject: [PATCH 2/2] [video_player_videohole] Align FFI code with analysis and format rules --- .../lib/src/ffi_messages.dart | 86 +++++++------------ 1 file changed, 31 insertions(+), 55 deletions(-) diff --git a/packages/video_player_videohole/lib/src/ffi_messages.dart b/packages/video_player_videohole/lib/src/ffi_messages.dart index 88df90687..31f0c6e02 100644 --- a/packages/video_player_videohole/lib/src/ffi_messages.dart +++ b/packages/video_player_videohole/lib/src/ffi_messages.dart @@ -22,7 +22,7 @@ class TrackMessage { /// Serializes this message to a JSON string. String toJson() { - final Map jsonMap = { + final jsonMap = { 'playerId': playerId, 'tracks': tracks, }; @@ -31,8 +31,7 @@ class TrackMessage { /// Deserializes a JSON string into a [TrackMessage]. static TrackMessage fromJson(String jsonString) { - final Map jsonMap = - jsonDecode(jsonString) as Map; + final jsonMap = jsonDecode(jsonString) as Map; return TrackMessage( playerId: jsonMap['playerId'] as int, tracks: (jsonMap['tracks'] as List) @@ -82,7 +81,7 @@ class CreateMessage { /// Serializes this message to a JSON string. String toJson() { - final Map jsonMap = {}; + final jsonMap = {}; if (asset != null && asset!.isNotEmpty) { jsonMap['asset'] = asset; } @@ -112,8 +111,7 @@ class CreateMessage { /// Deserializes a JSON string into a [CreateMessage]. static CreateMessage fromJson(String jsonString) { - final Map jsonMap = - jsonDecode(jsonString) as Map; + final jsonMap = jsonDecode(jsonString) as Map; return CreateMessage( asset: jsonMap['asset'] as String?, uri: jsonMap['uri'] as String?, @@ -121,10 +119,8 @@ class CreateMessage { formatHint: jsonMap['formatHint'] as String?, httpHeaders: (jsonMap['httpHeaders'] as Map?)?.cast(), drmConfigs: (jsonMap['drmConfigs'] as Map?)?.cast(), - playerOptions: - (jsonMap['playerOptions'] as Map?)?.cast(), - windowGeometry: - (jsonMap['windowGeometry'] as Map?)?.cast(), + playerOptions: (jsonMap['playerOptions'] as Map?)?.cast(), + windowGeometry: (jsonMap['windowGeometry'] as Map?)?.cast(), ); } } @@ -142,7 +138,7 @@ class DurationMessage { /// Serializes this message to a JSON string. String toJson() { - final Map jsonMap = { + final jsonMap = { 'playerId': playerId, if (durationRange != null) 'durationRange': durationRange, }; @@ -151,13 +147,11 @@ class DurationMessage { /// Deserializes a JSON string into a [DurationMessage]. static DurationMessage fromJson(String jsonString) { - final Map jsonMap = - jsonDecode(jsonString) as Map; + final jsonMap = jsonDecode(jsonString) as Map; return DurationMessage( playerId: jsonMap['playerId'] as int, - durationRange: (jsonMap['durationRange'] as List?) - ?.map((e) => (e as num).toInt()) - .toList(), + durationRange: + (jsonMap['durationRange'] as List?)?.map((e) => (e as num).toInt()).toList(), ); } } @@ -198,15 +192,12 @@ typedef _FFISetPlaybackSpeedDart = int Function(int, double); typedef _FFISetLoopingNative = ffi.Int32 Function(ffi.Int64, ffi.Bool); typedef _FFISetLoopingDart = int Function(int, bool); -typedef _FFIGetTrackInfoNative = ffi.Pointer Function( - ffi.Int64, ffi.Pointer); -typedef _FFIGetTrackInfoDart = ffi.Pointer Function( - int, ffi.Pointer); +typedef _FFIGetTrackInfoNative = ffi.Pointer Function(ffi.Int64, ffi.Pointer); +typedef _FFIGetTrackInfoDart = ffi.Pointer Function(int, ffi.Pointer); typedef _FFISetTrackSelectionNative = ffi.Int32 Function( ffi.Int64, ffi.Int64, ffi.Pointer); -typedef _FFISetTrackSelectionDart = int Function( - int, int, ffi.Pointer); +typedef _FFISetTrackSelectionDart = int Function(int, int, ffi.Pointer); typedef _FFISetDisplayGeometryNative = ffi.Int32 Function( ffi.Int64, ffi.Int32, ffi.Int32, ffi.Int32, ffi.Int32); @@ -227,8 +218,7 @@ typedef _FFISetMixWithOthersDart = int Function(bool); typedef _FFISuspendNative = ffi.Int32 Function(ffi.Int64); typedef _FFISuspendDart = int Function(int); -typedef _FFIRestoreNative = ffi.Int32 Function( - ffi.Int64, ffi.Pointer, ffi.Int64); +typedef _FFIRestoreNative = ffi.Int32 Function(ffi.Int64, ffi.Pointer, ffi.Int64); typedef _FFIRestoreDart = int Function(int, ffi.Pointer, int); typedef _FFIFreeStringNative = ffi.Void Function(ffi.Pointer); @@ -239,8 +229,7 @@ ffi.Pointer _toPointer(String? str) { return ffi.nullptr; } final Uint8List units = utf8.encode(str); - final ffi.Pointer result = - calloc.allocate(units.length + 1); + final ffi.Pointer result = calloc.allocate(units.length + 1); final Uint8List nativeString = result.asTypedList(units.length + 1); nativeString.setAll(0, units); nativeString[units.length] = 0; @@ -272,8 +261,7 @@ class VideoPlayerFFIBindings { late int Function(int, double) _ffiSetVolume; late int Function(int, double) _ffiSetPlaybackSpeed; late int Function(int, bool) _ffiSetLooping; - late ffi.Pointer Function(int, ffi.Pointer) - _ffiGetTrackInfo; + late ffi.Pointer Function(int, ffi.Pointer) _ffiGetTrackInfo; late int Function(int, int, ffi.Pointer) _ffiSetTrackSelection; late int Function(int, int, int, int, int) _ffiSetDisplayGeometry; late int Function(int, int) _ffiSetDisplayRotate; @@ -317,9 +305,8 @@ class VideoPlayerFFIBindings { .lookup>('ffi_dispose') .asFunction<_FFIDisposeDart>(); - _ffiPlay = _lib! - .lookup>('ffi_play') - .asFunction<_FFIPlayDart>(); + _ffiPlay = + _lib!.lookup>('ffi_play').asFunction<_FFIPlayDart>(); _ffiPause = _lib! .lookup>('ffi_pause') @@ -342,8 +329,7 @@ class VideoPlayerFFIBindings { .asFunction<_FFISetVolumeDart>(); _ffiSetPlaybackSpeed = _lib! - .lookup>( - 'ffi_set_playback_speed') + .lookup>('ffi_set_playback_speed') .asFunction<_FFISetPlaybackSpeedDart>(); _ffiSetLooping = _lib! @@ -351,23 +337,19 @@ class VideoPlayerFFIBindings { .asFunction<_FFISetLoopingDart>(); _ffiGetTrackInfo = _lib! - .lookup>( - 'ffi_get_track_info') + .lookup>('ffi_get_track_info') .asFunction<_FFIGetTrackInfoDart>(); _ffiSetTrackSelection = _lib! - .lookup>( - 'ffi_set_track_selection') + .lookup>('ffi_set_track_selection') .asFunction<_FFISetTrackSelectionDart>(); _ffiSetDisplayGeometry = _lib! - .lookup>( - 'ffi_set_display_geometry') + .lookup>('ffi_set_display_geometry') .asFunction<_FFISetDisplayGeometryDart>(); _ffiSetDisplayRotate = _lib! - .lookup>( - 'ffi_set_display_rotate') + .lookup>('ffi_set_display_rotate') .asFunction<_FFISetDisplayRotateDart>(); _ffiSuspend = _lib! @@ -383,13 +365,11 @@ class VideoPlayerFFIBindings { .asFunction<_FFISetActivateDart>(); _ffiSetDeactivate = _lib! - .lookup>( - 'ffi_set_deactivate') + .lookup>('ffi_set_deactivate') .asFunction<_FFISetDeactivateDart>(); _ffiSetMixWithOthers = _lib! - .lookup>( - 'ffi_set_mix_with_others') + .lookup>('ffi_set_mix_with_others') .asFunction<_FFISetMixWithOthersDart>(); _ffiFreeString = _lib! @@ -397,12 +377,10 @@ class VideoPlayerFFIBindings { .asFunction<_FFIFreeStringDart>(); _ffiRegisterDartPort = _lib! - .lookup>( - 'ffi_register_dart_port') + .lookup>('ffi_register_dart_port') .asFunction<_FFIRegisterEventPortDart>(); _ffiUnregisterDartPort = _lib! - .lookup>( - 'ffi_unregister_dart_port') + .lookup>('ffi_unregister_dart_port') .asFunction<_FFIUnregisterEventPortDart>(); } catch (e) { _lib = null; @@ -527,7 +505,7 @@ class VideoPlayerVideoholeFFIApi { } try { final ffi.Pointer bytes = ptr.cast(); - int length = 0; + var length = 0; while (bytes[length] != 0) { length++; } @@ -633,7 +611,7 @@ class VideoPlayerVideoholeFFIApi { ); } final ffi.Pointer bytes = ptr.cast(); - int length = 0; + var length = 0; while (bytes[length] != 0) { length++; } @@ -686,8 +664,7 @@ typedef _FFIRegisterEventPortDart = void Function(int); typedef _FFIUnregisterEventPortNative = ffi.Void Function(); typedef _FFIUnregisterEventPortDart = void Function(); -late ffi.Pointer>? - _ffiInitializeApiDlPtr; +late ffi.Pointer>? _ffiInitializeApiDlPtr; /// Whether the Dart API DL has been initialized. bool _apiDlInitialized = false; @@ -712,8 +689,7 @@ void ffiInitializeApiDL() { try { _ffiInitializeApiDlPtr = - lib.lookup>( - 'ffi_initialize_api_dl'); + lib.lookup>('ffi_initialize_api_dl'); } catch (e) { throw PlatformException( code: 'FFI_API_DL_LOOKUP_FAILED',