Save Favorites¶
Setup¶
Prerequisites¶
Run the example¶
Start a terminal/command prompt and go to the save_favorites
directory,
within the flutter examples directory
Build and run the example:
Build and run¶
Note - the gem_kit
directory containing the Maps SDK for Flutter
should be in the plugins
directory of the example, e.g.
save_favorites/plugins/gem_kit
- see the environment setup guide above.
Download project dependencies:
flutter upgrade
run the following terminal commands in the project directory,
where the pubspec.yaml
file is located:
flutter clean
flutter pub get
Run the example:
flutter run
If such a question appears, select the chrome
browser; in the above example, press 2.
First, verify that the ANDROID_SDK_ROOT
environment variable
is set to the root path of your android SDK.
In android/build.gradle
add the maven {}
block as shown,
within the allprojects {} block
, for both debug and release builds,
without the line numbers, those are for reference:
1allprojects {
2 repositories {
3 google()
4 mavenCentral()
5 maven {
6 url "${rootDir}/../plugins/gem_kit/android/build"
7 }
8 }
9}
in android/app/build.gradle
within the android {}
block, in the defaultConfig {}
block,
the android SDK version minSdkVersion
must be set as shown below.
Additionally, for release builds, in android/app/build.gradle
,
within the android {}
block, add the buildTypes {}
block as shown:
1android {
2 defaultConfig {
3 applicationId "com.magiclane.gem_kit.examples.save_favorites"
4 minSdkVersion 21
5 targetSdkVersion flutter.targetSdkVersion
6 versionCode flutterVersionCode.toInteger()
7 versionName flutterVersionName
8 }
9 buildTypes {
10 release {
11 // TODO: Add your own signing config for the release build.
12 // Signing with the debug keys for now, so `flutter run --release` works.
13 minifyEnabled false
14 shrinkResources false
15 signingConfig signingConfigs.debug
16 }
17 }
18}
Then build the apk:
flutter build apk --debug
flutter build apk --release
build/app/outputs/apk/debug
or
build/app/outputs/apk/release
subdirectory,
for debug or release build respectively,
within the current project directory, which is save_favorites
in this case.app-release.apk
or app-debug.apk
adb push app-release.apk sdcard
And then click on the apk in the file browser on the device to install and run it.
In the ios/Podfile
configuration text file, at the top, set the minimum ios
platform to 13 like this:
platform :ios, '13.0'
pod install
in the [ios folder] ./ios/
flutter build ios
to build a Runner.app.flutter run
to build and run on an attached device.<path/to>/ios/Runner.xcworkspace
project in Xcode
and execute and debug from there.How it works¶
In the save_favorites
project directory, there is a text file named
pubspec.yaml
which contains project configuration and dependencies.
The most important lines from this file are shown here:
1name: simulate_route
2version: 1.0.0+1
3
4environment:
5 sdk: '>=3.0.5 <4.0.0'
6
7dependencies:
8 flutter:
9 sdk: flutter
10 gem_kit:
11 path: plugins/gem_kit
12
13 cupertino_icons: ^1.0.2
14
15# The following section is specific to Flutter packages.
16flutter:
17 uses-material-design: true
The project must have a name and version. The dependencies list the Flutter SDK, and the gem_kit, Maps for Flutter SDK.
The source code is in save_favorites/lib/main.dart
1import 'dart:typed_data';
2
3import 'package:flutter/material.dart';
4
5import 'package:gem_kit/api/gem_coordinates.dart';
6import 'package:gem_kit/api/gem_landmark.dart';
7import 'package:gem_kit/api/gem_landmarkstore.dart';
8import 'package:gem_kit/api/gem_landmarkstoreservice.dart';
9import 'package:gem_kit/api/gem_mapviewrendersettings.dart';
10import 'package:gem_kit/api/gem_routingservice.dart';
11import 'package:gem_kit/api/gem_sdksettings.dart';
12import 'package:gem_kit/gem_kit_map_controller.dart';
13import 'package:gem_kit/widget/gem_kit_map.dart';
14
15import 'favorites_page.dart';
16import 'landmark_panel.dart';
17import 'utility.dart';
18
19void main() {
20 runApp(const MyApp());
21}
22
23class MyApp extends StatelessWidget {
24 const MyApp({super.key});
25
26 // This widget is the root of your application.
27 @override
28 Widget build(BuildContext context) {
29 return const MaterialApp(
30 debugShowCheckedModeBanner: false,
31 title: 'Save favorites example',
32 home: MyHomePage(),
33 );
34 }
35}
36
37// Model class which contains information about the landmark
38class PanelInfo {
39 Uint8List? image;
40 String name;
41 String categoryName;
42 String formattedCoords;
43
44 PanelInfo(
45 {this.image,
46 required this.name,
47 required this.categoryName,
48 required this.formattedCoords});
49}
50
51class MyHomePage extends StatefulWidget {
52 const MyHomePage({super.key});
53
54 @override
55 State<MyHomePage> createState() => _MyHomePageState();
56}
The dart
material package is imported, as well as the gem_kit
packages for the map controller, which enables user input such as pan and zoom,
the map package which draws the map, the landmark and coordinates packages for
geolocation, the landmarkstore and landmarkstoreservice for favorites,
and the settings and mapviewrendersettings packages.
The map is in a widget which is the root of the application.
1class _MyHomePageState extends State<MyHomePage> {
2 Landmark? _focusedLandmark;
3 // GemMapController object used to interact with the map
4 late GemMapController _mapController;
5
6 // SdkSettings object to initialize the SDK
7 late SdkSettings _sdkSettings;
8
9 // LandmarkStoreServiceObject to get or create the LandmarkStore
10 late LandmarkStoreService _landmarkStoreService;
11
12 // LandmarkStore object to save Landmarks
13 late LandmarkStore? _favoritesStore;
14
15 late bool _isLandmarkFavorite;
16
17 final favoritesStoreName = 'Favorites';
18
19 @override
20 void initState() {
21 super.initState();
22 }
23
24 Future<void> onMapCreated(GemMapController controller) async {
25 _mapController = controller;
26 _focusedLandmark = null;
27 _isLandmarkFavorite = false;
28
29 final token = 'YOUR_API_KEY_TOKEN';
30
31 SdkSettings.create(_mapController.mapId).then((value) {
32 _sdkSettings = value;
33 _sdkSettings.setAppAuthorization(token);
34 });
35
36 // Instantiate the LandmarkStoreService.
37 _landmarkStoreService = await LandmarkStoreService.create(controller.mapId);
38
39 // Retrieves the LandmarkStore with the given name.
40 _favoritesStore =
41 await _landmarkStoreService.getLandmarkStoreByName(favoritesStoreName);
42
43 // If there is no LandmarkStore with this name, then create it.
44 _favoritesStore ??=
45 await _landmarkStoreService.createLandmarkStore(favoritesStoreName);
46
47 // Listen for map landmark selection events.
48 _registerLandmarkTapCallback();
49 }
The map is initialized with the map controller and the settings.
Setting the API key¶
The string |
A tap on a landmark causes a panel to appear at the bottom, showing the name, coordinates, and an icon indicating the type of the landmark. If the heart icon on the right side is white inside, that means the landmark is not in the favorites list, and a tap on the heart will add it to the favorites. Conversely, if the heart icon is completely red inside, that means the landmark is in the favorites list. To remove it from the list, tap the heart icon, and when the heart icon becomes white inside, that means the landmark is no longer in the favorites list.
1@override
2Widget build(BuildContext context) {
3 return Scaffold(
4 appBar: AppBar(
5 backgroundColor: Colors.deepPurple[900],
6 title: const Text('Favourites'),
7 actions: [
8 IconButton(
9 onPressed: () => _onFavouritesButtonPressed(context),
10 icon: const Icon(Icons.favorite))
11 ],
12 ),
13 body: Center(
14 child: Stack(children: [
15 GemMap(
16 onMapCreated: onMapCreated,
17 ),
18 if (_focusedLandmark != null)
19 Positioned(
20 bottom: 30,
21 left: 10,
22 child: FutureBuilder<PanelInfo>(
23 future: getInfo(),
24 builder: (context, snapshot) {
25 if (!snapshot.hasData) {
26 return Container();
27 }
28 return LandmarkPanel(
29 onCancelTap: onCancelTap,
30 onFavoritesTap: onFavoritesTap,
31 isFavoriteLandmark: _isLandmarkFavorite,
32 coords: snapshot.data!.formattedCoords,
33 category: snapshot.data!.name,
34 img: snapshot.data!.image!,
35 name: snapshot.data!.name,
36 );
37 }),
38 )
39 ]),
40 ),
41 resizeToAvoidBottomInset: false,
42 );
43}
The top purple panel with the white heart icon to go to the list of saved favorites.
1Future<PanelInfo> getInfo() async {
2 late Uint8List? iconFuture;
3 late String nameFuture;
4 late Coordinates coordsFuture;
5 late String coordsFutureText;
6 late List<LandmarkCategory> categoriesFuture;
7
8 iconFuture = await _decodeLandmarkIcon(_focusedLandmark!);
9 nameFuture = await _focusedLandmark!.getName();
10 coordsFuture = await _focusedLandmark!.getCoordinates();
11 coordsFutureText =
12 "${coordsFuture.latitude.toString()}, ${coordsFuture.longitude.toString()}";
13 categoriesFuture = await _focusedLandmark!.getCategories();
14
15 return PanelInfo(
16 image: iconFuture,
17 name: nameFuture,
18 categoryName:
19 categoriesFuture.isNotEmpty ? categoriesFuture.first.name! : '',
20 formattedCoords: coordsFutureText);
21}
22
23Future<Uint8List?> _decodeLandmarkIcon(Landmark landmark) async {
24 final data = await landmark.getImage(100, 100);
25 return decodeImageData(data);
26}
This Future
retrieves the information about the selected landmark,
which will then be displayed in the LandmarkPanel.
1_registerLandmarkTapCallback() {
2 _mapController.registerTouchCallback((pos) async {
3 // Select the object at the tap position.
4 await _mapController.selectMapObjects(pos);
5
6 // Get the selected landmarks.
7 final landmarks = await _mapController.cursorSelectionLandmarks();
8
9 final landmarksSize = await landmarks.size();
10
11 // Check if there is a selected Landmark.
12 if (landmarksSize == 0) return;
13
14 // Highlight the landmark on the map.
15 _mapController.activateHighlight(landmarks);
16
17 final lmk = await landmarks.at(0);
18 setState(() {
19 _focusedLandmark = lmk;
20 });
21
22 await _checkIfFavourite();
23 });
24}
If the user tapped on the map, check if there are any landmarks at that location. If there are, grab the first one (at index 0) and check if it is already in the list of favorites.
1_onFavouritesButtonPressed(BuildContext context) async {
2 // Fetch landmarks from the store
3 final favoritesList = await _favoritesStore!.getLandmarks();
4
5 // Navigating to favorites screen then the result will be the selected item in the list.
6 final result = await Navigator.of(context).push(MaterialPageRoute(
7 builder: (context) => FavoritesPage(landmarkList: favoritesList),
8 ));
9
10 // Create a list of landmarks to highlight.
11 LandmarkList landmarkList = await LandmarkList.create(_mapController.mapId);
12
13 if (result is! Landmark) {
14 return;
15 }
16
17 // Add the result to the landmark list.
18 await landmarkList.push_back(result);
19 final coords = await result.getCoordinates();
20
21 // Highlight the landmark on the map.
22 await _mapController.activateHighlight(landmarkList,
23 renderSettings: RenderSettings());
24
25 // Centering the camera on landmark's coordinates
26 await _mapController.centerOnCoordinates(coords);
27
28 setState(() {
29 _focusedLandmark = result;
30 });
31 await _checkIfFavourite();
32}
The method to navigate to the favorites list page.
1void onCancelTap() {
2 // Remove landmark highlights from the map
3 _mapController.deactivateAllHighlights();
4
5 setState(() {
6 _focusedLandmark = null;
7 _isLandmarkFavorite = false;
8 });
9}
10
11void onFavoritesTap() async {
12 await _checkIfFavourite();
13
14 if (_isLandmarkFavorite) {
15 // Remove the landmark to the store.
16 await _favoritesStore!.removeLandmark(_focusedLandmark!);
17 } else {
18 // Add the landmark to the store.
19 await _favoritesStore!.addLandmark(_focusedLandmark!);
20 }
21 setState(() {
22 _isLandmarkFavorite = !_isLandmarkFavorite;
23 });
24}
Once the landmark info panel is displayed at the bottom, about the selected landmark, the heart icon is either white inside, and a tap on it adds the landmark to the favorites, or the heart icon is red inside, and a tap on it removes the landmark from the favorites.
A tap on the heart icon at the top right shows the list of favorites.
1_checkIfFavourite() async {
2 final focusedLandmarkCoords = await _focusedLandmark!.getCoordinates();
3 final favourites = await _favoritesStore!.getLandmarks();
4 final favoritesSize = await favourites.size();
5
6 for (int i = 0; i < favoritesSize; i++) {
7 final lmk = await favourites.at(i);
8 final coords = await lmk.getCoordinates();
9
10 if (focusedLandmarkCoords.latitude == coords.latitude &&
11 focusedLandmarkCoords.longitude == coords.longitude) {
12 setState(() {
13 _isLandmarkFavorite = true;
14 });
15 return;
16 }
17 }
18
19 setState(() {
20 _isLandmarkFavorite = false;
21 });
22}
23}
A method to check if the highlighted landmark is in the favorites list.