From 8f69835feab55bfa7cd9b9a57aa383d3f89a9f19 Mon Sep 17 00:00:00 2001 From: morvag Date: Tue, 13 Apr 2021 17:11:52 +0200 Subject: [PATCH 1/3] migrate to null-safety --- android/build.gradle | 3 +- .../mapbox/mapboxgl/MapboxMapController.java | 6 + example/android/app/build.gradle | 3 +- example/ios/Runner.xcodeproj/project.pbxproj | 14 +- .../contents.xcworkspacedata | 2 +- example/lib/animate_camera.dart | 2 +- example/lib/annotation_order_maps.dart | 4 +- example/lib/custom_marker.dart | 14 +- example/lib/full_map.dart | 2 +- example/lib/generated_plugin_registrant.dart | 2 + example/lib/line.dart | 22 +-- example/lib/local_style.dart | 4 +- example/lib/main.dart | 2 +- example/lib/map_ui.dart | 55 +++--- example/lib/move_camera.dart | 2 +- example/lib/offline_regions.dart | 24 +-- example/lib/place_batch.dart | 10 +- example/lib/place_circle.dart | 32 +-- example/lib/place_fill.dart | 26 +-- example/lib/place_source.dart | 2 +- example/lib/place_symbol.dart | 49 ++--- example/lib/scrolling_map.dart | 4 +- example/pubspec.yaml | 11 +- lib/src/controller.dart | 121 +++++------- lib/src/global.dart | 18 +- lib/src/mapbox_map.dart | 118 +++++------ lib/src/offline_region.dart | 38 +--- .../lib/mapbox_gl_platform_interface.dart | 5 +- .../lib/src/callbacks.dart | 1 - .../lib/src/camera.dart | 16 +- .../lib/src/circle.dart | 25 ++- .../lib/src/fill.dart | 25 ++- .../lib/src/line.dart | 31 ++- .../lib/src/location.dart | 97 +++++---- .../lib/src/mapbox_gl_platform_interface.dart | 85 ++++---- .../lib/src/method_channel_mapbox_gl.dart | 137 +++++++------ .../lib/src/symbol.dart | 65 +++--- mapbox_gl_platform_interface/lib/src/ui.dart | 6 +- mapbox_gl_platform_interface/pubspec.yaml | 4 +- mapbox_gl_web/lib/src/convert.dart | 12 +- .../src/feature_manager/circle_manager.dart | 12 +- .../src/feature_manager/feature_manager.dart | 25 ++- .../lib/src/feature_manager/fill_manager.dart | 14 +- .../lib/src/feature_manager/line_manager.dart | 12 +- .../src/feature_manager/symbol_manager.dart | 17 +- .../lib/src/mapbox_map_controller.dart | 187 ++++++++++-------- mapbox_gl_web/lib/src/options_sink.dart | 6 +- mapbox_gl_web/pubspec.yaml | 8 +- pubspec.lock | 67 ++----- pubspec.yaml | 10 +- 50 files changed, 682 insertions(+), 775 deletions(-) diff --git a/android/build.gradle b/android/build.gradle index 4dfbe73f9..e6b13d711 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -37,11 +37,12 @@ rootProject.allprojects { apply plugin: 'com.android.library' android { - compileSdkVersion 28 + compileSdkVersion 29 defaultConfig { minSdkVersion 20 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + multiDexEnabled true } lintOptions { disable 'InvalidPackage' diff --git a/android/src/main/java/com/mapbox/mapboxgl/MapboxMapController.java b/android/src/main/java/com/mapbox/mapboxgl/MapboxMapController.java index d8bcce666..24ec3d6df 100644 --- a/android/src/main/java/com/mapbox/mapboxgl/MapboxMapController.java +++ b/android/src/main/java/com/mapbox/mapboxgl/MapboxMapController.java @@ -37,6 +37,7 @@ import com.mapbox.mapboxsdk.Mapbox; import com.mapbox.mapboxsdk.camera.CameraPosition; import com.mapbox.mapboxsdk.camera.CameraUpdate; +import com.mapbox.mapboxsdk.constants.MapboxConstants; import com.mapbox.mapboxsdk.geometry.LatLng; import com.mapbox.mapboxsdk.geometry.LatLngBounds; import com.mapbox.mapboxsdk.geometry.LatLngQuad; @@ -1238,10 +1239,15 @@ public void setMinMaxZoomPreference(Float min, Float max) { //mapboxMap.resetMinMaxZoomPreference(); if (min != null) { mapboxMap.setMinZoomPreference(min); + } else { + mapboxMap.setMinZoomPreference(MapboxConstants.MINIMUM_ZOOM); } if (max != null) { mapboxMap.setMaxZoomPreference(max); } + else { + mapboxMap.setMaxZoomPreference(MapboxConstants.MAXIMUM_ZOOM); + } } @Override diff --git a/example/android/app/build.gradle b/example/android/app/build.gradle index 0ab29be2d..6d6819d3d 100644 --- a/example/android/app/build.gradle +++ b/example/android/app/build.gradle @@ -25,7 +25,7 @@ apply plugin: 'com.android.application' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { - compileSdkVersion 28 + compileSdkVersion 29 lintOptions { disable 'InvalidPackage' @@ -39,6 +39,7 @@ android { versionCode flutterVersionCode.toInteger() versionName flutterVersionName testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + multiDexEnabled true } buildTypes { diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj index f6dde2836..4de76e90b 100644 --- a/example/ios/Runner.xcodeproj/project.pbxproj +++ b/example/ios/Runner.xcodeproj/project.pbxproj @@ -247,31 +247,21 @@ ); inputPaths = ( "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh", - "${PODS_ROOT}/../Flutter/Flutter.framework", "${PODS_ROOT}/Mapbox-iOS-SDK/dynamic/Mapbox.framework", - "${PODS_ROOT}/Mapbox-iOS-SDK/dynamic/Mapbox.framework.dSYM", - "${PODS_ROOT}/Mapbox-iOS-SDK/dynamic/4794199C-B164-3A2D-A3B4-553B7D49EDD5.bcsymbolmap", - "${PODS_ROOT}/Mapbox-iOS-SDK/dynamic/097AD13C-9FDA-310F-8B76-64CB67B06A27.bcsymbolmap", - "${PODS_ROOT}/Mapbox-iOS-SDK/dynamic/491A77E9-7DBC-3309-A93C-BADAE0DDBC6E.bcsymbolmap", - "${PODS_ROOT}/Mapbox-iOS-SDK/dynamic/3F114CA8-302D-327F-87C3-670E0EC63C9A.bcsymbolmap", "${BUILT_PRODUCTS_DIR}/MapboxAnnotationExtension/MapboxAnnotationExtension.framework", "${BUILT_PRODUCTS_DIR}/MapboxMobileEvents/MapboxMobileEvents.framework", "${BUILT_PRODUCTS_DIR}/location/location.framework", "${BUILT_PRODUCTS_DIR}/mapbox_gl/mapbox_gl.framework", + "${BUILT_PRODUCTS_DIR}/path_provider/path_provider.framework", ); name = "[CP] Embed Pods Frameworks"; outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Flutter.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Mapbox.framework", - "${DWARF_DSYM_FOLDER_PATH}/Mapbox.framework.dSYM", - "${BUILT_PRODUCTS_DIR}/4794199C-B164-3A2D-A3B4-553B7D49EDD5.bcsymbolmap", - "${BUILT_PRODUCTS_DIR}/097AD13C-9FDA-310F-8B76-64CB67B06A27.bcsymbolmap", - "${BUILT_PRODUCTS_DIR}/491A77E9-7DBC-3309-A93C-BADAE0DDBC6E.bcsymbolmap", - "${BUILT_PRODUCTS_DIR}/3F114CA8-302D-327F-87C3-670E0EC63C9A.bcsymbolmap", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/MapboxAnnotationExtension.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/MapboxMobileEvents.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/location.framework", "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/mapbox_gl.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/path_provider.framework", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata index 1d526a16e..919434a62 100644 --- a/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ b/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -2,6 +2,6 @@ + location = "self:"> diff --git a/example/lib/animate_camera.dart b/example/lib/animate_camera.dart index e8e234118..36f6a9c41 100644 --- a/example/lib/animate_camera.dart +++ b/example/lib/animate_camera.dart @@ -25,7 +25,7 @@ class AnimateCamera extends StatefulWidget { } class AnimateCameraState extends State { - MapboxMapController mapController; + late MapboxMapController mapController; void _onMapCreated(MapboxMapController controller) { mapController = controller; diff --git a/example/lib/annotation_order_maps.dart b/example/lib/annotation_order_maps.dart index 03263ad1d..d0f66e4ab 100644 --- a/example/lib/annotation_order_maps.dart +++ b/example/lib/annotation_order_maps.dart @@ -21,8 +21,8 @@ class AnnotationOrderBody extends StatefulWidget { } class _AnnotationOrderBodyState extends State { - MapboxMapController controllerOne; - MapboxMapController controllerTwo; + late MapboxMapController controllerOne; + late MapboxMapController controllerTwo; final LatLng center = const LatLng(36.580664, 32.5563837); diff --git a/example/lib/custom_marker.dart b/example/lib/custom_marker.dart index b1f4b5052..f2fb48e95 100644 --- a/example/lib/custom_marker.dart +++ b/example/lib/custom_marker.dart @@ -30,7 +30,7 @@ class CustomMarker extends StatefulWidget { class CustomMarkerState extends State { final Random _rnd = new Random(); - MapboxMapController _mapController; + late MapboxMapController _mapController; List _markers = []; List<_MarkerState> _markerStates = []; @@ -116,7 +116,7 @@ class CustomMarkerState extends State { _mapController.toScreenLocationBatch(param).then((value) { for (var i = 0; i < randomMarkerNum; i++) { - var point = Point(value[i].x, value[i].y); + var point = Point(value[i].x as double, value[i].y as double); _addMarker(point, param[i]); } }); @@ -151,7 +151,7 @@ class CustomMarkerState extends State { } Future.wait(list); sw.stop(); - results[batch][0] += sw.elapsedMilliseconds; + results[batch]![0] += sw.elapsedMilliseconds; sw.reset(); } @@ -166,11 +166,11 @@ class CustomMarkerState extends State { } Future.wait([_mapController.toScreenLocationBatch(param)]); sw.stop(); - results[batch][1] += sw.elapsedMilliseconds; + results[batch]![1] += sw.elapsedMilliseconds; sw.reset(); } - print('batch=$batch,primitive=${results[batch][0] / trial}ms, batch=${results[batch][1] / trial}ms'); + print('batch=$batch,primitive=${results[batch]![0] / trial}ms, batch=${results[batch]![1] / trial}ms'); } } @@ -196,8 +196,8 @@ class _MarkerState extends State with TickerProviderStateMixin { Point _position; - AnimationController _controller; - Animation _animation; + late AnimationController _controller; + late Animation _animation; _MarkerState(this._position); diff --git a/example/lib/full_map.dart b/example/lib/full_map.dart index b6a10c89d..5b6bdcdb7 100644 --- a/example/lib/full_map.dart +++ b/example/lib/full_map.dart @@ -21,7 +21,7 @@ class FullMap extends StatefulWidget { } class FullMapState extends State { - MapboxMapController mapController; + MapboxMapController? mapController; void _onMapCreated(MapboxMapController controller) { mapController = controller; diff --git a/example/lib/generated_plugin_registrant.dart b/example/lib/generated_plugin_registrant.dart index 152fbf187..9338cdbe8 100644 --- a/example/lib/generated_plugin_registrant.dart +++ b/example/lib/generated_plugin_registrant.dart @@ -4,12 +4,14 @@ // ignore_for_file: lines_longer_than_80_chars +import 'package:location_web/location_web.dart'; import 'package:mapbox_gl_web/mapbox_gl_web.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; // ignore: public_member_api_docs void registerPlugins(Registrar registrar) { + LocationWebPlugin.registerWith(registrar); MapboxMapPlugin.registerWith(registrar); registrar.registerMessageHandler(); } diff --git a/example/lib/line.dart b/example/lib/line.dart index 49b32eeee..7ea958734 100644 --- a/example/lib/line.dart +++ b/example/lib/line.dart @@ -31,9 +31,9 @@ class LineBodyState extends State { static final LatLng center = const LatLng(-33.86711, 151.1947171); - MapboxMapController controller; + MapboxMapController? controller; int _lineCount = 0; - Line _selectedLine; + Line? _selectedLine; void _onMapCreated(MapboxMapController controller) { this.controller = controller; @@ -42,7 +42,7 @@ class LineBodyState extends State { @override void dispose() { - controller?.onLineTapped?.remove(_onLineTapped); + controller?.onLineTapped.remove(_onLineTapped); super.dispose(); } @@ -65,11 +65,11 @@ class LineBodyState extends State { } void _updateSelectedLine(LineOptions changes) { - controller.updateLine(_selectedLine, changes); + controller!.updateLine(_selectedLine!, changes); } void _add() { - controller.addLine( + controller!.addLine( LineOptions( geometry: [ LatLng(-33.86711, 151.1947171), @@ -88,7 +88,7 @@ class LineBodyState extends State { } void _remove() { - controller.removeLine(_selectedLine); + controller!.removeLine(_selectedLine!); setState(() { _selectedLine = null; _lineCount -= 1; @@ -96,7 +96,7 @@ class LineBodyState extends State { } Future _changeAlpha() async { - double current = _selectedLine.options.lineOpacity; + double? current = _selectedLine!.options.lineOpacity; if (current == null) { // default value current = 1.0; @@ -108,7 +108,7 @@ class LineBodyState extends State { } Future _toggleVisible() async { - double current = _selectedLine.options.lineOpacity; + double? current = _selectedLine!.options.lineOpacity; if (current == null) { // default value current = 1.0; @@ -119,7 +119,7 @@ class LineBodyState extends State { } void onStyleLoadedCallback() { - controller.addLine( + controller!.addLine( LineOptions( geometry: [LatLng(37.4220, -122.0841), LatLng(37.4240, -122.0941)], lineColor: "#ff0000", @@ -186,8 +186,8 @@ class LineBodyState extends State { onPressed: (_selectedLine == null) ? null : () async { - var latLngs = await controller - .getLineLatLngs(_selectedLine); + var latLngs = await controller! + .getLineLatLngs(_selectedLine!); for (var latLng in latLngs) { print(latLng.toString()); } diff --git a/example/lib/local_style.dart b/example/lib/local_style.dart index 9918b6675..c851b94a7 100644 --- a/example/lib/local_style.dart +++ b/example/lib/local_style.dart @@ -25,8 +25,8 @@ class LocalStyle extends StatefulWidget { } class LocalStyleState extends State { - MapboxMapController mapController; - String styleAbsoluteFilePath; + MapboxMapController? mapController; + String? styleAbsoluteFilePath; @override initState() { diff --git a/example/lib/main.dart b/example/lib/main.dart index ef5385dbd..de06ee3ee 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -50,7 +50,7 @@ class MapsDemo extends StatelessWidget { if (!kIsWeb) { final location = Location(); final hasPermissions = await location.hasPermission(); - if (hasPermissions != PermissionStatus.GRANTED) { + if (hasPermissions != PermissionStatus.granted) { await location.requestPermission(); } } diff --git a/example/lib/map_ui.dart b/example/lib/map_ui.dart index 68a1acfdc..9db427f34 100644 --- a/example/lib/map_ui.dart +++ b/example/lib/map_ui.dart @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'dart:convert'; import 'dart:math'; import 'package:flutter/material.dart'; @@ -40,8 +39,8 @@ class MapUiBodyState extends State { zoom: 11.0, ); - MapboxMapController mapController; - CameraPosition _position = _kInitialPosition; + MapboxMapController? mapController; + CameraPosition? _position = _kInitialPosition; bool _isMoving = false; bool _compassEnabled = true; CameraTargetBounds _cameraTargetBounds = CameraTargetBounds.unbounded; @@ -66,8 +65,8 @@ class MapUiBodyState extends State { bool _myLocationEnabled = true; bool _telemetryEnabled = true; MyLocationTrackingMode _myLocationTrackingMode = MyLocationTrackingMode.None; - List _featureQueryFilter; - Fill _selectedFill; + List? _featureQueryFilter; + Fill? _selectedFill; @override void initState() { @@ -81,13 +80,13 @@ class MapUiBodyState extends State { } void _extractMapInfo() { - _position = mapController.cameraPosition; - _isMoving = mapController.isCameraMoving; + _position = mapController!.cameraPosition; + _isMoving = mapController!.isCameraMoving; } @override void dispose() { - mapController.removeListener(_onMapChanged); + mapController?.removeListener(_onMapChanged); super.dispose(); } @@ -251,7 +250,7 @@ class MapUiBodyState extends State { return TextButton( child: Text('get currently visible region'), onPressed: () async { - var result = await mapController.getVisibleRegion(); + var result = await mapController!.getVisibleRegion(); ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text( "SW: ${result.southwest.toString()} NE: ${result.northeast.toString()}"), @@ -262,15 +261,15 @@ class MapUiBodyState extends State { _clearFill() { if (_selectedFill != null) { - mapController.removeFill(_selectedFill); + mapController!.removeFill(_selectedFill!); setState(() { _selectedFill = null; }); } } - _drawFill(features) async { - Map feature = jsonDecode(features[0]); + _drawFill(List features) async { + Map feature = features[0]; if (feature['geometry']['type'] == 'Polygon') { var coordinates = feature['geometry']['coordinates']; List> geometry = coordinates @@ -278,7 +277,7 @@ class MapUiBodyState extends State { (ll) => ll.map((l) => LatLng(l[1], l[0])).toList().cast()) .toList() .cast>(); - Fill fill = await mapController.addFill(FillOptions( + Fill fill = await mapController!.addFill(FillOptions( geometry: geometry, fillColor: "#FF0000", fillOutlineColor: "#FF0000", @@ -312,32 +311,32 @@ class MapUiBodyState extends State { print( "Map click: ${point.x},${point.y} ${latLng.latitude}/${latLng.longitude}"); print("Filter $_featureQueryFilter"); - List features = await mapController.queryRenderedFeatures( - point, [], _featureQueryFilter); + List features = await mapController! + .queryRenderedFeatures(point, [], _featureQueryFilter); print('# features: ${features.length}'); _clearFill(); - if (features.length == 0 && _featureQueryFilter != null) { + if (features.isEmpty && _featureQueryFilter != null) { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text('QueryRenderedFeatures: No features found!'))); - } else { + } else if (features.isNotEmpty) { _drawFill(features); } }, onMapLongClick: (point, latLng) async { print( "Map long press: ${point.x},${point.y} ${latLng.latitude}/${latLng.longitude}"); - Point convertedPoint = await mapController.toScreenLocation(latLng); - LatLng convertedLatLng = await mapController.toLatLng(point); + Point convertedPoint = await mapController!.toScreenLocation(latLng); + LatLng convertedLatLng = await mapController!.toLatLng(point); print( "Map long press converted: ${convertedPoint.x},${convertedPoint.y} ${convertedLatLng.latitude}/${convertedLatLng.longitude}"); double metersPerPixel = - await mapController.getMetersPerPixelAtLatitude(latLng.latitude); + await mapController!.getMetersPerPixelAtLatitude(latLng.latitude); print( "Map long press The distance measured in meters at latitude ${latLng.latitude} is $metersPerPixel m"); List features = - await mapController.queryRenderedFeatures(point, [], null); + await mapController!.queryRenderedFeatures(point, [], null); if (features.length > 0) { print(features[0]); } @@ -371,12 +370,12 @@ class MapUiBodyState extends State { Expanded( child: ListView( children: [ - Text('camera bearing: ${_position.bearing}'), + Text('camera bearing: ${_position!.bearing}'), Text( - 'camera target: ${_position.target.latitude.toStringAsFixed(4)},' - '${_position.target.longitude.toStringAsFixed(4)}'), - Text('camera zoom: ${_position.zoom}'), - Text('camera tilt: ${_position.tilt}'), + 'camera target: ${_position!.target.latitude.toStringAsFixed(4)},' + '${_position!.target.longitude.toStringAsFixed(4)}'), + Text('camera zoom: ${_position!.zoom}'), + Text('camera tilt: ${_position!.tilt}'), Text(_isMoving ? '(Camera moving)' : '(Camera idle)'), _queryFilterToggler(), _compassToggler(), @@ -405,10 +404,10 @@ class MapUiBodyState extends State { void onMapCreated(MapboxMapController controller) { mapController = controller; - mapController.addListener(_onMapChanged); + mapController!.addListener(_onMapChanged); _extractMapInfo(); - mapController.getTelemetryEnabled().then((isEnabled) => setState(() { + mapController!.getTelemetryEnabled().then((isEnabled) => setState(() { _telemetryEnabled = isEnabled; })); } diff --git a/example/lib/move_camera.dart b/example/lib/move_camera.dart index ce231d7c6..5c3043be0 100644 --- a/example/lib/move_camera.dart +++ b/example/lib/move_camera.dart @@ -24,7 +24,7 @@ class MoveCamera extends StatefulWidget { } class MoveCameraState extends State { - MapboxMapController mapController; + late MapboxMapController mapController; void _onMapCreated(MapboxMapController controller) { mapController = controller; diff --git a/example/lib/offline_regions.dart b/example/lib/offline_regions.dart index ed9cc4f7e..bac2a06cf 100644 --- a/example/lib/offline_regions.dart +++ b/example/lib/offline_regions.dart @@ -1,3 +1,4 @@ +import 'package:collection/collection.dart' show IterableExtension; import 'package:flutter/material.dart'; import 'package:mapbox_gl/mapbox_gl.dart'; import 'package:mapbox_gl_example/main.dart'; @@ -45,22 +46,22 @@ final List regionNames = ['Hawaii', 'Santiago', 'Auckland']; class OfflineRegionListItem { OfflineRegionListItem({ - @required this.offlineRegionDefinition, - @required this.downloadedId, - @required this.isDownloading, - @required this.name, - @required this.estimatedTiles, + required this.offlineRegionDefinition, + required this.downloadedId, + required this.isDownloading, + required this.name, + required this.estimatedTiles, }); final OfflineRegionDefinition offlineRegionDefinition; - final int downloadedId; + final int? downloadedId; final bool isDownloading; final String name; final int estimatedTiles; OfflineRegionListItem copyWith({ - int downloadedId, - bool isDownloading, + int? downloadedId, + bool? isDownloading, }) => OfflineRegionListItem( offlineRegionDefinition: offlineRegionDefinition, @@ -184,9 +185,8 @@ class _OfflineRegionsBodyState extends State { await getListOfRegions(accessToken: MapsDemo.ACCESS_TOKEN); List regionItems = []; for (var item in allRegions) { - final offlineRegion = offlineRegions.firstWhere( - (offlineRegion) => offlineRegion.metadata['name'] == item.name, - orElse: () => null); + final offlineRegion = offlineRegions.firstWhereOrNull( + (offlineRegion) => offlineRegion.metadata['name'] == item.name); if (offlineRegion != null) { regionItems.add(item.copyWith(downloadedId: offlineRegion.id)); } else { @@ -243,7 +243,7 @@ class _OfflineRegionsBodyState extends State { }); await deleteOfflineRegion( - item.downloadedId, + item.downloadedId!, accessToken: MapsDemo.ACCESS_TOKEN, ); diff --git a/example/lib/place_batch.dart b/example/lib/place_batch.dart index df8eec990..3b8f751ad 100644 --- a/example/lib/place_batch.dart +++ b/example/lib/place_batch.dart @@ -69,7 +69,7 @@ class BatchAddBodyState extends State { static final LatLng center = const LatLng(-33.86711, 151.1947171); - MapboxMapController controller; + late MapboxMapController controller; void _onMapCreated(MapboxMapController controller) { this.controller = controller; @@ -79,7 +79,7 @@ class BatchAddBodyState extends State { Iterable options) { final listOptions = []; for (final option in options) { - for (final geom in option.geometry) { + for (final geom in option.geometry!) { listOptions.add(LineOptions(geometry: geom, lineColor: "#00FF00")); } } @@ -91,7 +91,7 @@ class BatchAddBodyState extends State { final circleOptions = []; for (final option in options) { // put circles only on the outside - for (final latLng in option.geometry.first) { + for (final latLng in option.geometry!.first) { circleOptions .add(CircleOptions(geometry: latLng, circleColor: "#00FF00")); } @@ -104,8 +104,8 @@ class BatchAddBodyState extends State { final symbolOptions = []; for (final option in options) { // put symbols only on the inner most ring if it exists - if (option.geometry.length > 1) - for (final latLng in option.geometry.last) { + if (option.geometry!.length > 1) + for (final latLng in option.geometry!.last) { symbolOptions .add(SymbolOptions(iconImage: 'hospital-11', geometry: latLng)); } diff --git a/example/lib/place_circle.dart b/example/lib/place_circle.dart index 70a5a58cc..7b8d8161f 100644 --- a/example/lib/place_circle.dart +++ b/example/lib/place_circle.dart @@ -32,9 +32,9 @@ class PlaceCircleBodyState extends State { static final LatLng center = const LatLng(-33.86711, 151.1947171); - MapboxMapController controller; + MapboxMapController? controller; int _circleCount = 0; - Circle _selectedCircle; + Circle? _selectedCircle; void _onMapCreated(MapboxMapController controller) { this.controller = controller; @@ -43,7 +43,7 @@ class PlaceCircleBodyState extends State { @override void dispose() { - controller?.onCircleTapped?.remove(_onCircleTapped); + controller?.onCircleTapped.remove(_onCircleTapped); super.dispose(); } @@ -64,11 +64,11 @@ class PlaceCircleBodyState extends State { } void _updateSelectedCircle(CircleOptions changes) { - controller.updateCircle(_selectedCircle, changes); + controller!.updateCircle(_selectedCircle!, changes); } void _add() { - controller.addCircle( + controller!.addCircle( CircleOptions( geometry: LatLng( center.latitude + sin(_circleCount * pi / 6.0) / 20.0, @@ -82,7 +82,7 @@ class PlaceCircleBodyState extends State { } void _remove() { - controller.removeCircle(_selectedCircle); + controller!.removeCircle(_selectedCircle!); setState(() { _selectedCircle = null; _circleCount -= 1; @@ -90,7 +90,7 @@ class PlaceCircleBodyState extends State { } void _changePosition() { - final LatLng current = _selectedCircle.options.geometry; + final LatLng current = _selectedCircle!.options.geometry!; final Offset offset = Offset( center.latitude - current.latitude, center.longitude - current.longitude, @@ -106,7 +106,7 @@ class PlaceCircleBodyState extends State { } void _changeDraggable() { - bool draggable = _selectedCircle.options.draggable; + bool? draggable = _selectedCircle!.options.draggable; if (draggable == null) { // default value draggable = false; @@ -119,7 +119,7 @@ class PlaceCircleBodyState extends State { } void _getLatLng() async { - LatLng latLng = await controller.getCircleLatLng(_selectedCircle); + LatLng latLng = await controller!.getCircleLatLng(_selectedCircle!); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(latLng.toString()), @@ -128,7 +128,7 @@ class PlaceCircleBodyState extends State { } void _changeCircleStrokeOpacity() { - double current = _selectedCircle.options.circleStrokeOpacity; + double? current = _selectedCircle!.options.circleStrokeOpacity; if (current == null) { // default value current = 1.0; @@ -140,7 +140,7 @@ class PlaceCircleBodyState extends State { } void _changeCircleStrokeWidth() { - double current = _selectedCircle.options.circleStrokeWidth; + double? current = _selectedCircle!.options.circleStrokeWidth; if (current == null) { // default value current = 0; @@ -150,7 +150,7 @@ class PlaceCircleBodyState extends State { } Future _changeCircleStrokeColor() async { - String current = _selectedCircle.options.circleStrokeColor; + String? current = _selectedCircle!.options.circleStrokeColor; if (current == null) { // default value current = "#FFFFFF"; @@ -163,7 +163,7 @@ class PlaceCircleBodyState extends State { } Future _changeCircleOpacity() async { - double current = _selectedCircle.options.circleOpacity; + double? current = _selectedCircle!.options.circleOpacity; if (current == null) { // default value current = 1.0; @@ -175,7 +175,7 @@ class PlaceCircleBodyState extends State { } Future _changeCircleRadius() async { - double current = _selectedCircle.options.circleRadius; + double? current = _selectedCircle!.options.circleRadius; if (current == null) { // default value current = 0; @@ -186,7 +186,7 @@ class PlaceCircleBodyState extends State { } Future _changeCircleColor() async { - String current = _selectedCircle.options.circleColor; + String? current = _selectedCircle!.options.circleColor; if (current == null) { // default value current = "#FF0000"; @@ -198,7 +198,7 @@ class PlaceCircleBodyState extends State { } Future _changeCircleBlur() async { - double current = _selectedCircle.options.circleBlur; + double? current = _selectedCircle!.options.circleBlur; if (current == null) { // default value current = 0; diff --git a/example/lib/place_fill.dart b/example/lib/place_fill.dart index 6a34597b9..74c6187e1 100644 --- a/example/lib/place_fill.dart +++ b/example/lib/place_fill.dart @@ -34,9 +34,9 @@ class PlaceFillBodyState extends State { static final LatLng center = const LatLng(-33.86711, 151.1947171); final String _fillPatternImage = "assets/fill/cat_silhouette_pattern.png"; - MapboxMapController controller; + MapboxMapController? controller; int _fillCount = 0; - Fill _selectedFill; + Fill? _selectedFill; void _onMapCreated(MapboxMapController controller) { this.controller = controller; @@ -51,12 +51,12 @@ class PlaceFillBodyState extends State { Future addImageFromAsset(String name, String assetName) async { final ByteData bytes = await rootBundle.load(assetName); final Uint8List list = bytes.buffer.asUint8List(); - return controller.addImage(name, list); + return controller!.addImage(name, list); } @override void dispose() { - controller?.onFillTapped?.remove(_onFillTapped); + controller?.onFillTapped.remove(_onFillTapped); super.dispose(); } @@ -67,11 +67,11 @@ class PlaceFillBodyState extends State { } void _updateSelectedFill(FillOptions changes) { - controller.updateFill(_selectedFill, changes); + controller!.updateFill(_selectedFill!, changes); } void _add() { - controller.addFill( + controller!.addFill( FillOptions(geometry: [ [ LatLng(-33.719, 151.150), @@ -94,7 +94,7 @@ class PlaceFillBodyState extends State { } void _remove() { - controller.removeFill(_selectedFill); + controller!.removeFill(_selectedFill!); setState(() { _selectedFill = null; _fillCount -= 1; @@ -106,7 +106,7 @@ class PlaceFillBodyState extends State { } void _changeDraggable() { - bool draggable = _selectedFill.options.draggable; + bool? draggable = _selectedFill!.options.draggable; if (draggable == null) { // default value draggable = false; @@ -117,7 +117,7 @@ class PlaceFillBodyState extends State { } Future _changeFillOpacity() async { - double current = _selectedFill.options.fillOpacity; + double? current = _selectedFill!.options.fillOpacity; if (current == null) { // default value current = 1.0; @@ -129,7 +129,7 @@ class PlaceFillBodyState extends State { } Future _changeFillColor() async { - String current = _selectedFill.options.fillColor; + String? current = _selectedFill!.options.fillColor; if (current == null) { // default value current = "#FF0000"; @@ -141,7 +141,7 @@ class PlaceFillBodyState extends State { } Future _changeFillOutlineColor() async { - String current = _selectedFill.options.fillOutlineColor; + String? current = _selectedFill!.options.fillOutlineColor; if (current == null) { // default value current = "#FF0000"; @@ -153,8 +153,8 @@ class PlaceFillBodyState extends State { } Future _changeFillPattern() async { - String current = - _selectedFill.options.fillPattern == null ? "assetImage" : null; + String? current = + _selectedFill!.options.fillPattern == null ? "assetImage" : null; _updateSelectedFill( FillOptions(fillPattern: current), ); diff --git a/example/lib/place_source.dart b/example/lib/place_source.dart index 950bc5ace..1a92855fc 100644 --- a/example/lib/place_source.dart +++ b/example/lib/place_source.dart @@ -35,7 +35,7 @@ class PlaceSymbolBodyState extends State { static const LAYER_ID = 'sydney_layer'; bool sourceAdded = false; - MapboxMapController controller; + late MapboxMapController controller; void _onMapCreated(MapboxMapController controller) { this.controller = controller; diff --git a/example/lib/place_symbol.dart b/example/lib/place_symbol.dart index c9ba5c9d2..1a0996641 100644 --- a/example/lib/place_symbol.dart +++ b/example/lib/place_symbol.dart @@ -36,9 +36,9 @@ class PlaceSymbolBodyState extends State { static final LatLng center = const LatLng(-33.86711, 151.1947171); - MapboxMapController controller; + MapboxMapController? controller; int _symbolCount = 0; - Symbol _selectedSymbol; + Symbol? _selectedSymbol; bool _iconAllowOverlap = false; void _onMapCreated(MapboxMapController controller) { @@ -54,7 +54,7 @@ class PlaceSymbolBodyState extends State { @override void dispose() { - controller?.onSymbolTapped?.remove(_onSymbolTapped); + controller?.onSymbolTapped.remove(_onSymbolTapped); super.dispose(); } @@ -62,13 +62,13 @@ class PlaceSymbolBodyState extends State { Future addImageFromAsset(String name, String assetName) async { final ByteData bytes = await rootBundle.load(assetName); final Uint8List list = bytes.buffer.asUint8List(); - return controller.addImage(name, list); + return controller!.addImage(name, list); } /// Adds a network image to the currently displayed style Future addImageFromUrl(String name, Uri uri) async { var response = await http.get(uri); - return controller.addImage(name, response.bodyBytes); + return controller!.addImage(name, response.bodyBytes); } void _onSymbolTapped(Symbol symbol) { @@ -88,15 +88,16 @@ class PlaceSymbolBodyState extends State { } void _updateSelectedSymbol(SymbolOptions changes) { - controller.updateSymbol(_selectedSymbol, changes); + controller!.updateSymbol(_selectedSymbol!, changes); } void _add(String iconImage) { List availableNumbers = Iterable.generate(12).toList(); - controller.symbols.forEach( - (s) => availableNumbers.removeWhere((i) => i == s.data['count'])); + controller!.symbols.forEach( + (s) => availableNumbers.removeWhere((i) => i == s.data!['count'])); if (availableNumbers.isNotEmpty) { - controller.addSymbol(_getSymbolOptions(iconImage, availableNumbers.first), + controller!.addSymbol( + _getSymbolOptions(iconImage, availableNumbers.first), {'count': availableNumbers.first}); setState(() { _symbolCount += 1; @@ -131,14 +132,14 @@ class PlaceSymbolBodyState extends State { Future _addAll(String iconImage) async { List symbolsToAddNumbers = Iterable.generate(12).toList(); - controller.symbols.forEach( - (s) => symbolsToAddNumbers.removeWhere((i) => i == s.data['count'])); + controller!.symbols.forEach( + (s) => symbolsToAddNumbers.removeWhere((i) => i == s.data!['count'])); if (symbolsToAddNumbers.isNotEmpty) { final List symbolOptionsList = symbolsToAddNumbers .map((i) => _getSymbolOptions(iconImage, i)) .toList(); - controller.addSymbols(symbolOptionsList, + controller!.addSymbols(symbolOptionsList, symbolsToAddNumbers.map((i) => {'count': i}).toList()); setState(() { @@ -148,7 +149,7 @@ class PlaceSymbolBodyState extends State { } void _remove() { - controller.removeSymbol(_selectedSymbol); + controller!.removeSymbol(_selectedSymbol!); setState(() { _selectedSymbol = null; _symbolCount -= 1; @@ -156,7 +157,7 @@ class PlaceSymbolBodyState extends State { } void _removeAll() { - controller.removeSymbols(controller.symbols); + controller!.removeSymbols(controller!.symbols); setState(() { _selectedSymbol = null; _symbolCount = 0; @@ -164,7 +165,7 @@ class PlaceSymbolBodyState extends State { } void _changePosition() { - final LatLng current = _selectedSymbol.options.geometry; + final LatLng current = _selectedSymbol!.options.geometry!; final Offset offset = Offset( center.latitude - current.latitude, center.longitude - current.longitude, @@ -180,7 +181,7 @@ class PlaceSymbolBodyState extends State { } void _changeIconOffset() { - Offset currentAnchor = _selectedSymbol.options.iconOffset; + Offset? currentAnchor = _selectedSymbol!.options.iconOffset; if (currentAnchor == null) { // default value currentAnchor = Offset(0.0, 0.0); @@ -190,7 +191,7 @@ class PlaceSymbolBodyState extends State { } Future _changeIconAnchor() async { - String current = _selectedSymbol.options.iconAnchor; + String? current = _selectedSymbol!.options.iconAnchor; if (current == null || current == 'center') { current = 'bottom'; } else { @@ -202,7 +203,7 @@ class PlaceSymbolBodyState extends State { } Future _toggleDraggable() async { - bool draggable = _selectedSymbol.options.draggable; + bool? draggable = _selectedSymbol!.options.draggable; if (draggable == null) { // default value draggable = false; @@ -214,7 +215,7 @@ class PlaceSymbolBodyState extends State { } Future _changeAlpha() async { - double current = _selectedSymbol.options.iconOpacity; + double? current = _selectedSymbol!.options.iconOpacity; if (current == null) { // default value current = 1.0; @@ -226,7 +227,7 @@ class PlaceSymbolBodyState extends State { } Future _changeRotation() async { - double current = _selectedSymbol.options.iconRotate; + double? current = _selectedSymbol!.options.iconRotate; if (current == null) { // default value current = 0; @@ -237,7 +238,7 @@ class PlaceSymbolBodyState extends State { } Future _toggleVisible() async { - double current = _selectedSymbol.options.iconOpacity; + double? current = _selectedSymbol!.options.iconOpacity; if (current == null) { // default value current = 1.0; @@ -249,7 +250,7 @@ class PlaceSymbolBodyState extends State { } Future _changeZIndex() async { - int current = _selectedSymbol.options.zIndex; + int? current = _selectedSymbol!.options.zIndex; if (current == null) { // default value current = 0; @@ -260,7 +261,7 @@ class PlaceSymbolBodyState extends State { } void _getLatLng() async { - LatLng latLng = await controller.getSymbolLatLng(_selectedSymbol); + LatLng latLng = await controller!.getSymbolLatLng(_selectedSymbol!); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(latLng.toString()), @@ -272,7 +273,7 @@ class PlaceSymbolBodyState extends State { setState(() { _iconAllowOverlap = !_iconAllowOverlap; }); - controller.setSymbolIconAllowOverlap(_iconAllowOverlap); + controller!.setSymbolIconAllowOverlap(_iconAllowOverlap); } @override diff --git a/example/lib/scrolling_map.dart b/example/lib/scrolling_map.dart index e1d693dc1..c40561735 100644 --- a/example/lib/scrolling_map.dart +++ b/example/lib/scrolling_map.dart @@ -28,8 +28,8 @@ class ScrollingMapBody extends StatefulWidget { } class _ScrollingMapBodyState extends State { - MapboxMapController controllerOne; - MapboxMapController controllerTwo; + late MapboxMapController controllerOne; + late MapboxMapController controllerTwo; final LatLng center = const LatLng(32.080664, 34.9563837); diff --git a/example/pubspec.yaml b/example/pubspec.yaml index 62ae23122..f8ca7a68e 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -4,7 +4,7 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ">=2.1.0 <3.0.0" + sdk: '>=2.12.0 <3.0.0' dependencies: flutter: @@ -12,10 +12,11 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. - cupertino_icons: ^0.1.2 - location: ^2.5.3 - path_provider: ^1.6.27 - http: + cupertino_icons: ^1.0.0 + location: ^4.0.0 + path_provider: ^2.0.0 + http: ^0.13.0 + collection: ^1.0.0 dependency_overrides: mapbox_gl_platform_interface: diff --git a/lib/src/controller.dart b/lib/src/controller.dart index ba65c74c6..1cc15c8da 100644 --- a/lib/src/controller.dart +++ b/lib/src/controller.dart @@ -42,42 +42,41 @@ class MapboxMapController extends ChangeNotifier { this.onCameraTrackingChanged, this.onMapIdle, this.onUserLocationUpdated, - this.onCameraIdle}) - : assert(_id != null) { + this.onCameraIdle}) { _cameraPosition = initialCameraPosition; MapboxGlPlatform.getInstance(_id) .onInfoWindowTappedPlatform .add((symbolId) { - final Symbol symbol = _symbols[symbolId]; + final symbol = _symbols[symbolId]; if (symbol != null) { onInfoWindowTapped(symbol); } }); MapboxGlPlatform.getInstance(_id).onSymbolTappedPlatform.add((symbolId) { - final Symbol symbol = _symbols[symbolId]; + final symbol = _symbols[symbolId]; if (symbol != null) { onSymbolTapped(symbol); } }); MapboxGlPlatform.getInstance(_id).onLineTappedPlatform.add((lineId) { - final Line line = _lines[lineId]; + final line = _lines[lineId]; if (line != null) { onLineTapped(line); } }); MapboxGlPlatform.getInstance(_id).onCircleTappedPlatform.add((circleId) { - final Circle circle = _circles[circleId]; + final circle = _circles[circleId]; if (circle != null) { onCircleTapped(circle); } }); MapboxGlPlatform.getInstance(_id).onFillTappedPlatform.add((fillId) { - final Fill fill = _fills[fillId]; + final fill = _fills[fillId]; if (fill != null) { onFillTapped(fill); } @@ -103,26 +102,26 @@ class MapboxMapController extends ChangeNotifier { _cameraPosition = cameraPosition; } if (onCameraIdle != null) { - onCameraIdle(); + onCameraIdle!(); } notifyListeners(); }); MapboxGlPlatform.getInstance(_id).onMapStyleLoadedPlatform.add((_) { if (onStyleLoadedCallback != null) { - onStyleLoadedCallback(); + onStyleLoadedCallback!(); } }); MapboxGlPlatform.getInstance(_id).onMapClickPlatform.add((dict) { if (onMapClick != null) { - onMapClick(dict['point'], dict['latLng']); + onMapClick!(dict['point'], dict['latLng']); } }); MapboxGlPlatform.getInstance(_id).onMapLongClickPlatform.add((dict) { if (onMapLongClick != null) { - onMapLongClick(dict['point'], dict['latLng']); + onMapLongClick!(dict['point'], dict['latLng']); } }); @@ -130,7 +129,7 @@ class MapboxMapController extends ChangeNotifier { .onCameraTrackingChangedPlatform .add((mode) { if (onCameraTrackingChanged != null) { - onCameraTrackingChanged(mode); + onCameraTrackingChanged!(mode); } }); @@ -138,13 +137,13 @@ class MapboxMapController extends ChangeNotifier { .onCameraTrackingDismissedPlatform .add((_) { if (onCameraTrackingDismissed != null) { - onCameraTrackingDismissed(); + onCameraTrackingDismissed!(); } }); MapboxGlPlatform.getInstance(_id).onMapIdlePlatform.add((_) { if (onMapIdle != null) { - onMapIdle(); + onMapIdle!(); } }); MapboxGlPlatform.getInstance(_id) @@ -155,15 +154,14 @@ class MapboxMapController extends ChangeNotifier { } static MapboxMapController init(int id, CameraPosition initialCameraPosition, - {OnStyleLoadedCallback onStyleLoadedCallback, - OnMapClickCallback onMapClick, - OnUserLocationUpdated onUserLocationUpdated, - OnMapLongClickCallback onMapLongClick, - OnCameraTrackingDismissedCallback onCameraTrackingDismissed, - OnCameraTrackingChangedCallback onCameraTrackingChanged, - OnCameraIdleCallback onCameraIdle, - OnMapIdleCallback onMapIdle}) { - assert(id != null); + {OnStyleLoadedCallback? onStyleLoadedCallback, + OnMapClickCallback? onMapClick, + OnUserLocationUpdated? onUserLocationUpdated, + OnMapLongClickCallback? onMapLongClick, + OnCameraTrackingDismissedCallback? onCameraTrackingDismissed, + OnCameraTrackingChangedCallback? onCameraTrackingChanged, + OnCameraIdleCallback? onCameraIdle, + OnMapIdleCallback? onMapIdle}) { return MapboxMapController._(id, initialCameraPosition, onStyleLoadedCallback: onStyleLoadedCallback, onMapClick: onMapClick, @@ -176,23 +174,22 @@ class MapboxMapController extends ChangeNotifier { } static Future initPlatform(int id) async { - assert(id != null); await MapboxGlPlatform.getInstance(id).initPlatform(id); } - final OnStyleLoadedCallback onStyleLoadedCallback; + final OnStyleLoadedCallback? onStyleLoadedCallback; - final OnMapClickCallback onMapClick; - final OnMapLongClickCallback onMapLongClick; + final OnMapClickCallback? onMapClick; + final OnMapLongClickCallback? onMapLongClick; - final OnUserLocationUpdated onUserLocationUpdated; + final OnUserLocationUpdated? onUserLocationUpdated; - final OnCameraTrackingDismissedCallback onCameraTrackingDismissed; - final OnCameraTrackingChangedCallback onCameraTrackingChanged; + final OnCameraTrackingDismissedCallback? onCameraTrackingDismissed; + final OnCameraTrackingChangedCallback? onCameraTrackingChanged; - final OnCameraIdleCallback onCameraIdle; + final OnCameraIdleCallback? onCameraIdle; - final OnMapIdleCallback onMapIdle; + final OnMapIdleCallback? onMapIdle; /// Callbacks to receive tap events for symbols placed on this map. final ArgumentCallbacks onSymbolTapped = ArgumentCallbacks(); @@ -240,14 +237,14 @@ class MapboxMapController extends ChangeNotifier { /// Returns the most recent camera position reported by the platform side. /// Will be null, if [MapboxMap.trackCameraPosition] is false. - CameraPosition get cameraPosition => _cameraPosition; - CameraPosition _cameraPosition; + CameraPosition? get cameraPosition => _cameraPosition; + CameraPosition? _cameraPosition; final int _id; //ignore: unused_field Widget buildView( Map creationParams, - Function onPlatformViewCreated, + OnPlatformViewCreatedCallback onPlatformViewCreated, Set> gestureRecognizers) { return MapboxGlPlatform.getInstance(_id) .buildView(creationParams, onPlatformViewCreated, gestureRecognizers); @@ -260,7 +257,6 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes after listeners have been notified. Future _updateMapOptions(Map optionsUpdate) async { - assert(optionsUpdate != null); _cameraPosition = await MapboxGlPlatform.getInstance(_id).updateMapOptions(optionsUpdate); notifyListeners(); @@ -272,8 +268,7 @@ class MapboxMapController extends ChangeNotifier { /// platform side. /// It returns true if the camera was successfully moved and false if the movement was canceled. /// Note: this currently always returns immediately with a value of null on iOS - Future animateCamera(CameraUpdate cameraUpdate) async { - assert(cameraUpdate != null); + Future animateCamera(CameraUpdate cameraUpdate) async { return MapboxGlPlatform.getInstance(_id).animateCamera(cameraUpdate); } @@ -284,7 +279,7 @@ class MapboxMapController extends ChangeNotifier { /// platform side. /// It returns true if the camera was successfully moved and false if the movement was canceled. /// Note: this currently always returns immediately with a value of null on iOS - Future moveCamera(CameraUpdate cameraUpdate) async { + Future moveCamera(CameraUpdate cameraUpdate) async { return MapboxGlPlatform.getInstance(_id).moveCamera(cameraUpdate); } @@ -356,8 +351,9 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes with the added symbol once listeners have /// been notified. - Future addSymbol(SymbolOptions options, [Map data]) async { - List result = await addSymbols([options], [data]); + Future addSymbol(SymbolOptions options, [Map? data]) async { + List result = + await addSymbols([options], data != null ? [data] : []); return result.first; } @@ -371,7 +367,7 @@ class MapboxMapController extends ChangeNotifier { /// The returned [Future] completes with the added symbol once listeners have /// been notified. Future> addSymbols(List options, - [List data]) async { + [List? data]) async { final List effectiveOptions = options.map((o) => SymbolOptions.defaultOptions.copyWith(o)).toList(); @@ -390,9 +386,8 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes once listeners have been notified. Future updateSymbol(Symbol symbol, SymbolOptions changes) async { - assert(symbol != null); assert(_symbols[symbol.id] == symbol); - assert(changes != null); + await MapboxGlPlatform.getInstance(_id).updateSymbol(symbol, changes); symbol.options = symbol.options.copyWith(changes); notifyListeners(); @@ -402,7 +397,6 @@ class MapboxMapController extends ChangeNotifier { /// This may be different from the value of `symbol.options.geometry` if the symbol is draggable. /// In that case this method provides the symbol's actual position, and `symbol.options.geometry` the last programmatically set position. Future getSymbolLatLng(Symbol symbol) async { - assert(symbol != null); assert(_symbols[symbol.id] == symbol); final symbolLatLng = await MapboxGlPlatform.getInstance(_id).getSymbolLatLng(symbol); @@ -418,7 +412,6 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes once listeners have been notified. Future removeSymbol(Symbol symbol) async { - assert(symbol != null); assert(_symbols[symbol.id] == symbol); await _removeSymbols([symbol.id]); notifyListeners(); @@ -446,8 +439,7 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes once listeners have been notified. Future clearSymbols() async { - assert(_symbols != null); - await MapboxGlPlatform.getInstance(_id).removeLines(_symbols.keys); + await MapboxGlPlatform.getInstance(_id).removeSymbols(_symbols.keys); _symbols.clear(); notifyListeners(); } @@ -469,7 +461,7 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes with the added line once listeners have /// been notified. - Future addLine(LineOptions options, [Map data]) async { + Future addLine(LineOptions options, [Map? data]) async { final LineOptions effectiveOptions = LineOptions.defaultOptions.copyWith(options); final line = @@ -487,7 +479,7 @@ class MapboxMapController extends ChangeNotifier { /// The returned [Future] completes with the added line once listeners have /// been notified. Future> addLines(List options, - [List data]) async { + [List? data]) async { final lines = await MapboxGlPlatform.getInstance(_id).addLines(options, data); lines.forEach((l) => _lines[l.id] = l); @@ -503,9 +495,7 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes once listeners have been notified. Future updateLine(Line line, LineOptions changes) async { - assert(line != null); assert(_lines[line.id] == line); - assert(changes != null); await MapboxGlPlatform.getInstance(_id).updateLine(line, changes); line.options = line.options.copyWith(changes); notifyListeners(); @@ -515,7 +505,6 @@ class MapboxMapController extends ChangeNotifier { /// This may be different from the value of `line.options.geometry` if the line is draggable. /// In that case this method provides the line's actual position, and `line.options.geometry` the last programmatically set position. Future> getLineLatLngs(Line line) async { - assert(line != null); assert(_lines[line.id] == line); final lineLatLngs = await MapboxGlPlatform.getInstance(_id).getLineLatLngs(line); @@ -531,7 +520,6 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes once listeners have been notified. Future removeLine(Line line) async { - assert(line != null); assert(_lines[line.id] == line); await MapboxGlPlatform.getInstance(_id).removeLine(line.id); @@ -562,7 +550,6 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes once listeners have been notified. Future clearLines() async { - assert(_lines != null); final List lineIds = List.from(_lines.keys); await MapboxGlPlatform.getInstance(_id).removeLines(lineIds); _lines.clear(); @@ -576,7 +563,7 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes with the added circle once listeners have /// been notified. - Future addCircle(CircleOptions options, [Map data]) async { + Future addCircle(CircleOptions options, [Map? data]) async { final CircleOptions effectiveOptions = CircleOptions.defaultOptions.copyWith(options); final circle = await MapboxGlPlatform.getInstance(_id) @@ -595,7 +582,7 @@ class MapboxMapController extends ChangeNotifier { /// The returned [Future] completes with the added circle once listeners have /// been notified. Future> addCircles(List options, - [List data]) async { + [List? data]) async { final circles = await MapboxGlPlatform.getInstance(_id).addCircles(options, data); circles.forEach((c) => _circles[c.id] = c); @@ -611,9 +598,7 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes once listeners have been notified. Future updateCircle(Circle circle, CircleOptions changes) async { - assert(circle != null); assert(_circles[circle.id] == circle); - assert(changes != null); await MapboxGlPlatform.getInstance(_id).updateCircle(circle, changes); circle.options = circle.options.copyWith(changes); notifyListeners(); @@ -623,7 +608,6 @@ class MapboxMapController extends ChangeNotifier { /// This may be different from the value of `circle.options.geometry` if the circle is draggable. /// In that case this method provides the circle's actual position, and `circle.options.geometry` the last programmatically set position. Future getCircleLatLng(Circle circle) async { - assert(circle != null); assert(_circles[circle.id] == circle); final circleLatLng = await MapboxGlPlatform.getInstance(_id).getCircleLatLng(circle); @@ -639,7 +623,6 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes once listeners have been notified. Future removeCircle(Circle circle) async { - assert(circle != null); assert(_circles[circle.id] == circle); await MapboxGlPlatform.getInstance(_id).removeCircle(circle.id); @@ -656,7 +639,6 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes once listeners have been notified. Future removeCircles(Iterable circles) async { - assert(circles != null); final ids = circles.where((c) => _circles[c.id] == c).map((c) => c.id); assert(circles.length == ids.length); @@ -672,7 +654,6 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes once listeners have been notified. Future clearCircles() async { - assert(_circles != null); await MapboxGlPlatform.getInstance(_id).removeCircles(_circles.keys); _circles.clear(); @@ -686,7 +667,7 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes with the added fill once listeners have /// been notified. - Future addFill(FillOptions options, [Map data]) async { + Future addFill(FillOptions options, [Map? data]) async { final FillOptions effectiveOptions = FillOptions.defaultOptions.copyWith(options); final fill = @@ -705,7 +686,7 @@ class MapboxMapController extends ChangeNotifier { /// The returned [Future] completes with the added fills once listeners have /// been notified. Future> addFills(List options, - [List data]) async { + [List? data]) async { final circles = await MapboxGlPlatform.getInstance(_id).addFills(options, data); circles.forEach((f) => _fills[f.id] = f); @@ -721,9 +702,7 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes once listeners have been notified. Future updateFill(Fill fill, FillOptions changes) async { - assert(fill != null); assert(_fills[fill.id] == fill); - assert(changes != null); await MapboxGlPlatform.getInstance(_id).updateFill(fill, changes); fill.options = fill.options.copyWith(changes); notifyListeners(); @@ -736,7 +715,6 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes once listeners have been notified. Future clearFills() async { - assert(_fills != null); await MapboxGlPlatform.getInstance(_id).removeFills(_fills.keys); _fills.clear(); @@ -751,7 +729,6 @@ class MapboxMapController extends ChangeNotifier { /// /// The returned [Future] completes once listeners have been notified. Future removeFill(Fill fill) async { - assert(fill != null); assert(_fills[fill.id] == fill); await MapboxGlPlatform.getInstance(_id).removeFill(fill.id); _fills.remove(fill.id); @@ -776,13 +753,13 @@ class MapboxMapController extends ChangeNotifier { } Future queryRenderedFeatures( - Point point, List layerIds, List filter) async { + Point point, List layerIds, List? filter) async { return MapboxGlPlatform.getInstance(_id) .queryRenderedFeatures(point, layerIds, filter); } Future queryRenderedFeaturesInRect( - Rect rect, List layerIds, String filter) async { + Rect rect, List layerIds, String? filter) async { return MapboxGlPlatform.getInstance(_id) .queryRenderedFeaturesInRect(rect, layerIds, filter); } @@ -794,7 +771,7 @@ class MapboxMapController extends ChangeNotifier { /// Get last my location /// /// Return last latlng, nullable - Future requestMyLocationLatLng() async { + Future requestMyLocationLatLng() async { return MapboxGlPlatform.getInstance(_id).requestMyLocationLatLng(); } diff --git a/lib/src/global.dart b/lib/src/global.dart index 5aef59b13..43b6788b0 100644 --- a/lib/src/global.dart +++ b/lib/src/global.dart @@ -20,7 +20,7 @@ Future installOfflineMapTiles(String tilesDb) async { Future setOffline( bool offline, { - String accessToken, + String? accessToken, }) => _globalChannel.invokeMethod( 'setOffline', @@ -32,7 +32,7 @@ Future setOffline( Future> mergeOfflineRegions( String path, { - String accessToken, + String? accessToken, }) async { String regionsJson = await _globalChannel.invokeMethod( 'mergeOfflineRegions', @@ -45,7 +45,7 @@ Future> mergeOfflineRegions( return regions.map((region) => OfflineRegion.fromMap(region)).toList(); } -Future> getListOfRegions({String accessToken}) async { +Future> getListOfRegions({String? accessToken}) async { String regionsJson = await _globalChannel.invokeMethod( 'getListOfRegions', { @@ -59,7 +59,7 @@ Future> getListOfRegions({String accessToken}) async { Future updateOfflineRegionMetadata( int id, Map metadata, { - String accessToken, + String? accessToken, }) async { final regionJson = await _globalChannel.invokeMethod( 'updateOfflineRegionMetadata', @@ -73,7 +73,7 @@ Future updateOfflineRegionMetadata( return OfflineRegion.fromMap(json.decode(regionJson)); } -Future setOfflineTileCountLimit(int limit, {String accessToken}) => +Future setOfflineTileCountLimit(int limit, {String? accessToken}) => _globalChannel.invokeMethod( 'setOfflineTileCountLimit', { @@ -82,7 +82,7 @@ Future setOfflineTileCountLimit(int limit, {String accessToken}) => }, ); -Future deleteOfflineRegion(int id, {String accessToken}) => +Future deleteOfflineRegion(int id, {String? accessToken}) => _globalChannel.invokeMethod( 'deleteOfflineRegion', { @@ -94,8 +94,8 @@ Future deleteOfflineRegion(int id, {String accessToken}) => Future downloadOfflineRegion( OfflineRegionDefinition definition, { Map metadata = const {}, - String accessToken, - Function(DownloadRegionStatus event) onEvent, + String? accessToken, + Function(DownloadRegionStatus event)? onEvent, }) async { String channelName = 'downloadOfflineRegion_${DateTime.now().microsecondsSinceEpoch}'; @@ -126,7 +126,7 @@ Future downloadOfflineRegion( return unknownError; }).listen((data) { final Map jsonData = json.decode(data); - DownloadRegionStatus status; + DownloadRegionStatus? status; switch (jsonData['status']) { case 'start': status = InProgress(0.0); diff --git a/lib/src/mapbox_map.dart b/lib/src/mapbox_map.dart index b62a38464..b07d7925d 100644 --- a/lib/src/mapbox_map.dart +++ b/lib/src/mapbox_map.dart @@ -10,8 +10,8 @@ typedef void MapCreatedCallback(MapboxMapController controller); class MapboxMap extends StatefulWidget { const MapboxMap({ - Key key, - @required this.initialCameraPosition, + Key? key, + required this.initialCameraPosition, this.accessToken, this.onMapCreated, this.onStyleLoadedCallback, @@ -51,10 +51,7 @@ class MapboxMap extends StatefulWidget { AnnotationType.line, AnnotationType.circle, ], - }) : assert(initialCameraPosition != null), - assert(annotationOrder != null), - assert(annotationOrder.length == 4), - assert(annotationConsumeTapEvents != null), + }) : assert(annotationOrder.length == 4), assert(annotationConsumeTapEvents.length > 0), super(key: key); @@ -71,14 +68,14 @@ class MapboxMap extends StatefulWidget { /// The reccommended way is to use this parameter to set your access token, an alternative way to add your access tokens through external files is described in the plugin's wiki on Github. /// /// Note: You should not use this parameter AND set the access token through external files at the same time, and you should use the same token throughout the entire app. - final String accessToken; + final String? accessToken; /// Please note: you should only add annotations (e.g. symbols or circles) after `onStyleLoadedCallback` has been called. - final MapCreatedCallback onMapCreated; + final MapCreatedCallback? onMapCreated; /// Called when the map style has been successfully loaded and the annotation managers have been enabled. /// Please note: you should only add annotations (e.g. symbols or circles) after this callback has been called. - final OnStyleLoadedCallback onStyleLoadedCallback; + final OnStyleLoadedCallback? onStyleLoadedCallback; /// The initial position of the map's camera. final CameraPosition initialCameraPosition; @@ -92,7 +89,7 @@ class MapboxMap extends StatefulWidget { /// Style URL or Style JSON /// Can be a MapboxStyle constant, any Mapbox Style URL, /// or a StyleJSON (https://docs.mapbox.com/mapbox-gl-js/style-spec/) - final String styleString; + final String? styleString; /// Preferred bounds for the camera zoom level. /// @@ -150,16 +147,16 @@ class MapboxMap extends StatefulWidget { final MyLocationRenderMode myLocationRenderMode; /// Set the layout margins for the Mapbox Logo - final Point logoViewMargins; + final Point? logoViewMargins; /// Set the position for the Mapbox Compass - final CompassViewPosition compassViewPosition; + final CompassViewPosition? compassViewPosition; /// Set the layout margins for the Mapbox Compass - final Point compassViewMargins; + final Point? compassViewMargins; /// Set the layout margins for the Mapbox Attribution Buttons - final Point attributionButtonMargins; + final Point? attributionButtonMargins; /// Which gestures should be consumed by the map. /// @@ -170,23 +167,23 @@ class MapboxMap extends StatefulWidget { /// /// When this set is empty or null, the map will only handle pointer events for gestures that /// were not claimed by any other gesture recognizer. - final Set> gestureRecognizers; + final Set>? gestureRecognizers; - final OnMapClickCallback onMapClick; - final OnMapClickCallback onMapLongClick; + final OnMapClickCallback? onMapClick; + final OnMapClickCallback? onMapLongClick; /// While the `myLocationEnabled` property is set to `true`, this method is /// called whenever a new location update is received by the map view. - final OnUserLocationUpdated onUserLocationUpdated; + final OnUserLocationUpdated? onUserLocationUpdated; /// Called when the map's camera no longer follows the physical device location, e.g. because the user moved the map - final OnCameraTrackingDismissedCallback onCameraTrackingDismissed; + final OnCameraTrackingDismissedCallback? onCameraTrackingDismissed; /// Called when the location tracking mode changes - final OnCameraTrackingChangedCallback onCameraTrackingChanged; + final OnCameraTrackingChangedCallback? onCameraTrackingChanged; // Called when camera movement has ended. - final OnCameraIdleCallback onCameraIdle; + final OnCameraIdleCallback? onCameraIdle; /// Called when map view is entering an idle state, and no more drawing will /// be necessary until new data is loaded or there is some interaction with @@ -194,7 +191,7 @@ class MapboxMap extends StatefulWidget { /// * No camera transitions are in progress /// * All currently requested tiles have loaded /// * All fade/transition animations have completed - final OnMapIdleCallback onMapIdle; + final OnMapIdleCallback? onMapIdle; @override State createState() => _MapboxMapState(); @@ -204,7 +201,7 @@ class _MapboxMapState extends State { final Completer _controller = Completer(); - _MapboxMapOptions _mapboxMapOptions; + late _MapboxMapOptions _mapboxMapOptions; final MapboxGlPlatform _mapboxGlPlatform = MapboxGlPlatform.createInstance(); @override @@ -215,7 +212,7 @@ class _MapboxMapState extends State { widget.annotationConsumeTapEvents.map((e) => e.toString()).toList(); final Map creationParams = { - 'initialCameraPosition': widget.initialCameraPosition?.toMap(), + 'initialCameraPosition': widget.initialCameraPosition.toMap(), 'options': _MapboxMapOptions.fromWidget(widget).toMap(), 'accessToken': widget.accessToken, 'annotationOrder': annotationOrder, @@ -252,24 +249,33 @@ class _MapboxMapState extends State { Future onPlatformViewCreated(int id) async { MapboxGlPlatform.addInstance(id, _mapboxGlPlatform); final MapboxMapController controller = MapboxMapController.init( - id, widget.initialCameraPosition, onStyleLoadedCallback: () { - if (_controller.isCompleted) { - widget.onStyleLoadedCallback(); - } else { - _controller.future.then((_) => widget.onStyleLoadedCallback()); - } - }, - onMapClick: widget.onMapClick, - onUserLocationUpdated: widget.onUserLocationUpdated, - onMapLongClick: widget.onMapLongClick, - onCameraTrackingDismissed: widget.onCameraTrackingDismissed, - onCameraTrackingChanged: widget.onCameraTrackingChanged, - onCameraIdle: widget.onCameraIdle, - onMapIdle: widget.onMapIdle); + id, + widget.initialCameraPosition, + onStyleLoadedCallback: () { + if (_controller.isCompleted) { + if (widget.onStyleLoadedCallback != null) { + widget.onStyleLoadedCallback!(); + } + } else { + _controller.future.then((_) { + if (widget.onStyleLoadedCallback != null) { + widget.onStyleLoadedCallback!(); + } + }); + } + }, + onMapClick: widget.onMapClick, + onUserLocationUpdated: widget.onUserLocationUpdated, + onMapLongClick: widget.onMapLongClick, + onCameraTrackingDismissed: widget.onCameraTrackingDismissed, + onCameraTrackingChanged: widget.onCameraTrackingChanged, + onCameraIdle: widget.onCameraIdle, + onMapIdle: widget.onMapIdle, + ); await MapboxMapController.initPlatform(id); _controller.complete(controller); if (widget.onMapCreated != null) { - widget.onMapCreated(controller); + widget.onMapCreated!(controller); } } } @@ -319,37 +325,37 @@ class _MapboxMapOptions { ); } - final bool compassEnabled; + final bool? compassEnabled; - final CameraTargetBounds cameraTargetBounds; + final CameraTargetBounds? cameraTargetBounds; - final String styleString; + final String? styleString; - final MinMaxZoomPreference minMaxZoomPreference; + final MinMaxZoomPreference? minMaxZoomPreference; - final bool rotateGesturesEnabled; + final bool? rotateGesturesEnabled; - final bool scrollGesturesEnabled; + final bool? scrollGesturesEnabled; - final bool tiltGesturesEnabled; + final bool? tiltGesturesEnabled; - final bool trackCameraPosition; + final bool? trackCameraPosition; - final bool zoomGesturesEnabled; + final bool? zoomGesturesEnabled; - final bool myLocationEnabled; + final bool? myLocationEnabled; - final MyLocationTrackingMode myLocationTrackingMode; + final MyLocationTrackingMode? myLocationTrackingMode; - final MyLocationRenderMode myLocationRenderMode; + final MyLocationRenderMode? myLocationRenderMode; - final Point logoViewMargins; + final Point? logoViewMargins; - final CompassViewPosition compassViewPosition; + final CompassViewPosition? compassViewPosition; - final Point compassViewMargins; + final Point? compassViewMargins; - final Point attributionButtonMargins; + final Point? attributionButtonMargins; Map toMap() { final Map optionsMap = {}; @@ -360,7 +366,7 @@ class _MapboxMapOptions { } } - List pointToArray(Point fieldName) { + List? pointToArray(Point? fieldName) { if (fieldName != null) { return [fieldName.x, fieldName.y]; } diff --git a/lib/src/offline_region.dart b/lib/src/offline_region.dart index e85a52ffc..94dd72250 100644 --- a/lib/src/offline_region.dart +++ b/lib/src/offline_region.dart @@ -4,10 +4,10 @@ part of mapbox_gl; /// the download is initiated. class OfflineRegionDefinition { const OfflineRegionDefinition({ - @required this.bounds, - @required this.mapStyleUrl, - @required this.minZoom, - @required this.maxZoom, + required this.bounds, + required this.mapStyleUrl, + required this.minZoom, + required this.maxZoom, this.includeIdeographs = false, }); @@ -33,11 +33,7 @@ class OfflineRegionDefinition { factory OfflineRegionDefinition.fromMap(Map map) { return OfflineRegionDefinition( - bounds: map['bounds'] != null - ? _latLngBoundsFromList( - map['bounds'], - ) - : null, + bounds: _latLngBoundsFromList(map['bounds']), mapStyleUrl: map['mapStyleUrl'], // small integers may deserialize to Int minZoom: map['minZoom'].toDouble(), @@ -47,29 +43,19 @@ class OfflineRegionDefinition { } static LatLngBounds _latLngBoundsFromList(List json) { - if (json == null) { - return null; - } return LatLngBounds( - southwest: _latLngFromList(json[0]), - northeast: _latLngFromList(json[1]), + southwest: LatLng(json[0][0], json[0][1]), + northeast: LatLng(json[1][0], json[1][1]), ); } - - static LatLng _latLngFromList(dynamic json) { - if (json == null) { - return null; - } - return LatLng(json[0], json[1]); - } } /// Description of a downloaded region including its identifier. class OfflineRegion { const OfflineRegion({ - this.id, - this.definition, - this.metadata, + required this.id, + required this.definition, + required this.metadata, }); final int id; @@ -77,10 +63,6 @@ class OfflineRegion { final Map metadata; factory OfflineRegion.fromMap(Map json) { - if (json == null) { - return null; - } - return OfflineRegion( id: json['id'], definition: OfflineRegionDefinition.fromMap(json['definition']), diff --git a/mapbox_gl_platform_interface/lib/mapbox_gl_platform_interface.dart b/mapbox_gl_platform_interface/lib/mapbox_gl_platform_interface.dart index f5c1ed938..d82515e1b 100644 --- a/mapbox_gl_platform_interface/lib/mapbox_gl_platform_interface.dart +++ b/mapbox_gl_platform_interface/lib/mapbox_gl_platform_interface.dart @@ -1,12 +1,14 @@ library mapbox_gl_platform_interface; +import 'dart:async'; +import 'dart:convert'; import 'dart:math'; import 'dart:typed_data'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:meta/meta.dart' show required, visibleForTesting; +import 'package:meta/meta.dart' show visibleForTesting; part 'src/callbacks.dart'; part 'src/camera.dart'; @@ -18,4 +20,3 @@ part 'src/symbol.dart'; part 'src/fill.dart'; part 'src/ui.dart'; part 'src/mapbox_gl_platform_interface.dart'; - diff --git a/mapbox_gl_platform_interface/lib/src/callbacks.dart b/mapbox_gl_platform_interface/lib/src/callbacks.dart index e375f2fef..f2d084a8e 100644 --- a/mapbox_gl_platform_interface/lib/src/callbacks.dart +++ b/mapbox_gl_platform_interface/lib/src/callbacks.dart @@ -36,7 +36,6 @@ class ArgumentCallbacks { /// Adds a callback to this collection. void add(ArgumentCallback callback) { - assert(callback != null); _callbacks.add(callback); } diff --git a/mapbox_gl_platform_interface/lib/src/camera.dart b/mapbox_gl_platform_interface/lib/src/camera.dart index bbf756944..219cff119 100644 --- a/mapbox_gl_platform_interface/lib/src/camera.dart +++ b/mapbox_gl_platform_interface/lib/src/camera.dart @@ -10,13 +10,10 @@ part of mapbox_gl_platform_interface; class CameraPosition { const CameraPosition({ this.bearing = 0.0, - @required this.target, + required this.target, this.tilt = 0.0, this.zoom = 0.0, - }) : assert(bearing != null), - assert(target != null), - assert(tilt != null), - assert(zoom != null); + }); /// The camera's bearing in degrees, measured clockwise from north. /// @@ -59,13 +56,13 @@ class CameraPosition { }; @visibleForTesting - static CameraPosition fromMap(dynamic json) { + static CameraPosition? fromMap(dynamic json) { if (json == null) { return null; } return CameraPosition( bearing: json['bearing'], - target: LatLng._fromJson(json['target']), + target: LatLng._fromJson(json['target'])!, tilt: json['tilt'], zoom: json['zoom'], ); @@ -108,11 +105,10 @@ class CameraUpdate { return CameraUpdate._(['newLatLng', latLng.toJson()]); } - /// Returns a camera update that transforms the camera so that the specified /// geographical bounding box is centered in the map view at the greatest /// possible zoom level. A non-zero [left], [top], [right] and [bottom] padding - /// insets the bounding box from the map view's edges. + /// insets the bounding box from the map view's edges. /// The camera's new tilt and bearing will both be 0.0. static CameraUpdate newLatLngBounds(LatLngBounds bounds, {double left = 0, double top = 0, double right = 0, double bottom = 0}) { @@ -149,7 +145,7 @@ class CameraUpdate { /// Returns a camera update that modifies the camera zoom level by the /// specified amount. The optional [focus] is a screen point whose underlying /// geographical location should be invariant, if possible, by the movement. - static CameraUpdate zoomBy(double amount, [Offset focus]) { + static CameraUpdate zoomBy(double amount, [Offset? focus]) { if (focus == null) { return CameraUpdate._(['zoomBy', amount]); } else { diff --git a/mapbox_gl_platform_interface/lib/src/circle.dart b/mapbox_gl_platform_interface/lib/src/circle.dart index 01815ae85..a75a0217e 100644 --- a/mapbox_gl_platform_interface/lib/src/circle.dart +++ b/mapbox_gl_platform_interface/lib/src/circle.dart @@ -15,8 +15,8 @@ class Circle { final String _id; String get id => _id; - final Map _data; - Map get data => _data; + final Map? _data; + Map? get data => _data; /// The circle configuration options most recently applied programmatically /// via the map controller. @@ -47,22 +47,19 @@ class CircleOptions { this.draggable, }); - final double circleRadius; - final String circleColor; - final double circleBlur; - final double circleOpacity; - final double circleStrokeWidth; - final String circleStrokeColor; - final double circleStrokeOpacity; - final LatLng geometry; - final bool draggable; + final double? circleRadius; + final String? circleColor; + final double? circleBlur; + final double? circleOpacity; + final double? circleStrokeWidth; + final String? circleStrokeColor; + final double? circleStrokeOpacity; + final LatLng? geometry; + final bool? draggable; static const CircleOptions defaultOptions = CircleOptions(); CircleOptions copyWith(CircleOptions changes) { - if (changes == null) { - return this; - } return CircleOptions( circleRadius: changes.circleRadius ?? circleRadius, circleColor: changes.circleColor ?? circleColor, diff --git a/mapbox_gl_platform_interface/lib/src/fill.dart b/mapbox_gl_platform_interface/lib/src/fill.dart index dbeb4e25c..15c966551 100644 --- a/mapbox_gl_platform_interface/lib/src/fill.dart +++ b/mapbox_gl_platform_interface/lib/src/fill.dart @@ -9,7 +9,7 @@ part of mapbox_gl_platform_interface; FillOptions translateFillOptions(FillOptions options, LatLng delta) { if (options.geometry != null) { List> newGeometry = []; - for (var ring in options.geometry) { + for (var ring in options.geometry!) { List newRing = []; for (var coords in ring) { newRing.add(coords + delta); @@ -30,8 +30,8 @@ class Fill { final String _id; String get id => _id; - final Map _data; - Map get data => _data; + final Map? _data; + Map? get data => _data; /// The fill configuration options most recently applied programmatically /// via the map controller. @@ -58,19 +58,16 @@ class FillOptions { this.geometry, this.draggable}); - final double fillOpacity; - final String fillColor; - final String fillOutlineColor; - final String fillPattern; - final List> geometry; - final bool draggable; + final double? fillOpacity; + final String? fillColor; + final String? fillOutlineColor; + final String? fillPattern; + final List>? geometry; + final bool? draggable; static const FillOptions defaultOptions = FillOptions(); FillOptions copyWith(FillOptions changes) { - if (changes == null) { - return this; - } return FillOptions( fillOpacity: changes.fillOpacity ?? fillOpacity, fillColor: changes.fillColor ?? fillColor, @@ -98,8 +95,8 @@ class FillOptions { 'geometry', geometry ?.map((List latLngList) => - latLngList.map((LatLng latLng) => latLng.toJson())?.toList()) - ?.toList()); + latLngList.map((LatLng latLng) => latLng.toJson()).toList()) + .toList()); addIfPresent('draggable', draggable); return json; } diff --git a/mapbox_gl_platform_interface/lib/src/line.dart b/mapbox_gl_platform_interface/lib/src/line.dart index 376ac1f78..0447bd26d 100644 --- a/mapbox_gl_platform_interface/lib/src/line.dart +++ b/mapbox_gl_platform_interface/lib/src/line.dart @@ -16,9 +16,9 @@ class Line { String get id => _id; - final Map _data; + final Map? _data; - Map get data => _data; + Map? get data => _data; /// The line configuration options most recently applied programmatically /// via the map controller. @@ -50,23 +50,20 @@ class LineOptions { this.draggable, }); - final String lineJoin; - final double lineOpacity; - final String lineColor; - final double lineWidth; - final double lineGapWidth; - final double lineOffset; - final double lineBlur; - final String linePattern; - final List geometry; - final bool draggable; + final String? lineJoin; + final double? lineOpacity; + final String? lineColor; + final double? lineWidth; + final double? lineGapWidth; + final double? lineOffset; + final double? lineBlur; + final String? linePattern; + final List? geometry; + final bool? draggable; static const LineOptions defaultOptions = LineOptions(); LineOptions copyWith(LineOptions changes) { - if (changes == null) { - return this; - } return LineOptions( lineJoin: changes.lineJoin ?? lineJoin, lineOpacity: changes.lineOpacity ?? lineOpacity, @@ -98,8 +95,8 @@ class LineOptions { addIfPresent('lineOffset', lineOffset); addIfPresent('lineBlur', lineBlur); addIfPresent('linePattern', linePattern); - addIfPresent('geometry', - geometry?.map((LatLng latLng) => latLng.toJson())?.toList()); + addIfPresent( + 'geometry', geometry?.map((LatLng latLng) => latLng.toJson()).toList()); addIfPresent('draggable', draggable); return json; } diff --git a/mapbox_gl_platform_interface/lib/src/location.dart b/mapbox_gl_platform_interface/lib/src/location.dart index ba54f314f..bc839c72c 100644 --- a/mapbox_gl_platform_interface/lib/src/location.dart +++ b/mapbox_gl_platform_interface/lib/src/location.dart @@ -14,9 +14,7 @@ class LatLng { /// The longitude is normalized to the half-open interval from -180.0 /// (inclusive) to +180.0 (exclusive) const LatLng(double latitude, double longitude) - : assert(latitude != null), - assert(longitude != null), - latitude = + : latitude = (latitude < -90.0 ? -90.0 : (90.0 < latitude ? 90.0 : latitude)), longitude = (longitude + 180.0) % 360.0 - 180.0; @@ -38,7 +36,7 @@ class LatLng { return [latitude, longitude]; } - static LatLng _fromJson(dynamic json) { + static LatLng? _fromJson(dynamic json) { if (json == null) { return null; } @@ -70,10 +68,8 @@ class LatLngBounds { /// /// The latitude of the southwest corner cannot be larger than the /// latitude of the northeast corner. - LatLngBounds({@required this.southwest, @required this.northeast}) - : assert(southwest != null), - assert(northeast != null), - assert(southwest.latitude <= northeast.latitude); + LatLngBounds({required this.southwest, required this.northeast}) + : assert(southwest.latitude <= northeast.latitude); /// The southwest corner of the rectangle. final LatLng southwest; @@ -86,13 +82,13 @@ class LatLngBounds { } @visibleForTesting - static LatLngBounds fromList(dynamic json) { + static LatLngBounds? fromList(dynamic json) { if (json == null) { return null; } return LatLngBounds( - southwest: LatLng._fromJson(json[0]), - northeast: LatLng._fromJson(json[1]), + southwest: LatLng._fromJson(json[0])!, + northeast: LatLng._fromJson(json[1])!, ); } @@ -115,15 +111,12 @@ class LatLngBounds { /// A geographical area representing a non-aligned quadrilateral /// This class does not wrap values to the world bounds class LatLngQuad { - const LatLngQuad( - {@required this.topLeft, - @required this.topRight, - @required this.bottomRight, - @required this.bottomLeft}) - : assert(topLeft != null), - assert(topRight != null), - assert(bottomRight != null), - assert(bottomLeft != null); + const LatLngQuad({ + required this.topLeft, + required this.topRight, + required this.bottomRight, + required this.bottomLeft, + }); final LatLng topLeft; @@ -143,15 +136,15 @@ class LatLngQuad { } @visibleForTesting - static LatLngQuad fromList(dynamic json) { + static LatLngQuad? fromList(dynamic json) { if (json == null) { return null; } return LatLngQuad( - topLeft: LatLng._fromJson(json[0]), - topRight: LatLng._fromJson(json[1]), - bottomRight: LatLng._fromJson(json[2]), - bottomLeft: LatLng._fromJson(json[3]), + topLeft: LatLng._fromJson(json[0])!, + topRight: LatLng._fromJson(json[1])!, + bottomRight: LatLng._fromJson(json[2])!, + bottomLeft: LatLng._fromJson(json[3])!, ); } @@ -179,35 +172,35 @@ class UserLocation { final LatLng position; /// User's altitude in meters - final double altitude; + final double? altitude; /// Direction user is traveling, measured in degrees - final double bearing; + final double? bearing; /// User's speed in meters per second - final double speed; + final double? speed; /// The radius of uncertainty for the location, measured in meters - final double horizontalAccuracy; + final double? horizontalAccuracy; /// Accuracy of the altitude measurement, in meters - final double verticalAccuracy; + final double? verticalAccuracy; /// Time the user's location was observed final DateTime timestamp; /// The heading of the user location, null if not available. - final UserHeading heading; + final UserHeading? heading; const UserLocation( - {@required this.position, - @required this.altitude, - @required this.bearing, - @required this.speed, - @required this.horizontalAccuracy, - @required this.verticalAccuracy, - @required this.timestamp, - @required this.heading}); + {required this.position, + required this.altitude, + required this.bearing, + required this.speed, + required this.horizontalAccuracy, + required this.verticalAccuracy, + required this.timestamp, + required this.heading}); } /// Type represents a geomagnetic value, measured in microteslas, relative to a @@ -216,35 +209,35 @@ class UserHeading { /// Represents the direction in degrees, where 0 degrees is magnetic North. /// The direction is referenced from the top of the device regardless of /// device orientation as well as the orientation of the user interface. - final double magneticHeading; + final double? magneticHeading; /// Represents the direction in degrees, where 0 degrees is true North. The /// direction is referenced from the top of the device regardless of device /// orientation as well as the orientation of the user interface - final double trueHeading; + final double? trueHeading; /// Represents the maximum deviation of where the magnetic heading may differ /// from the actual geomagnetic heading in degrees. A negative value indicates /// an invalid heading. - final double headingAccuracy; + final double? headingAccuracy; /// Returns a raw value for the geomagnetism measured in the x-axis. - final double x; + final double? x; /// Returns a raw value for the geomagnetism measured in the y-axis. - final double y; + final double? y; /// Returns a raw value for the geomagnetism measured in the z-axis. - final double z; + final double? z; /// Returns a timestamp for when the magnetic heading was determined. final DateTime timestamp; const UserHeading( - {@required this.magneticHeading, - @required this.trueHeading, - @required this.headingAccuracy, - @required this.x, - @required this.y, - @required this.z, - @required this.timestamp}); + {required this.magneticHeading, + required this.trueHeading, + required this.headingAccuracy, + required this.x, + required this.y, + required this.z, + required this.timestamp}); } diff --git a/mapbox_gl_platform_interface/lib/src/mapbox_gl_platform_interface.dart b/mapbox_gl_platform_interface/lib/src/mapbox_gl_platform_interface.dart index dd7f091c9..a261ca6ac 100644 --- a/mapbox_gl_platform_interface/lib/src/mapbox_gl_platform_interface.dart +++ b/mapbox_gl_platform_interface/lib/src/mapbox_gl_platform_interface.dart @@ -2,6 +2,8 @@ part of mapbox_gl_platform_interface; +typedef OnPlatformViewCreatedCallback = void Function(int); + abstract class MapboxGlPlatform { /// The default instance of [MapboxGlPlatform] to use. /// @@ -19,53 +21,39 @@ abstract class MapboxGlPlatform { } static MapboxGlPlatform getInstance(int id) { - return _instances[id]; + return _instances[id]!; } - final ArgumentCallbacks onInfoWindowTappedPlatform = - ArgumentCallbacks(); + final onInfoWindowTappedPlatform = ArgumentCallbacks(); - final ArgumentCallbacks onSymbolTappedPlatform = - ArgumentCallbacks(); + final onSymbolTappedPlatform = ArgumentCallbacks(); - final ArgumentCallbacks onLineTappedPlatform = - ArgumentCallbacks(); + final onLineTappedPlatform = ArgumentCallbacks(); - final ArgumentCallbacks onCircleTappedPlatform = - ArgumentCallbacks(); + final onCircleTappedPlatform = ArgumentCallbacks(); - final ArgumentCallbacks onFillTappedPlatform = - ArgumentCallbacks(); + final onFillTappedPlatform = ArgumentCallbacks(); - final ArgumentCallbacks onCameraMoveStartedPlatform = - ArgumentCallbacks(); + final onCameraMoveStartedPlatform = ArgumentCallbacks(); - final ArgumentCallbacks onCameraMovePlatform = - ArgumentCallbacks(); + final onCameraMovePlatform = ArgumentCallbacks(); - final ArgumentCallbacks onCameraIdlePlatform = - ArgumentCallbacks(); + final onCameraIdlePlatform = ArgumentCallbacks(); - final ArgumentCallbacks onMapStyleLoadedPlatform = - ArgumentCallbacks(); + final onMapStyleLoadedPlatform = ArgumentCallbacks(); - final ArgumentCallbacks> onMapClickPlatform = - ArgumentCallbacks>(); + final onMapClickPlatform = ArgumentCallbacks>(); - final ArgumentCallbacks> onMapLongClickPlatform = - ArgumentCallbacks>(); + final onMapLongClickPlatform = ArgumentCallbacks>(); - final ArgumentCallbacks - onCameraTrackingChangedPlatform = + final onCameraTrackingChangedPlatform = ArgumentCallbacks(); - final ArgumentCallbacks onCameraTrackingDismissedPlatform = - ArgumentCallbacks(); + final onCameraTrackingDismissedPlatform = ArgumentCallbacks(); - final ArgumentCallbacks onMapIdlePlatform = ArgumentCallbacks(); + final onMapIdlePlatform = ArgumentCallbacks(); - final ArgumentCallbacks onUserLocationUpdatedPlatform = - ArgumentCallbacks(); + final onUserLocationUpdatedPlatform = ArgumentCallbacks(); Future initPlatform(int id) async { throw UnimplementedError('initPlatform() has not been implemented.'); @@ -73,21 +61,21 @@ abstract class MapboxGlPlatform { Widget buildView( Map creationParams, - Function onPlatformViewCreated, - Set> gestureRecognizers) { + OnPlatformViewCreatedCallback onPlatformViewCreated, + Set>? gestureRecognizers) { throw UnimplementedError('buildView() has not been implemented.'); } - Future updateMapOptions( + Future updateMapOptions( Map optionsUpdate) async { throw UnimplementedError('updateMapOptions() has not been implemented.'); } - Future animateCamera(CameraUpdate cameraUpdate) async { + Future animateCamera(CameraUpdate cameraUpdate) async { throw UnimplementedError('animateCamera() has not been implemented.'); } - Future moveCamera(CameraUpdate cameraUpdate) async { + Future moveCamera(CameraUpdate cameraUpdate) async { throw UnimplementedError('moveCamera() has not been implemented.'); } @@ -119,7 +107,7 @@ abstract class MapboxGlPlatform { } Future> addSymbols(List options, - [List data]) async { + [List? data]) async { throw UnimplementedError('addSymbols() has not been implemented.'); } @@ -131,12 +119,12 @@ abstract class MapboxGlPlatform { throw UnimplementedError('removeSymbol() has not been implemented.'); } - Future addLine(LineOptions options, [Map data]) async { + Future addLine(LineOptions options, [Map? data]) async { throw UnimplementedError('addLine() has not been implemented.'); } Future> addLines(List options, - [List data]) async { + [List? data]) async { throw UnimplementedError('addLines() has not been implemented.'); } @@ -152,12 +140,12 @@ abstract class MapboxGlPlatform { throw UnimplementedError('removeLines() has not been implemented.'); } - Future addCircle(CircleOptions options, [Map data]) async { + Future addCircle(CircleOptions options, [Map? data]) async { throw UnimplementedError('addCircle() has not been implemented.'); } Future> addCircles(List options, - [List data]) async { + [List? data]) async { throw UnimplementedError('addCircles() has not been implemented.'); } @@ -185,12 +173,12 @@ abstract class MapboxGlPlatform { throw UnimplementedError('removeCircles() has not been implemented.'); } - Future addFill(FillOptions options, [Map data]) async { + Future addFill(FillOptions options, [Map? data]) async { throw UnimplementedError('addFill() has not been implemented.'); } Future> addFills(List options, - [List data]) async { + [List? data]) async { throw UnimplementedError('addFills() has not been implemented.'); } @@ -207,13 +195,13 @@ abstract class MapboxGlPlatform { } Future queryRenderedFeatures( - Point point, List layerIds, List filter) async { + Point point, List layerIds, List? filter) async { throw UnimplementedError( 'queryRenderedFeatures() has not been implemented.'); } Future queryRenderedFeaturesInRect( - Rect rect, List layerIds, String filter) async { + Rect rect, List layerIds, String? filter) async { throw UnimplementedError( 'queryRenderedFeaturesInRect() has not been implemented.'); } @@ -223,7 +211,7 @@ abstract class MapboxGlPlatform { 'invalidateAmbientCache() has not been implemented.'); } - Future requestMyLocationLatLng() async { + Future requestMyLocationLatLng() async { throw UnimplementedError( 'requestMyLocationLatLng() has not been implemented.'); } @@ -283,14 +271,13 @@ abstract class MapboxGlPlatform { throw UnimplementedError('toScreenLocation() has not been implemented.'); } - Future> toScreenLocationBatch(Iterable latLngs) async{ + Future> toScreenLocationBatch(Iterable latLngs) async { throw UnimplementedError( 'toScreenLocationList() has not been implemented.'); } - Future toLatLng(Point screenLocation) async{ - throw UnimplementedError( - 'toLatLng() has not been implemented.'); + Future toLatLng(Point screenLocation) async { + throw UnimplementedError('toLatLng() has not been implemented.'); } Future getMetersPerPixelAtLatitude(double latitude) async { diff --git a/mapbox_gl_platform_interface/lib/src/method_channel_mapbox_gl.dart b/mapbox_gl_platform_interface/lib/src/method_channel_mapbox_gl.dart index bf5ff4c45..56ebd36bf 100644 --- a/mapbox_gl_platform_interface/lib/src/method_channel_mapbox_gl.dart +++ b/mapbox_gl_platform_interface/lib/src/method_channel_mapbox_gl.dart @@ -1,36 +1,36 @@ part of mapbox_gl_platform_interface; class MethodChannelMapboxGl extends MapboxGlPlatform { - MethodChannel _channel; + late MethodChannel _channel; Future _handleMethodCall(MethodCall call) async { switch (call.method) { case 'infoWindow#onTap': - final String symbolId = call.arguments['symbol']; + final String? symbolId = call.arguments['symbol']; if (symbolId != null) { onInfoWindowTappedPlatform(symbolId); } break; case 'symbol#onTap': - final String symbolId = call.arguments['symbol']; + final String? symbolId = call.arguments['symbol']; if (symbolId != null) { onSymbolTappedPlatform(symbolId); } break; case 'line#onTap': - final String lineId = call.arguments['line']; + final String? lineId = call.arguments['line']; if (lineId != null) { onLineTappedPlatform(lineId); } break; case 'circle#onTap': - final String circleId = call.arguments['circle']; + final String? circleId = call.arguments['circle']; if (circleId != null) { onCircleTappedPlatform(circleId); } break; case 'fill#onTap': - final String fillId = call.arguments['fill']; + final String? fillId = call.arguments['fill']; if (fillId != null) { onFillTappedPlatform(fillId); } @@ -39,12 +39,12 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { onCameraMoveStartedPlatform(null); break; case 'camera#onMove': - final CameraPosition cameraPosition = - CameraPosition.fromMap(call.arguments['position']); + final cameraPosition = + CameraPosition.fromMap(call.arguments['position'])!; onCameraMovePlatform(cameraPosition); break; case 'camera#onIdle': - final CameraPosition cameraPosition = + final cameraPosition = CameraPosition.fromMap(call.arguments['position']); onCameraIdlePlatform(cameraPosition); break; @@ -81,30 +81,30 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { case 'map#onUserLocationUpdated': final dynamic userLocation = call.arguments['userLocation']; final dynamic heading = call.arguments['heading']; - if (onUserLocationUpdatedPlatform != null) { - onUserLocationUpdatedPlatform(UserLocation( - position: LatLng( - userLocation['position'][0], userLocation['position'][1]), - altitude: userLocation['altitude'], - bearing: userLocation['bearing'], - speed: userLocation['speed'], - horizontalAccuracy: userLocation['horizontalAccuracy'], - verticalAccuracy: userLocation['verticalAccuracy'], - heading: heading == null - ? null - : UserHeading( - magneticHeading: heading['magneticHeading'], - trueHeading: heading['trueHeading'], - headingAccuracy: heading['headingAccuracy'], - x: heading['x'], - y: heading['y'], - z: heading['x'], - timestamp: DateTime.fromMillisecondsSinceEpoch( - heading['timestamp']), - ), - timestamp: DateTime.fromMillisecondsSinceEpoch( - userLocation['timestamp']))); - } + onUserLocationUpdatedPlatform(UserLocation( + position: LatLng( + userLocation['position'][0], + userLocation['position'][1], + ), + altitude: userLocation['altitude'], + bearing: userLocation['bearing'], + speed: userLocation['speed'], + horizontalAccuracy: userLocation['horizontalAccuracy'], + verticalAccuracy: userLocation['verticalAccuracy'], + heading: heading == null + ? null + : UserHeading( + magneticHeading: heading['magneticHeading'], + trueHeading: heading['trueHeading'], + headingAccuracy: heading['headingAccuracy'], + x: heading['x'], + y: heading['y'], + z: heading['x'], + timestamp: DateTime.fromMillisecondsSinceEpoch( + heading['timestamp']), + ), + timestamp: DateTime.fromMillisecondsSinceEpoch( + userLocation['timestamp']))); break; default: throw MissingPluginException(); @@ -113,7 +113,6 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { @override Future initPlatform(int id) async { - assert(id != null); _channel = MethodChannel('plugins.flutter.io/mapbox_maps_$id'); await _channel.invokeMethod('map#waitForMap'); _channel.setMethodCallHandler(_handleMethodCall); @@ -123,11 +122,11 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { Widget buildView( Map creationParams, Function onPlatformViewCreated, - Set> gestureRecognizers) { + Set>? gestureRecognizers) { if (defaultTargetPlatform == TargetPlatform.android) { return AndroidView( viewType: 'plugins.flutter.io/mapbox_gl', - onPlatformViewCreated: onPlatformViewCreated, + onPlatformViewCreated: onPlatformViewCreated as void Function(int)?, gestureRecognizers: gestureRecognizers, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), @@ -135,7 +134,7 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { } else if (defaultTargetPlatform == TargetPlatform.iOS) { return UiKitView( viewType: 'plugins.flutter.io/mapbox_gl', - onPlatformViewCreated: onPlatformViewCreated, + onPlatformViewCreated: onPlatformViewCreated as void Function(int)?, gestureRecognizers: gestureRecognizers, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), @@ -146,7 +145,7 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { } @override - Future updateMapOptions( + Future updateMapOptions( Map optionsUpdate) async { final dynamic json = await _channel.invokeMethod( 'map#update', @@ -158,14 +157,14 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { } @override - Future animateCamera(cameraUpdate) async { + Future animateCamera(cameraUpdate) async { return await _channel.invokeMethod('camera#animate', { 'cameraUpdate': cameraUpdate.toJson(), }); } @override - Future moveCamera(CameraUpdate cameraUpdate) async { + Future moveCamera(CameraUpdate cameraUpdate) async { return await _channel.invokeMethod('camera#move', { 'cameraUpdate': cameraUpdate.toJson(), }); @@ -219,7 +218,7 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { @override Future> addSymbols(List options, - [List data]) async { + [List? data]) async { final List symbolIds = await _channel.invokeMethod( 'symbols#addAll', { @@ -265,7 +264,7 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { } @override - Future addLine(LineOptions options, [Map data]) async { + Future addLine(LineOptions options, [Map? data]) async { final String lineId = await _channel.invokeMethod( 'line#add', { @@ -277,7 +276,7 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { @override Future> addLines(List options, - [List data]) async { + [List? data]) async { final List ids = await _channel.invokeMethod( 'line#addAll', { @@ -332,7 +331,7 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { } @override - Future addCircle(CircleOptions options, [Map data]) async { + Future addCircle(CircleOptions options, [Map? data]) async { final String circleId = await _channel.invokeMethod( 'circle#add', { @@ -344,7 +343,7 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { @override Future> addCircles(List options, - [List data]) async { + [List? data]) async { final List ids = await _channel.invokeMethod( 'circle#addAll', { @@ -393,7 +392,7 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { } @override - Future addFill(FillOptions options, [Map data]) async { + Future addFill(FillOptions options, [Map? data]) async { final String fillId = await _channel.invokeMethod( 'fill#add', { @@ -405,7 +404,7 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { @override Future> addFills(List options, - [List data]) async { + [List? data]) async { final List ids = await _channel.invokeMethod( 'fill#addAll', { @@ -448,18 +447,18 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { @override Future queryRenderedFeatures( - Point point, List layerIds, List filter) async { + Point point, List layerIds, List? filter) async { try { - final Map reply = await _channel.invokeMethod( + final Map reply = await _channel.invokeMethod( 'map#queryRenderedFeatures', - { + { 'x': point.x, 'y': point.y, 'layerIds': layerIds, 'filter': filter, }, ); - return reply['features']; + return reply['features'].map((feature) => jsonDecode(feature)).toList(); } on PlatformException catch (e) { return new Future.error(e); } @@ -467,11 +466,11 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { @override Future queryRenderedFeaturesInRect( - Rect rect, List layerIds, String filter) async { + Rect rect, List layerIds, String? filter) async { try { - final Map reply = await _channel.invokeMethod( + final Map reply = await _channel.invokeMethod( 'map#queryRenderedFeatures', - { + { 'left': rect.left, 'top': rect.top, 'right': rect.right, @@ -480,7 +479,7 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { 'filter': filter, }, ); - return reply['features']; + return reply['features'].map((feature) => jsonDecode(feature)).toList(); } on PlatformException catch (e) { return new Future.error(e); } @@ -517,18 +516,14 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { @override Future getVisibleRegion() async { try { - final Map reply = + final Map reply = await _channel.invokeMethod('map#getVisibleRegion', null); - LatLng southwest, northeast; - if (reply.containsKey('sw')) { - List coordinates = reply['sw']; - southwest = LatLng(coordinates[0], coordinates[1]); - } - if (reply.containsKey('ne')) { - List coordinates = reply['ne']; - northeast = LatLng(coordinates[0], coordinates[1]); - } - return LatLngBounds(southwest: southwest, northeast: northeast); + final southwest = reply['sw'] as List; + final northeast = reply['ne'] as List; + return LatLngBounds( + southwest: LatLng(southwest[0], southwest[1]), + northeast: LatLng(northeast[0], northeast[1]), + ); } on PlatformException catch (e) { return new Future.error(e); } @@ -630,10 +625,12 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { @override Future> toScreenLocationBatch(Iterable latLngs) async { try { - var coordinates = Float64List.fromList( - latLngs.map((e) => [e.latitude, e.longitude]).expand((e) => e).toList()); - Float64List result = await _channel - .invokeMethod('map#toScreenLocationBatch', {"coordinates": coordinates}); + var coordinates = Float64List.fromList(latLngs + .map((e) => [e.latitude, e.longitude]) + .expand((e) => e) + .toList()); + Float64List result = await _channel.invokeMethod( + 'map#toScreenLocationBatch', {"coordinates": coordinates}); var points = []; for (int i = 0; i < result.length; i += 2) { diff --git a/mapbox_gl_platform_interface/lib/src/symbol.dart b/mapbox_gl_platform_interface/lib/src/symbol.dart index 9409cb069..87eaa79b5 100644 --- a/mapbox_gl_platform_interface/lib/src/symbol.dart +++ b/mapbox_gl_platform_interface/lib/src/symbol.dart @@ -16,8 +16,8 @@ class Symbol { String get id => _id; - final Map _data; - Map get data => _data; + final Map? _data; + Map? get data => _data; /// The symbol configuration options most recently applied programmatically /// via the map controller. @@ -27,7 +27,7 @@ class Symbol { SymbolOptions options; } -dynamic _offsetToJson(Offset offset) { +dynamic _offsetToJson(Offset? offset) { if (offset == null) { return null; } @@ -74,41 +74,38 @@ class SymbolOptions { this.draggable, }); - final double iconSize; - final String iconImage; - final double iconRotate; - final Offset iconOffset; - final String iconAnchor; - final List fontNames; - final String textField; - final double textSize; - final double textMaxWidth; - final double textLetterSpacing; - final String textJustify; - final String textAnchor; - final double textRotate; - final String textTransform; - final Offset textOffset; - final double iconOpacity; - final String iconColor; - final String iconHaloColor; - final double iconHaloWidth; - final double iconHaloBlur; - final double textOpacity; - final String textColor; - final String textHaloColor; - final double textHaloWidth; - final double textHaloBlur; - final LatLng geometry; - final int zIndex; - final bool draggable; + final double? iconSize; + final String? iconImage; + final double? iconRotate; + final Offset? iconOffset; + final String? iconAnchor; + final List? fontNames; + final String? textField; + final double? textSize; + final double? textMaxWidth; + final double? textLetterSpacing; + final String? textJustify; + final String? textAnchor; + final double? textRotate; + final String? textTransform; + final Offset? textOffset; + final double? iconOpacity; + final String? iconColor; + final String? iconHaloColor; + final double? iconHaloWidth; + final double? iconHaloBlur; + final double? textOpacity; + final String? textColor; + final String? textHaloColor; + final double? textHaloWidth; + final double? textHaloBlur; + final LatLng? geometry; + final int? zIndex; + final bool? draggable; static const SymbolOptions defaultOptions = SymbolOptions(); SymbolOptions copyWith(SymbolOptions changes) { - if (changes == null) { - return this; - } return SymbolOptions( iconSize: changes.iconSize ?? iconSize, iconImage: changes.iconImage ?? iconImage, diff --git a/mapbox_gl_platform_interface/lib/src/ui.dart b/mapbox_gl_platform_interface/lib/src/ui.dart index 460189533..e9476b2cb 100644 --- a/mapbox_gl_platform_interface/lib/src/ui.dart +++ b/mapbox_gl_platform_interface/lib/src/ui.dart @@ -79,7 +79,7 @@ class CameraTargetBounds { /// The geographical bounding box for the map camera target. /// /// A null value means the camera target is unbounded. - final LatLngBounds bounds; + final LatLngBounds? bounds; /// Unbounded camera target. static const CameraTargetBounds unbounded = CameraTargetBounds(null); @@ -112,10 +112,10 @@ class MinMaxZoomPreference { : assert(minZoom == null || maxZoom == null || minZoom <= maxZoom); /// The preferred minimum zoom level or null, if unbounded from below. - final double minZoom; + final double? minZoom; /// The preferred maximum zoom level or null, if unbounded from above. - final double maxZoom; + final double? maxZoom; /// Unbounded zooming. static const MinMaxZoomPreference unbounded = diff --git a/mapbox_gl_platform_interface/pubspec.yaml b/mapbox_gl_platform_interface/pubspec.yaml index 88b4f1099..b6b027a1b 100644 --- a/mapbox_gl_platform_interface/pubspec.yaml +++ b/mapbox_gl_platform_interface/pubspec.yaml @@ -9,5 +9,5 @@ dependencies: meta: ^1.0.5 environment: - sdk: ">=2.1.0 <3.0.0" - flutter: ">=1.10.0" + sdk: '>=2.12.0 <3.0.0' + flutter: ">=2.0.0" diff --git a/mapbox_gl_web/lib/src/convert.dart b/mapbox_gl_web/lib/src/convert.dart index 668d2fdac..3b533c8ce 100644 --- a/mapbox_gl_web/lib/src/convert.dart +++ b/mapbox_gl_web/lib/src/convert.dart @@ -203,7 +203,7 @@ class Convert { properties['iconRotate'] = options.iconRotate; } if (options.iconOffset != null) { - properties['iconOffset'] = [options.iconOffset.dx, options.iconOffset.dy]; + properties['iconOffset'] = [options.iconOffset!.dx, options.iconOffset!.dy]; } if (options.iconAnchor != null) { properties['iconAnchor'] = options.iconAnchor; @@ -233,7 +233,7 @@ class Convert { properties['textTransform'] = options.textTransform; } if (options.textOffset != null) { - properties['textOffset'] = [options.textOffset.dx, options.textOffset.dy]; + properties['textOffset'] = [options.textOffset!.dx, options.textOffset!.dy]; } if (options.iconOpacity != null) { properties['iconOpacity'] = options.iconOpacity; @@ -268,7 +268,7 @@ class Convert { if (options.geometry != null) { geometry = Geometry( type: geometry.type, - coordinates: [options.geometry.longitude, options.geometry.latitude], + coordinates: [options.geometry!.longitude, options.geometry!.latitude], ); } if (options.zIndex != null) { @@ -310,7 +310,7 @@ class Convert { if (options.geometry != null) { geometry = Geometry( type: geometry.type, - coordinates: options.geometry + coordinates: options.geometry! .map((latLng) => [latLng.longitude, latLng.latitude]) .toList(), ); @@ -349,7 +349,7 @@ class Convert { if (options.geometry != null) { geometry = Geometry( type: geometry.type, - coordinates: [options.geometry.longitude, options.geometry.latitude], + coordinates: [options.geometry!.longitude, options.geometry!.latitude], ); } if (options.draggable != null) { @@ -406,7 +406,7 @@ class Convert { if (options.geometry != null) { geometry = Geometry( type: geometry.type, - coordinates: fillGeometryToFeatureGeometry(options.geometry), + coordinates: fillGeometryToFeatureGeometry(options.geometry!), ); } return feature.copyWith(properties: properties, geometry: geometry); diff --git a/mapbox_gl_web/lib/src/feature_manager/circle_manager.dart b/mapbox_gl_web/lib/src/feature_manager/circle_manager.dart index c55e3e1fd..94269242f 100644 --- a/mapbox_gl_web/lib/src/feature_manager/circle_manager.dart +++ b/mapbox_gl_web/lib/src/feature_manager/circle_manager.dart @@ -1,15 +1,9 @@ part of mapbox_gl_web; -/// Signature for when a tap has occurred. -typedef CircleTapCallback = void Function(String id); - class CircleManager extends FeatureManager { - final MapboxMap map; - final CircleTapCallback onTap; - CircleManager({ - @required this.map, - this.onTap, + required MapboxMap map, + ArgumentCallbacks? onTap, }) : super( sourceId: 'circle_source', layerId: 'circle_layer', @@ -42,7 +36,7 @@ class CircleManager extends FeatureManager { @override void update(String lineId, CircleOptions changes) { - Feature olfFeature = getFeature(lineId); + Feature olfFeature = getFeature(lineId)!; Feature newFeature = Convert.interpretCircleOptions(changes, olfFeature); updateFeature(newFeature); } diff --git a/mapbox_gl_web/lib/src/feature_manager/feature_manager.dart b/mapbox_gl_web/lib/src/feature_manager/feature_manager.dart index 2f850d70a..a4bcfbfb0 100644 --- a/mapbox_gl_web/lib/src/feature_manager/feature_manager.dart +++ b/mapbox_gl_web/lib/src/feature_manager/feature_manager.dart @@ -1,24 +1,21 @@ part of mapbox_gl_web; -/// Signature for when a tap has occurred. -typedef FeatureTapCallback = void Function(String id); - abstract class FeatureManager { final String sourceId; final String layerId; final MapboxMap map; - final FeatureTapCallback onTap; + final ArgumentCallbacks? onTap; @protected - LatLng dragOrigin; + late LatLng dragOrigin; final Map _features = {}; num featureCounter = 1; - String _draggableFeatureId; + String? _draggableFeatureId; FeatureManager({ - @required this.sourceId, - @required this.layerId, - @required this.map, + required this.sourceId, + required this.layerId, + required this.map, this.onTap, }) { var featureSource = GeoJsonSource(data: FeatureCollection(features: [])); @@ -59,7 +56,7 @@ abstract class FeatureManager { _updateSource(); } - Feature getFeature(String featureId) { + Feature? getFeature(String featureId) { return _features[featureId]; } @@ -67,9 +64,9 @@ abstract class FeatureManager { map.on('click', (e) { if (e is Event) { final features = map.queryRenderedFeatures([e.point.x, e.point.y]); - if (features.length > 0 && features[0].source == sourceId) { + if (features.isNotEmpty && features[0].source == sourceId) { if (onTap != null) { - onTap('${features[0].id}'); + onTap!('${features[0].id}'); } } } @@ -93,14 +90,14 @@ abstract class FeatureManager { _draggableFeatureId = '${e.features[0].id}'; map.getCanvas().style.cursor = 'grabbing'; var coords = e.lngLat; - dragOrigin = LatLng(coords.lat, coords.lng); + dragOrigin = LatLng(coords.lat as double, coords.lng as double); } }); map.on('mousemove', (e) { if (_draggableFeatureId != null) { var coords = e.lngLat; - onDrag(_draggableFeatureId, LatLng(coords.lat, coords.lng)); + onDrag(_draggableFeatureId!, LatLng(coords.lat, coords.lng)); } }); diff --git a/mapbox_gl_web/lib/src/feature_manager/fill_manager.dart b/mapbox_gl_web/lib/src/feature_manager/fill_manager.dart index 9c06fb249..14def9505 100644 --- a/mapbox_gl_web/lib/src/feature_manager/fill_manager.dart +++ b/mapbox_gl_web/lib/src/feature_manager/fill_manager.dart @@ -1,15 +1,9 @@ part of mapbox_gl_web; -/// Signature for when a tap has occurred. -typedef FillTapCallback = void Function(String id); - class FillManager extends FeatureManager { - final MapboxMap map; - final FillTapCallback onTap; - FillManager({ - @required this.map, - this.onTap, + required MapboxMap map, + ArgumentCallbacks? onTap, }) : super( sourceId: 'fill_source', layerId: 'fill_layer', @@ -33,7 +27,7 @@ class FillManager extends FeatureManager { @override void onDrag(String featureId, LatLng latLng) { - Feature oldFeature = getFeature(featureId); + Feature oldFeature = getFeature(featureId)!; final geometry = Convert.featureGeometryToFillGeometry(oldFeature.geometry.coordinates); update( @@ -45,7 +39,7 @@ class FillManager extends FeatureManager { @override void update(String featureId, FillOptions changes) { - Feature oldFeature = getFeature(featureId); + Feature oldFeature = getFeature(featureId)!; Feature newFeature = Convert.intepretFillOptions(changes, oldFeature); updateFeature(newFeature); } diff --git a/mapbox_gl_web/lib/src/feature_manager/line_manager.dart b/mapbox_gl_web/lib/src/feature_manager/line_manager.dart index 27a668bc6..59c3a71ed 100644 --- a/mapbox_gl_web/lib/src/feature_manager/line_manager.dart +++ b/mapbox_gl_web/lib/src/feature_manager/line_manager.dart @@ -1,15 +1,9 @@ part of mapbox_gl_web; -/// Signature for when a tap has occurred. -typedef LineTapCallback = void Function(String id); - class LineManager extends FeatureManager { - final MapboxMap map; - final LineTapCallback onTap; - LineManager({ - @required this.map, - this.onTap, + required MapboxMap map, + ArgumentCallbacks? onTap, }) : super( sourceId: 'line_source', layerId: 'line_layer', @@ -40,7 +34,7 @@ class LineManager extends FeatureManager { } void update(String lineId, LineOptions changes) { - Feature olfFeature = getFeature(lineId); + Feature olfFeature = getFeature(lineId)!; Feature newFeature = Convert.interpretLineOptions(changes, olfFeature); updateFeature(newFeature); } diff --git a/mapbox_gl_web/lib/src/feature_manager/symbol_manager.dart b/mapbox_gl_web/lib/src/feature_manager/symbol_manager.dart index 7ed68a210..a3d2e7567 100644 --- a/mapbox_gl_web/lib/src/feature_manager/symbol_manager.dart +++ b/mapbox_gl_web/lib/src/feature_manager/symbol_manager.dart @@ -1,15 +1,9 @@ part of mapbox_gl_web; -/// Signature for when a tap has occurred. -typedef SymbolTapCallback = void Function(String id); - class SymbolManager extends FeatureManager { - final MapboxMap map; - final SymbolTapCallback onTap; - SymbolManager({ - @required this.map, - this.onTap, + required MapboxMap map, + ArgumentCallbacks? onTap, }) : super( sourceId: 'symbol_source', layerId: 'symbol_layer', @@ -79,16 +73,15 @@ class SymbolManager extends FeatureManager { updateAll({lineId: changes}); } - void updateAll(Map changesById) { List featuresWithUpdatedOptions = []; changesById.forEach( (id, options) => featuresWithUpdatedOptions.add( Convert.interpretSymbolOptions( options, - getFeature(id) - ) - ) + getFeature(id)!, + ), + ), ); updateFeatures(featuresWithUpdatedOptions); } diff --git a/mapbox_gl_web/lib/src/mapbox_map_controller.dart b/mapbox_gl_web/lib/src/mapbox_map_controller.dart index d3687847d..459e76b0c 100644 --- a/mapbox_gl_web/lib/src/mapbox_map_controller.dart +++ b/mapbox_gl_web/lib/src/mapbox_map_controller.dart @@ -5,29 +5,29 @@ const _mapboxGlCssUrl = class MapboxMapController extends MapboxGlPlatform implements MapboxMapOptionsSink { - DivElement _mapElement; + late DivElement _mapElement; - Map _creationParams; - MapboxMap _map; + late Map _creationParams; + late MapboxMap _map; List annotationOrder = []; - SymbolManager symbolManager; - LineManager lineManager; - CircleManager circleManager; - FillManager fillManager; + late SymbolManager symbolManager; + late LineManager lineManager; + late CircleManager circleManager; + late FillManager fillManager; bool _trackCameraPosition = false; - GeolocateControl _geolocateControl; - LatLng _myLastLocation; + GeolocateControl? _geolocateControl; + LatLng? _myLastLocation; - String _navigationControlPosition; - NavigationControl _navigationControl; + String? _navigationControlPosition; + NavigationControl? _navigationControl; @override Widget buildView( Map creationParams, - Function onPlatformViewCreated, - Set> gestureRecognizers) { + OnPlatformViewCreatedCallback onPlatformViewCreated, + Set>? gestureRecognizers) { _creationParams = creationParams; _registerViewFactory(onPlatformViewCreated, this.hashCode); return HtmlElementView( @@ -81,7 +81,7 @@ class MapboxMapController extends MapboxGlPlatform } @override - Future updateMapOptions( + Future updateMapOptions( Map optionsUpdate) async { // FIX: why is called indefinitely? (map_ui page) Convert.interpretMapboxMapOptions(optionsUpdate, this); @@ -89,20 +89,16 @@ class MapboxMapController extends MapboxGlPlatform } @override - Future animateCamera(CameraUpdate cameraUpdate) async { + Future animateCamera(CameraUpdate cameraUpdate) async { final cameraOptions = Convert.toCameraOptions(cameraUpdate, _map); - if (cameraOptions != null) { - _map.flyTo(cameraOptions); - } + _map.flyTo(cameraOptions); return true; } @override - Future moveCamera(CameraUpdate cameraUpdate) async { + Future moveCamera(CameraUpdate cameraUpdate) async { final cameraOptions = Convert.toCameraOptions(cameraUpdate, _map); - if (cameraOptions != null) { - _map.jumpTo(cameraOptions); - } + _map.jumpTo(cameraOptions); return true; } @@ -114,7 +110,7 @@ class MapboxMapController extends MapboxGlPlatform @override Future matchMapLanguageWithDeviceDefault() async { - setMapLanguage(ui.window.locale.languageCode); + setMapLanguage(ui.window.locale!.languageCode); } @override @@ -140,21 +136,22 @@ class MapboxMapController extends MapboxGlPlatform @override Future> addSymbols(List options, - [List data]) async { - Map optionsById = Map.fromIterable(options, - key: (o) => symbolManager.add(Feature( - geometry: Geometry( - type: 'Point', - coordinates: [o.geometry.longitude, o.geometry.latitude], - ), - )), - value: (o) => o); + [List? data]) async { + Map optionsById = { + for (final o in options) + symbolManager.add(Feature( + geometry: Geometry( + type: 'Point', + coordinates: [o.geometry!.longitude, o.geometry!.latitude], + ), + )): o, + }; symbolManager.updateAll(optionsById); return optionsById .map((id, singleOptions) { int dataIndex = options.indexOf(singleOptions); - Map singleData = data != null && data.length >= dataIndex + 1 + Map? singleData = data != null && data.length >= dataIndex + 1 ? data[dataIndex] : null; return MapEntry(id, Symbol(id, singleOptions, singleData)); @@ -174,11 +171,11 @@ class MapboxMapController extends MapboxGlPlatform } @override - Future addLine(LineOptions options, [Map data]) async { + Future addLine(LineOptions options, [Map? data]) async { String lineId = lineManager.add(Feature( geometry: Geometry( type: 'LineString', - coordinates: options.geometry + coordinates: options.geometry! .map((latLng) => [latLng.longitude, latLng.latitude]) .toList(), ), @@ -198,11 +195,11 @@ class MapboxMapController extends MapboxGlPlatform } @override - Future addCircle(CircleOptions options, [Map data]) async { + Future addCircle(CircleOptions options, [Map? data]) async { String circleId = circleManager.add(Feature( geometry: Geometry( type: 'Point', - coordinates: [options.geometry.longitude, options.geometry.latitude], + coordinates: [options.geometry!.longitude, options.geometry!.latitude], ), )); circleManager.update(circleId, options); @@ -216,7 +213,7 @@ class MapboxMapController extends MapboxGlPlatform @override Future getCircleLatLng(Circle circle) async { - var coordinates = circleManager.getFeature(circle.id).geometry.coordinates; + var coordinates = circleManager.getFeature(circle.id)!.geometry.coordinates; return LatLng(coordinates[1], coordinates[0]); } @@ -225,11 +222,11 @@ class MapboxMapController extends MapboxGlPlatform circleManager.remove(circleId); } - Future addFill(FillOptions options, [Map data]) async { + Future addFill(FillOptions options, [Map? data]) async { String fillId = fillManager.add(Feature( geometry: Geometry( type: 'Polygon', - coordinates: Convert.fillGeometryToFeatureGeometry(options.geometry), + coordinates: Convert.fillGeometryToFeatureGeometry(options.geometry!), ), )); @@ -247,7 +244,7 @@ class MapboxMapController extends MapboxGlPlatform @override Future queryRenderedFeatures( - Point point, List layerIds, List filter) async { + Point point, List layerIds, List? filter) async { Map options = {}; if (layerIds.length > 0) { options['layers'] = layerIds; @@ -255,12 +252,24 @@ class MapboxMapController extends MapboxGlPlatform if (filter != null) { options['filter'] = filter; } - return _map.queryRenderedFeatures([point, point], options); + return _map + .queryRenderedFeatures([point, point], options) + .map((feature) => { + 'type': 'Feature', + 'id': feature.id as int?, + 'geometry': { + 'type': feature.geometry.type, + 'coordinates': feature.geometry.coordinates, + }, + 'properties': feature.properties, + 'source': feature.source, + }) + .toList(); } @override Future queryRenderedFeaturesInRect( - Rect rect, List layerIds, String filter) async { + Rect rect, List layerIds, String? filter) async { Map options = {}; if (layerIds.length > 0) { options['layers'] = layerIds; @@ -268,10 +277,22 @@ class MapboxMapController extends MapboxGlPlatform if (filter != null) { options['filter'] = filter; } - return _map.queryRenderedFeatures([ - Point(rect.left, rect.bottom), - Point(rect.right, rect.top), - ], options); + return _map + .queryRenderedFeatures([ + Point(rect.left, rect.bottom), + Point(rect.right, rect.top), + ], options) + .map((feature) => { + 'type': 'Feature', + 'id': feature.id as int?, + 'geometry': { + 'type': feature.geometry.type, + 'coordinates': feature.geometry.coordinates, + }, + 'properties': feature.properties, + 'source': feature.source, + }) + .toList(); } @override @@ -280,7 +301,7 @@ class MapboxMapController extends MapboxGlPlatform } @override - Future requestMyLocationLatLng() async { + Future requestMyLocationLatLng() async { return _myLastLocation; } @@ -288,15 +309,21 @@ class MapboxMapController extends MapboxGlPlatform Future getVisibleRegion() async { final bounds = _map.getBounds(); return LatLngBounds( - southwest: LatLng(bounds.getSouthWest().lat, bounds.getSouthWest().lng), - northeast: LatLng(bounds.getNorthEast().lat, bounds.getNorthEast().lng), + southwest: LatLng( + bounds.getSouthWest().lat as double, + bounds.getSouthWest().lng as double, + ), + northeast: LatLng( + bounds.getNorthEast().lat as double, + bounds.getNorthEast().lng as double, + ), ); } @override Future addImage(String name, Uint8List bytes, [bool sdf = false]) async { - final photo = decodeImage(bytes); + final photo = decodeImage(bytes)!; if (!_map.hasImage(name)) { _map.addImage( name, @@ -334,14 +361,14 @@ class MapboxMapController extends MapboxGlPlatform print('setSymbolTextIgnorePlacement not implemented yet'); } - CameraPosition _getCameraPosition() { + CameraPosition? _getCameraPosition() { if (_trackCameraPosition) { final center = _map.getCenter(); return CameraPosition( - bearing: _map.getBearing(), - target: LatLng(center.lat, center.lng), - tilt: _map.getPitch(), - zoom: _map.getZoom(), + bearing: _map.getBearing() as double, + target: LatLng(center.lat as double, center.lng as double), + tilt: _map.getPitch() as double, + zoom: _map.getZoom() as double, ); } return null; @@ -413,10 +440,10 @@ class MapboxMapController extends MapboxGlPlatform void _onCameraMove(_) { final center = _map.getCenter(); var camera = CameraPosition( - bearing: _map.getBearing(), - target: LatLng(center.lat, center.lng), - tilt: _map.getPitch(), - zoom: _map.getZoom(), + bearing: _map.getBearing() as double, + target: LatLng(center.lat as double, center.lng as double), + tilt: _map.getPitch() as double, + zoom: _map.getZoom() as double, ); onCameraMovePlatform(camera); } @@ -424,10 +451,10 @@ class MapboxMapController extends MapboxGlPlatform void _onCameraIdle(_) { final center = _map.getCenter(); var camera = CameraPosition( - bearing: _map.getBearing(), - target: LatLng(center.lat, center.lng), - tilt: _map.getPitch(), - zoom: _map.getZoom(), + bearing: _map.getBearing() as double, + target: LatLng(center.lat as double, center.lng as double), + tilt: _map.getPitch() as double, + zoom: _map.getZoom() as double, ); onCameraIdlePlatform(camera); } @@ -444,17 +471,17 @@ class MapboxMapController extends MapboxGlPlatform onCameraTrackingDismissedPlatform(null); } - void _addGeolocateControl({bool trackUserLocation}) { + void _addGeolocateControl({bool trackUserLocation = false}) { _removeGeolocateControl(); _geolocateControl = GeolocateControl( GeolocateControlOptions( positionOptions: PositionOptions(enableHighAccuracy: true), - trackUserLocation: trackUserLocation ?? false, + trackUserLocation: trackUserLocation, showAccuracyCircle: true, showUserLocation: true, ), ); - _geolocateControl.on('geolocate', (e) { + _geolocateControl!.on('geolocate', (e) { _myLastLocation = LatLng(e.coords.latitude, e.coords.longitude); onUserLocationUpdatedPlatform(UserLocation( position: LatLng(e.coords.latitude, e.coords.longitude), @@ -466,10 +493,10 @@ class MapboxMapController extends MapboxGlPlatform heading: null, timestamp: DateTime.fromMillisecondsSinceEpoch(e.timestamp))); }); - _geolocateControl.on('trackuserlocationstart', (_) { + _geolocateControl!.on('trackuserlocationstart', (_) { _onCameraTrackingChanged(true); }); - _geolocateControl.on('trackuserlocationend', (_) { + _geolocateControl!.on('trackuserlocationend', (_) { _onCameraTrackingChanged(false); _onCameraTrackingDismissed(); }); @@ -484,16 +511,16 @@ class MapboxMapController extends MapboxGlPlatform } void _updateNavigationControl({ - bool compassEnabled, - CompassViewPosition position, + bool? compassEnabled, + CompassViewPosition? position, }) { - bool prevShowCompass; + bool? prevShowCompass; if (_navigationControl != null) { - prevShowCompass = _navigationControl.options.showCompass; + prevShowCompass = _navigationControl!.options.showCompass; } - String prevPosition = _navigationControlPosition; + String? prevPosition = _navigationControlPosition; - String positionString; + String? positionString; switch (position) { case CompassViewPosition.TopRight: positionString = 'top-right'; @@ -512,7 +539,7 @@ class MapboxMapController extends MapboxGlPlatform } bool newShowComapss = compassEnabled ?? prevShowCompass ?? false; - String newPosition = positionString ?? prevPosition ?? null; + String? newPosition = positionString ?? prevPosition ?? null; _removeNavigationControl(); _navigationControl = NavigationControl(NavigationControlOptions( @@ -545,7 +572,7 @@ class MapboxMapController extends MapboxGlPlatform } @override - void setCameraTargetBounds(LatLngBounds bounds) { + void setCameraTargetBounds(LatLngBounds? bounds) { if (bounds == null) { _map.setMaxBounds(null); } else { @@ -585,7 +612,7 @@ class MapboxMapController extends MapboxGlPlatform } @override - void setMinMaxZoomPreference(num min, num max) { + void setMinMaxZoomPreference(num? min, num? max) { // FIX: why is called indefinitely? (map_ui page) _map.setMinZoom(min); _map.setMaxZoom(max); @@ -644,7 +671,7 @@ class MapboxMapController extends MapboxGlPlatform } @override - void setStyleString(String styleString) { + void setStyleString(String? styleString) { _map.setStyle(styleString); } @@ -701,7 +728,7 @@ class MapboxMapController extends MapboxGlPlatform Future toLatLng(Point screenLocation) async { var lngLat = _map.unproject(mapbox.Point(screenLocation.x, screenLocation.y)); - return LatLng(lngLat.lat, lngLat.lng); + return LatLng(lngLat.lat as double, lngLat.lng as double); } @override diff --git a/mapbox_gl_web/lib/src/options_sink.dart b/mapbox_gl_web/lib/src/options_sink.dart index 7698f5b30..9c326975d 100644 --- a/mapbox_gl_web/lib/src/options_sink.dart +++ b/mapbox_gl_web/lib/src/options_sink.dart @@ -2,14 +2,14 @@ part of mapbox_gl_web; abstract class MapboxMapOptionsSink { // TODO: dddd replace with CameraPosition.Builder target - void setCameraTargetBounds(LatLngBounds bounds); + void setCameraTargetBounds(LatLngBounds? bounds); void setCompassEnabled(bool compassEnabled); // TODO: styleString is not actually a part of options. consider moving - void setStyleString(String styleString); + void setStyleString(String? styleString); - void setMinMaxZoomPreference(num min, num max); + void setMinMaxZoomPreference(num? min, num? max); void setRotateGesturesEnabled(bool rotateGesturesEnabled); diff --git a/mapbox_gl_web/pubspec.yaml b/mapbox_gl_web/pubspec.yaml index f48606a64..0fd2c4b68 100644 --- a/mapbox_gl_web/pubspec.yaml +++ b/mapbox_gl_web/pubspec.yaml @@ -20,8 +20,8 @@ dependencies: git: url: https://github.com/tobrun/flutter-mapbox-gl.git path: mapbox_gl_platform_interface - mapbox_gl_dart: ^0.1.5 - image: ^3.0.2 + mapbox_gl_dart: ^0.2.0-nullsafety + image: ^3.0.0 dependency_overrides: mapbox_gl_platform_interface: @@ -32,5 +32,5 @@ dev_dependencies: sdk: flutter environment: - sdk: ">=2.1.0 <3.0.0" - flutter: ">=1.12.13+hotfix.4" + sdk: ">=2.12.0 <3.0.0" + flutter: ">=2.0.0" diff --git a/pubspec.lock b/pubspec.lock index eae87bfc3..6307528c2 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -7,49 +7,28 @@ packages: name: archive url: "https://pub.dartlang.org" source: hosted - version: "2.0.13" - args: - dependency: transitive - description: - name: args - url: "https://pub.dartlang.org" - source: hosted - version: "1.6.0" + version: "3.1.2" characters: dependency: transitive description: name: characters url: "https://pub.dartlang.org" source: hosted - version: "1.1.0-nullsafety.5" - charcode: - dependency: transitive - description: - name: charcode - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.3" + version: "1.1.0" collection: dependency: transitive description: name: collection url: "https://pub.dartlang.org" source: hosted - version: "1.15.0-nullsafety.5" - convert: - dependency: transitive - description: - name: convert - url: "https://pub.dartlang.org" - source: hosted - version: "2.1.1" + version: "1.15.0" crypto: dependency: transitive description: name: crypto url: "https://pub.dartlang.org" source: hosted - version: "2.1.5" + version: "3.0.1" flutter: dependency: "direct main" description: flutter @@ -66,60 +45,56 @@ packages: name: image url: "https://pub.dartlang.org" source: hosted - version: "2.1.19" + version: "3.0.2" js: dependency: transitive description: name: js url: "https://pub.dartlang.org" source: hosted - version: "0.6.3-nullsafety.3" + version: "0.6.3" mapbox_gl_dart: dependency: transitive description: name: mapbox_gl_dart url: "https://pub.dartlang.org" source: hosted - version: "0.1.5" + version: "0.2.0-nullsafety.0" mapbox_gl_platform_interface: dependency: "direct main" description: path: mapbox_gl_platform_interface - ref: HEAD - resolved-ref: "37703aa872a877d0dc4c88fe358647003f4949cc" - url: "https://github.com/tobrun/flutter-mapbox-gl.git" - source: git - version: "0.9.0" + relative: true + source: path + version: "0.12.0" mapbox_gl_web: dependency: "direct main" description: path: mapbox_gl_web - ref: HEAD - resolved-ref: "37703aa872a877d0dc4c88fe358647003f4949cc" - url: "https://github.com/tobrun/flutter-mapbox-gl.git" - source: git - version: "0.9.0" + relative: true + source: path + version: "0.12.0" meta: dependency: transitive description: name: meta url: "https://pub.dartlang.org" source: hosted - version: "1.3.0-nullsafety.6" + version: "1.3.0" path: dependency: transitive description: name: path url: "https://pub.dartlang.org" source: hosted - version: "1.7.0" + version: "1.8.0" petitparser: dependency: transitive description: name: petitparser url: "https://pub.dartlang.org" source: hosted - version: "3.1.0" + version: "4.1.0" sky_engine: dependency: transitive description: flutter @@ -131,21 +106,21 @@ packages: name: typed_data url: "https://pub.dartlang.org" source: hosted - version: "1.3.0-nullsafety.5" + version: "1.3.0" vector_math: dependency: transitive description: name: vector_math url: "https://pub.dartlang.org" source: hosted - version: "2.1.0-nullsafety.5" + version: "2.1.0" xml: dependency: transitive description: name: xml url: "https://pub.dartlang.org" source: hosted - version: "4.5.1" + version: "5.1.0" sdks: - dart: ">=2.12.0-0 <3.0.0" - flutter: ">=1.12.13+hotfix.4 <2.0.0" + dart: ">=2.12.0 <3.0.0" + flutter: ">=2.0.0" diff --git a/pubspec.yaml b/pubspec.yaml index 464a5cea9..f692d044a 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -15,6 +15,12 @@ dependencies: url: https://github.com/tobrun/flutter-mapbox-gl.git path: mapbox_gl_web +dependency_overrides: + mapbox_gl_platform_interface: + path: ./mapbox_gl_platform_interface + mapbox_gl_web: + path: ./mapbox_gl_web + flutter: plugin: platforms: @@ -27,6 +33,6 @@ flutter: default_package: mapbox_gl_web environment: - sdk: ">=2.1.0 <3.0.0" + sdk: '>=2.12.0 <3.0.0' # Flutter versions prior to 1.10 did not support the flutter.plugin.platforms map. - flutter: ">=1.10.0" + flutter: ">=2.0.0" From 19fff8115d0722e76c2b39b0cfa9c6db6c8318e8 Mon Sep 17 00:00:00 2001 From: morvag Date: Wed, 21 Apr 2021 16:38:31 +0200 Subject: [PATCH 2/3] address comments --- .../mapbox/mapboxgl/MapboxMapController.java | 14 ++------------ .../lib/src/camera.dart | 2 +- .../lib/src/location.dart | 17 +++++++---------- .../lib/src/method_channel_mapbox_gl.dart | 6 +++--- 4 files changed, 13 insertions(+), 26 deletions(-) diff --git a/android/src/main/java/com/mapbox/mapboxgl/MapboxMapController.java b/android/src/main/java/com/mapbox/mapboxgl/MapboxMapController.java index 24ec3d6df..62b3cbd75 100644 --- a/android/src/main/java/com/mapbox/mapboxgl/MapboxMapController.java +++ b/android/src/main/java/com/mapbox/mapboxgl/MapboxMapController.java @@ -1236,18 +1236,8 @@ public void setTiltGesturesEnabled(boolean tiltGesturesEnabled) { @Override public void setMinMaxZoomPreference(Float min, Float max) { - //mapboxMap.resetMinMaxZoomPreference(); - if (min != null) { - mapboxMap.setMinZoomPreference(min); - } else { - mapboxMap.setMinZoomPreference(MapboxConstants.MINIMUM_ZOOM); - } - if (max != null) { - mapboxMap.setMaxZoomPreference(max); - } - else { - mapboxMap.setMaxZoomPreference(MapboxConstants.MAXIMUM_ZOOM); - } + mapboxMap.setMinZoomPreference(min != null ? min : MapboxConstants.MINIMUM_ZOOM); + mapboxMap.setMaxZoomPreference(max != null ? max : MapboxConstants.MAXIMUM_ZOOM); } @Override diff --git a/mapbox_gl_platform_interface/lib/src/camera.dart b/mapbox_gl_platform_interface/lib/src/camera.dart index 219cff119..3094923aa 100644 --- a/mapbox_gl_platform_interface/lib/src/camera.dart +++ b/mapbox_gl_platform_interface/lib/src/camera.dart @@ -62,7 +62,7 @@ class CameraPosition { } return CameraPosition( bearing: json['bearing'], - target: LatLng._fromJson(json['target'])!, + target: LatLng._fromJson(json['target']), tilt: json['tilt'], zoom: json['zoom'], ); diff --git a/mapbox_gl_platform_interface/lib/src/location.dart b/mapbox_gl_platform_interface/lib/src/location.dart index bc839c72c..d93ead548 100644 --- a/mapbox_gl_platform_interface/lib/src/location.dart +++ b/mapbox_gl_platform_interface/lib/src/location.dart @@ -36,10 +36,7 @@ class LatLng { return [latitude, longitude]; } - static LatLng? _fromJson(dynamic json) { - if (json == null) { - return null; - } + static LatLng _fromJson(List json) { return LatLng(json[0], json[1]); } @@ -87,8 +84,8 @@ class LatLngBounds { return null; } return LatLngBounds( - southwest: LatLng._fromJson(json[0])!, - northeast: LatLng._fromJson(json[1])!, + southwest: LatLng._fromJson(json[0]), + northeast: LatLng._fromJson(json[1]), ); } @@ -141,10 +138,10 @@ class LatLngQuad { return null; } return LatLngQuad( - topLeft: LatLng._fromJson(json[0])!, - topRight: LatLng._fromJson(json[1])!, - bottomRight: LatLng._fromJson(json[2])!, - bottomLeft: LatLng._fromJson(json[3])!, + topLeft: LatLng._fromJson(json[0]), + topRight: LatLng._fromJson(json[1]), + bottomRight: LatLng._fromJson(json[2]), + bottomLeft: LatLng._fromJson(json[3]), ); } diff --git a/mapbox_gl_platform_interface/lib/src/method_channel_mapbox_gl.dart b/mapbox_gl_platform_interface/lib/src/method_channel_mapbox_gl.dart index 56ebd36bf..fbc12ae07 100644 --- a/mapbox_gl_platform_interface/lib/src/method_channel_mapbox_gl.dart +++ b/mapbox_gl_platform_interface/lib/src/method_channel_mapbox_gl.dart @@ -121,12 +121,12 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { @override Widget buildView( Map creationParams, - Function onPlatformViewCreated, + OnPlatformViewCreatedCallback onPlatformViewCreated, Set>? gestureRecognizers) { if (defaultTargetPlatform == TargetPlatform.android) { return AndroidView( viewType: 'plugins.flutter.io/mapbox_gl', - onPlatformViewCreated: onPlatformViewCreated as void Function(int)?, + onPlatformViewCreated: onPlatformViewCreated, gestureRecognizers: gestureRecognizers, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), @@ -134,7 +134,7 @@ class MethodChannelMapboxGl extends MapboxGlPlatform { } else if (defaultTargetPlatform == TargetPlatform.iOS) { return UiKitView( viewType: 'plugins.flutter.io/mapbox_gl', - onPlatformViewCreated: onPlatformViewCreated as void Function(int)?, + onPlatformViewCreated: onPlatformViewCreated, gestureRecognizers: gestureRecognizers, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), From aa7a12318e4b6b095981d18e27dddba4f3b81387 Mon Sep 17 00:00:00 2001 From: morvag Date: Thu, 22 Apr 2021 09:28:13 +0200 Subject: [PATCH 3/3] fixed parameter type of _fromJson --- mapbox_gl_platform_interface/lib/src/location.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mapbox_gl_platform_interface/lib/src/location.dart b/mapbox_gl_platform_interface/lib/src/location.dart index d93ead548..c64e05e2c 100644 --- a/mapbox_gl_platform_interface/lib/src/location.dart +++ b/mapbox_gl_platform_interface/lib/src/location.dart @@ -36,7 +36,7 @@ class LatLng { return [latitude, longitude]; } - static LatLng _fromJson(List json) { + static LatLng _fromJson(List json) { return LatLng(json[0], json[1]); }