Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Magic Lane Maps SDK for Flutter Documentation
https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7
Admin
Documentation for Magic Lane Maps SDK for Flutter
Tokens:
1,712,667
Snippets:
15,249
Trust Score:
3.5
Update:
2 months ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
================ LIBRARY RULES ================ - This project uses: flutter, dart, sdk ================ CODE SNIPPETS ================ ### Main App Setup in Flutter Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/examples/17_maps-3dscene/05_map-gestures.md Sets up the basic structure of a Flutter application, including the MaterialApp and MyHomePage widgets. This is the entry point for the map gesture example. ```dart class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, title: 'Map Gestures', home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } ``` -------------------------------- ### Main Application Setup Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/examples/17_routing-navigation/02_route-profile.md Sets up the basic MaterialApp and MyHomePage widget for the application. Includes basic navigation and state management setup. ```dart void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(debugShowCheckedModeBanner: false, title: 'Route Profile', home: MyHomePage()); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { late GemMapController _mapController; // We use the handler to cancel the route calculation. TaskHandler? _routingHandler; Route? _focusedRoute; final ElevationChartController _chartController = ElevationChartController(); @override void dispose() { GemKit.release(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.deepPurple[900], title: const Text('Route Profile', style: TextStyle(color: Colors.white)), actions: [ // Routes are not built. if (_routingHandler == null && _focusedRoute == null) IconButton( onPressed: () => _onBuildRouteButtonPressed(context), icon: const Icon(Icons.route, color: Colors.white), ), // Routes calculating is in progress. if (_routingHandler != null) IconButton( onPressed: () => _onCancelRouteButtonPressed(), icon: const Icon(Icons.stop, color: Colors.white), ), // Routes calculating is finished. if (_focusedRoute != null) IconButton( onPressed: () => _onClearRoutesButtonPressed(), icon: const Icon(Icons.clear, color: Colors.white), ), ], ), body: Stack( children: [ GemMap(key: ValueKey("GemMap"), onMapCreated: _onMapCreated, appAuthorization: projectApiToken), if (_focusedRoute != null) Align( alignment: Alignment.bottomCenter, child: RouteProfilePanel( route: _focusedRoute!, mapController: _mapController, chartController: _chartController, centerOnRoute: () => _centerOnRoute([_focusedRoute!]), ), ), ], ), ); } // The callback for when map is ready to use. Future<void> _onMapCreated(GemMapController controller) async { // Save controller for further usage. _mapController = controller; // Register route tap gesture callback. await _registerRouteTapCallback(); } void _onBuildRouteButtonPressed(BuildContext context) { // Define the departure. final departureLandmark = Landmark.withLatLng(latitude: 46.59344, longitude: 7.91069); // Define the destination. final destinationLandmark = Landmark.withLatLng(latitude: 46.55945, longitude: 7.89293); // Define the route preferences. // Terrain profile has to be enabled for this example to work. final routePreferences = RoutePreferences( buildTerrainProfile: const BuildTerrainProfile(enable: true), transportMode: RouteTransportMode.pedestrian, ); _showSnackBar(context, message: "The route is being calculated."); // Calling the calculateRoute SDK method. // (err, results) - is a callback function that gets called when the route computing is finished. // err is an error enum, results is a list of routes. _routingHandler = RoutingService.calculateRoute([departureLandmark, destinationLandmark], routePreferences, ( err, routes, ) { // If the route calculation is finished, we don't have a progress listener anymore. _routingHandler = null; ScaffoldMessenger.of(context).clearSnackBars(); // If there aren't any errors, we display the routes. if (err == GemError.success) { // Get the routes collection from map preferences. final routesMap = _mapController.preferences.routes; // Display the routes on map. for (final route in routes) { routesMap.add(route, route == routes.first, label: getMapLabel(route)); } // Center the camera on routes. _centerOnRoute(routes); setState(() { _focusedRoute = routes.first; }); } }); setState(() {}); } void _onClearRoutesButtonPressed() { _mapController.preferences.paths.clear(); // Remove the routes from map. _mapController.preferences.routes.clear(); setState(() { _focusedRoute = null; }); } } ``` -------------------------------- ### start Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/sense/DataSource-class.html Starts the data source. ```APIDOC ## start ### Description Start the data source. ### Method start ### Returns - [GemError](../core/GemError.html) - An error object if starting fails, otherwise null or an indicator of success. ``` -------------------------------- ### SoundMark.start Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/sense/SoundMark/start.html Gets or sets the start offset in milliseconds for a SoundMark. The value must be within the bounds of the sound log length. ```APIDOC ## SoundMark.start ### Description This property represents the starting point of a sound mark within a log, specified in milliseconds. It can be both read (getter) and written to (setter). ### Getter/Setter This is a getter/setter pair. ### Parameters #### Setter Parameter * **start** (int) - Required - The start offset in milliseconds. Must be between 0 and the log length. ``` -------------------------------- ### DataSource.start Method Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/sense/DataSource/start.html Starts the data source, initiating data production. Some data sources start automatically upon creation. ```APIDOC ## start Method ### Description Starts the data source. Begins producing data (live sampling or playback) depending on the data source type. Some data sources types are automatically started upon creation and calling this method has no effect. ### Method Signature `GemError start()` ### Returns * `GemError.success` on success. * Other `GemError` values on failure. ``` -------------------------------- ### Install iOS Dependencies Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/examples/17_get-started-with-sample-apps/index.md Navigate to the 'ios' directory and run this command to install CocoaPods dependencies if targeting iOS. ```bash cd ios pod install ``` -------------------------------- ### Start Simulation Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/navigation/NavigationService-class.html Starts a simulated navigation session. This is useful for testing and development purposes. ```APIDOC ## startSimulation ### Description Starts simulated navigation. ### Method `startSimulation` ### Parameters (Details not provided in source, but likely similar to `startNavigation`) ### Response Returns a `TaskHandler` to manage the simulation session. ``` -------------------------------- ### Fetch Project Dependencies Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/examples/17_get-started-with-sample-apps/index.md Run this command in the root directory of the example project to download necessary packages. ```bash flutter pub get ``` -------------------------------- ### Get Map Version Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/map/MapDetails/mapVersion.html Retrieves the currently installed map data version. This implementation calls a static method to get the version string and then parses it into a Version object. ```Dart static Version get mapVersion { final OperationResult resultString = staticMethod( 'MapDetails', 'getMapVersion', ); return Version.fromJson(resultString['result']); } ``` -------------------------------- ### startTime Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/driver_behaviour/DriverBehaviourAnalysis/startTime.html Gets the start time of the session in milliseconds since the Unix epoch (UTC). ```APIDOC ## startTime ### Description Gets the start time of the session in milliseconds since the Unix epoch (UTC). ### Method GET ### Endpoint N/A (Dart property) ### Returns - **int** - The start time in milliseconds since epoch. ### Implementation Example ```dart // Assuming 'driverBehaviourAnalysis' is an instance of DriverBehaviourAnalysis int sessionStartTime = driverBehaviourAnalysis.startTime; ``` ``` -------------------------------- ### timezoneId Property Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/core/TimezoneResult/timezoneId.html Gets the ID of the timezone. The format is 'Continent/City_Name', with examples like 'Europe/Paris' or 'America/New_York'. ```APIDOC ## timezoneId Property ### Description Gets the ID of the timezone. It is in the format "Continent/City_Name". Examples: Europe/Paris, America/New_York, Europe/Moscow. ### Signature `String get timezoneId` ### Implementation ```dart String get timezoneId { final OperationResult resultString = objectMethod( pointerId, 'TimezoneResult', 'timezoneId', ); return resultString['result']; } ``` ``` -------------------------------- ### Create and Start Simulation Data Source Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/guides/5_positioning/03_custom-positioning.md Create a simulation data source from a route and register it with the PositionService. Ensure to start the data source after registration. ```dart final dataSource = DataSource.createSimulationDataSource(route); if (dataSource == null) { showSnackbar("The datasource could not be created"); return; } PositionService.setExternalDataSource(dataSource); dataSource.start(); ``` -------------------------------- ### Get TrafficEvent startTime Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/core/TrafficEvent/startTime.html Retrieves the UTC start time of a traffic event. Returns null if the start time is not available. This implementation uses an internal objectMethod to fetch the time in milliseconds since the epoch. ```dart DateTime? get startTime { final OperationResult resultString = objectMethod( pointerId, 'TrafficEvent', 'getStartTime', ); final int milliseconds = resultString['result']; if (milliseconds == 0) { return null; } return DateTime.fromMillisecondsSinceEpoch(milliseconds, isUtc: true); } ``` -------------------------------- ### startNavigation Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/navigation/NavigationService/startNavigation.html Initiates navigation along a specified route. This method accepts a `Route` object and a comprehensive set of optional callback functions to handle different navigation events. It registers these callbacks with the platform and returns a `TaskHandlerImpl` to manage the navigation task. An `ArgumentError` is thrown if both `onNavigationInstruction` and `onNavigationInstructionOptimized` are provided. ```APIDOC ## startNavigation ### Description Starts navigation along a specified route. This method accepts a `Route` object and a comprehensive set of optional callback functions to handle different navigation events. It registers these callbacks with the platform and returns a `TaskHandlerImpl` to manage the navigation task. An `ArgumentError` is thrown if both `onNavigationInstruction` and `onNavigationInstructionOptimized` are provided. ### Method `static TaskHandlerImpl? startNavigation({ required Route route, void Function()? onNavigationStarted, void Function(NavigationInstruction instruction, Set<NavigationInstructionUpdateEvents> events)? onNavigationInstruction, void Function()? onNavigationInstructionOptimized, void Function(Landmark destination)? onDestinationReached, void Function(GemError error)? onError, void Function(NavigationStatus status)? onNotifyStatusChange, void Function()? onRouteCalculationStarted, void Function(GemError error)? onRouteCalculationCompleted, void Function(Route route)? onRouteUpdated, void Function(TextToSpeechInstruction instruction)? onTextToSpeechInstruction, void Function()? onBetterRouteDetected, void Function()? onBetterRouteRejected, void Function()? onBetterRouteInvalidated, void Function()? onSkipNextIntermediateDestinationDetected, void Function()? onTurnAround, void Function(Set<RouteRestrictionType> exitRestrictions, Set<RouteRestrictionType> enterRestrictions)? onRestrictionsUpdated, }) async ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart // Example usage: final route = Route(/* ... */); NavigationService.startNavigation( route: route, onNavigationStarted: () => print('Navigation started!'), onDestinationReached: (destination) => print('Destination reached: ${destination.name}'), onError: (error) => print('Navigation error: ${error.message}'), ); ``` ### Response #### Success Response - **TaskHandlerImpl?**: Returns a `TaskHandlerImpl` object if navigation starts successfully, otherwise returns `null`. #### Response Example ```json { "result": "TaskHandlerImpl object or null" } ``` ### Error Handling - **ArgumentError**: Thrown if both `onNavigationInstruction` and `onNavigationInstructionOptimized` callbacks are provided. - **GemError**: If an error occurs during route calculation or navigation, the `onError` callback is invoked with a `GemError` object. ``` -------------------------------- ### Get TrafficEvent isActive Status Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/core/TrafficEvent/isActive.html Retrieves the active status of a TrafficEvent. This getter checks if the event has started. ```dart bool get isActive { final OperationResult resultString = objectMethod( pointerId, 'TrafficEvent', 'isActive', ); return resultString['result']; } ``` -------------------------------- ### Start Download with Progress and Completion Callbacks Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/content_store/ContentStoreItem/asyncDownload.html Initiates a download for a content item and logs progress and completion status. Ensure GemError and related types are imported. ```dart item.asyncDownload((GemError err) { if (err == GemError.success) { print('Download finished successfully'); } else { print('Download failed: $err'); } }, onProgress: (int p) { print('Download progress: $p%'); }); ``` -------------------------------- ### durationMillis property Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/sense/LogMetadata/durationMillis.html Gets the total duration of the log in milliseconds. This is typically calculated as the difference between the end and start timestamps. ```APIDOC ## durationMillis property ### Description Gets the total duration of the log in milliseconds. This is typically calculated as the difference between the end and start timestamps. ### Method GET ### Endpoint LogMetadata.durationMillis ### Returns - **int** - An integer representing the duration in milliseconds. ### See Also - [activeDurationMillis](../../sense/LogMetadata/activeDurationMillis.html): Total active recording time excluding pauses. ``` -------------------------------- ### Starting Navigation with Instruction Callback Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/navigation/NavigationInstruction-class.html Demonstrates how to initiate navigation and receive real-time navigation instructions via a callback. This is the primary method for accessing NavigationInstruction instances during an active session. ```dart NavigationService.startNavigation( route, onNavigationInstruction: (instruction, events) { // Use the instruction object }, ); ``` -------------------------------- ### Registering a Sound Start Callback Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/core/SoundPlayingListener/registerOnStart.html Use this method to set a function that will be called every time the SDK starts playing a sound. The callback receives no arguments. ```dart void registerOnStart(final void Function()? callback) { _onStart = callback; } ``` -------------------------------- ### Get maxElevationDistance Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/core/RouteTerrainProfile/maxElevationDistance.html Retrieves the distance in meters from the route start where the maximum elevation occurs. This is part of the RouteTerrainProfile class. ```Dart int get maxElevationDistance { final OperationResult resultString = objectMethod( pointerId, 'RouteTerrainProfile', 'getMaxElevationDistance', ); return resultString['result']; } ``` -------------------------------- ### Main Application Setup Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/examples/17_routing-navigation/24_speed-tts-warning.md Sets up the main application widget, including the MaterialApp, navigation, and the home page. It also defines constants for API tokens. ```dart const projectApiToken = String.fromEnvironment('YOUR_API_TOKEN_HERE'); void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, title: 'Speed Tts Warning', home: MyHomePage(), ); } } ``` -------------------------------- ### minElevationDistance Property Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/core/RouteTerrainProfile/minElevationDistance.html Gets the distance from the route start where the route reaches its minimum elevation. The distance is returned in meters. ```APIDOC ## minElevationDistance Property ### Description Gets the distance from the route start where the route reaches its minimum elevation. The distance is returned in meters. ### Returns * Distance in meters. ### Related Properties * [maxElevation](../../core/RouteTerrainProfile/maxElevation.html) - Maximum elevation along the route * [maxElevationDistance](../../core/RouteTerrainProfile/maxElevationDistance.html) - Distance where maximum elevation occurs ``` -------------------------------- ### startSimulation Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/navigation/NavigationService/startSimulation.html Initiates a navigation simulation. This method takes a `Route` object and an optional `speedMultiplier`. It also accepts a comprehensive set of callback functions to handle various navigation events, such as starting, instruction updates, reaching waypoints or destinations, errors, route updates, and more. If both `onNavigationInstruction` and `onNavigationInstructionOptimized` are provided, an `ArgumentError` is thrown. ```APIDOC ## startSimulation ### Description Starts a navigation simulation with the given route and optional callbacks. ### Method static void startSimulation({ required Route route, required void Function(NavigationInstruction instruction, Set<NavigationInstructionUpdateEvents> events)? onNavigationInstruction, required void Function(NavigationInstruction instruction, Set<NavigationInstructionUpdateEvents> events)? onNavigationInstructionOptimized, required void Function()? onNavigationStarted, required void Function()? onWaypointReached, required void Function(Landmark destination)? onDestinationReached, required void Function(GemError error)? onRouteUpdated, required void Function(TextToSpeechInstruction instruction)? onTextToSpeechInstruction, required void Function(GemError reason)? onBetterRouteRejected, required void Function()? onBetterRouteInvalidated, required void Function()? onSkipNextIntermediateDestinationDetected, required void Function()? onTurnAround, required void Function( Set<RouteRestrictionType> exitRestrictions, Set<RouteRestrictionType> enterRestrictions, )? onRestrictionsUpdated, required void Function(GemError error)? onError, required void Function(NavigationStatus status)? onNotifyStatusChange, required void Function()? onRouteCalculationStarted, required void Function(GemError error)? onRouteCalculationCompleted, double speedMultiplier = 1.0, }) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) Returns a `TaskHandlerImpl` object that can be used to manage the simulation. #### Response Example ```dart TaskHandlerImpl ``` ### Error Handling - Throws `ArgumentError` if both `onNavigationInstruction` and `onNavigationInstructionOptimized` callbacks are provided. - If `gemApiError` indicates an error, the `onError` callback is invoked with the corresponding `GemError`. ``` -------------------------------- ### Main Application Setup Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/examples/17_maps-3dscene/09_advanced-follow-position.md Sets up the main Flutter application, initializes the GemKit, and defines the basic UI structure including the app bar, map, and tabbed panels for controls and information. ```dart void main() async { WidgetsFlutterBinding.ensureInitialized(); await GemKit.initialize(appAuthorization: projectApiToken); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(title: 'Follow Position Advanced', debugShowCheckedModeBanner: false, home: MyHomePage()); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { final FollowPositionController _controller = FollowPositionController(); TaskHandler? _routingTask; TaskHandler? _simulationTask; bool _hasMapRoute = false; GemMapController? _mapController; @override void dispose() { _controller.dispose(); GemKit.release(); super.dispose(); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: _controller, builder: (context, _) { return LayoutBuilder( builder: (context, constraints) { final bool isLandscape = constraints.maxWidth > constraints.maxHeight; final double sidePanelWidth = min(360, constraints.maxWidth * 0.5); final Widget bodyContent = isLandscape ? _buildLandscapeLayout(sidePanelWidth) : _buildPortraitLayout(); return Scaffold( appBar: AppBar( backgroundColor: Colors.deepPurple[900], title: const Text('Follow Position Advanced', style: TextStyle(color: Colors.white)), actions: [ if (!_hasMapRoute && _routingTask == null && _simulationTask == null) IconButton( icon: const Icon(Icons.directions_car, color: Colors.white), onPressed: _calculateAndNavigate, ), if (_hasMapRoute) IconButton( icon: const Icon(Icons.clear, color: Colors.white), onPressed: _hasMapRoute ? _cancelRoutingAndNavigation : null, ), ], ), body: Column(children: [Expanded(child: bodyContent)]), ); }, ); }, ); } void _onMapCreated(GemMapController controller) async { _mapController = controller; _controller.attachMapController(controller); await _controller.refreshInfo(); } Widget _buildLandscapeLayout(double sidePanelWidth) { return Row( children: [ Expanded( child: GemMap(key: const ValueKey('GemMap'), onMapCreated: _onMapCreated, appAuthorization: projectApiToken), ), SizedBox(width: sidePanelWidth, child: _buildPanelTabs()), ], ); } Widget _buildPortraitLayout() { return SafeArea( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: GemMap( key: const ValueKey('GemMap'), onMapCreated: _onMapCreated, appAuthorization: projectApiToken, ), ), Expanded(child: _buildPanelTabs()), ], ), ); } Widget _buildPanelTabs() { return DefaultTabController( length: 2, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Material( color: Colors.deepPurple[900], child: TabBar( tabs: const [ Tab(text: 'Info'), Tab(text: 'Controls'), ], indicatorColor: Colors.white, labelColor: Colors.white, unselectedLabelColor: Colors.white70, ), ), Expanded( child: TabBarView( children: [ FollowPositionInfoPanel(controller: _controller), FollowPositionControlsPanel(controller: _controller), ], ), ), ], ), ); } } ``` -------------------------------- ### Main App Setup and UI Integration Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/examples/17_routing-navigation/08_public-transit.md Sets up the main Flutter application, including the MaterialApp, MyHomePage widget, and the AppBar with route-related action buttons. It also initializes the GemMap and handles its creation callback. ```dart void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, title: 'Public Transit', home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { late GemMapController _mapController; // We use the handler to cancel the route calculation. TaskHandler? _routingHandler; List<PTRouteSegment>? _ptSegments; @override void dispose() { GemKit.release(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.deepPurple[900], title: const Text( 'Public Transit', style: TextStyle(color: Colors.white), ), actions: [ // Routes are not built. if (_routingHandler == null && _ptSegments == null) IconButton( onPressed: () => _onBuildRouteButtonPressed(context), icon: const Icon(Icons.route, color: Colors.white), ), // Routes calculating is in progress. if (_routingHandler != null) IconButton( onPressed: () => _onCancelRouteButtonPressed(), icon: const Icon(Icons.stop, color: Colors.white), ), // Routes calculating is finished. if (_ptSegments != null) IconButton( onPressed: () => _onClearRoutesButtonPressed(), icon: const Icon(Icons.clear, color: Colors.white), ), ], ), body: Stack( alignment: AlignmentDirectional.bottomCenter, children: [ GemMap( key: ValueKey("GemMap"), onMapCreated: _onMapCreated, appAuthorization: projectApiToken, ), if (_ptSegments != null) Padding( padding: const EdgeInsets.all(8.0), child: Container( height: MediaQuery.of(context).size.height * 0.1, width: MediaQuery.of(context).size.width * 0.9, color: Colors.white, child: Row( // Build a TransitSegment to display data from each segment children: _ptSegments!.map((segment) { return TransitSegment(segment: segment); }).toList(), ), ), ), ], ), ); } // The callback for when map is ready to use. Future<void> _onMapCreated(GemMapController controller) async { // Save controller for further usage. _mapController = controller; // Register route tap gesture callback. await _registerRouteTapCallback(); } ``` -------------------------------- ### Get Start Timestamp in Millis Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/sense/LogMetadata/startTimestampInMillis.html Retrieves the timestamp of the first sensor data in milliseconds since epoch from the LogMetadata object. ```Dart int get startTimestampInMillis { final OperationResult resultString = objectMethod( pointerId, 'LogMetadata', 'getStartTimestampInMillis', ); return resultString['result']; } ``` -------------------------------- ### Get Elevation Samples Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/core/RouteTerrainProfile/getElevationSamples.html Retrieves sampled elevation values for a specified route interval. Use this method to get elevation data for a given number of samples between a start and end distance along a route. It returns the elevation samples and their resolution. ```Dart (List<double>, double) getElevationSamples( final int countSamples, final int distBegin, final int distEnd, ) { final OperationResult resultString = objectMethod( pointerId, 'RouteTerrainProfile', 'getElevationSamplesBE', args: <String, int>{ 'countSamples': countSamples, 'distBegin': distBegin, 'distEnd': distEnd, }, ); final List<dynamic> listDynamic = resultString['result']['floatlist']; final List<double> listFloat = listDynamic.cast<double>(); final double sample = resultString['result']['sample']; return (listFloat, sample); } ``` -------------------------------- ### Create and Start Recorder Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/guides/5_positioning/04_recorder.md This snippet shows how to create a live data source, configure it for background location updates, and then create and start the recorder. Ensure you have the necessary permissions and configurations set up. ```dart final logsDir = await _getLogsDir(); // Create the live data source final dataSource = DataSource.createLiveDataSource()!; // Enable background location updates final config = dataSource.getConfiguration(DataType.position); config.allowsBackgroundLocationUpdates = true; dataSource.setConfiguration(type: DataType.position, config: config); // Create the recorder with config final recorder = Recorder.create( RecorderConfiguration( dataSource: dataSource, logsDir: logsDir, recordedTypes: [DataType.position], ), ); // Start recording final errorStart = await recorder.startRecording(); if (errorStart != GemError.success) { showSnackbar("Error starting recording: $errorStart"); } ``` -------------------------------- ### Get continuousRecording Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/sense/RecorderConfiguration/continuousRecording.html Retrieves the current state of the continuousRecording property. When true, new recordings are started automatically when the current chunk completes. ```APIDOC ## Get continuousRecording ### Description Retrieves the current state of the continuousRecording property. When true, new recordings are started automatically when the current chunk completes. ### Method GET ### Endpoint /RecorderConfiguration/continuousRecording ### Response #### Success Response (200) - **continuousRecording** (bool) - Whether recordings continue automatically after a chunk ends. ``` -------------------------------- ### Example Link Generation (Full URL) Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/guides/2_get-started/06_coding-with-ai.md Generates a full URL to a documentation file, including the protocol, for use in links. ```javascript const { siteConfig } = useDocusaurusContext(); const baseUrl = siteConfig.baseUrl.replace(///$/, ''); const url = `${siteConfig.url}${baseUrl}/${file}`; const display = `${siteConfig.url.replace(/^https?: strip//, '')}${baseUrl}/${file}`; return <a href={url}>{display}</a>; ``` -------------------------------- ### Starting a Map Download Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/map/MapDownloaderService/startDownload.html Demonstrates how to initiate a map tile download for a given area and handle the completion callback. Ensure the MapDownloaderService is instantiated and maxSquareKm is set appropriately. ```dart final service = MapDownloaderService(); service.maxSquareKm = 300; service.startDownload([area], (err) { if (err == GemError.success) { print('Download started successfully.'); } else { print('Failed to start download: $err'); } }); ``` -------------------------------- ### Get timeBeforeTurnPresentation Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/map/FollowPositionPreferences/timeBeforeTurnPresentation.html Retrieves the current time interval in seconds before turn presentation starts. Returns -1 if the SDK default is used. ```Dart int get timeBeforeTurnPresentation { final OperationResult resultString = objectMethod( pointerId, 'FollowPositionPreferences', 'getTimeBeforeTurnPresentation', dependencyId: _mapPointerId, ); return resultString['result']; } ``` -------------------------------- ### Start Audio Recording Implementation Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/sense/Recorder/startAudioRecording.html This is the implementation of the startAudioRecording method. It calls the objectMethod with relevant parameters to initiate the audio capture process. ```dart void startAudioRecording() { objectMethod(pointerId, 'Recorder', 'startAudioRecording'); } ``` -------------------------------- ### RouteTrafficEvent.from Implementation Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/core/RouteTrafficEvent/from.html Retrieves the start coordinate of a traffic event on the route. This implementation uses an internal method to get the coordinate data. ```dart Coordinates get from { final OperationResult resultString = objectMethod( pointerId, 'RouteTrafficEvent', 'getFrom', ); return Coordinates.fromJson(resultString['result']); } ``` -------------------------------- ### Start Recording Implementation Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/sense/Recorder/startRecording.html This is the implementation of the startRecording method. It calls the native platform using invokeMethod to initiate recording and returns a GemError based on the platform's response. ```Dart Future<GemError> startRecording() async { final String? resultString = await GemKitPlatform.instance .getChannel(mapId: -1) .invokeMethod<String>( 'callObjectMethod', jsonEncode(<String, Object>{ 'id': pointerId, 'class': 'Recorder', 'method': 'startRecording', 'args': <dynamic, dynamic>{}, }), ); return GemErrorExtension.fromCode(jsonDecode(resultString!)['result']); } ``` -------------------------------- ### Get Elevation by Distance Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/core/RouteTerrainProfile/getElevation.html Retrieves the elevation in meters at a specific distance from the route start. Requires the distance in meters as an integer parameter. ```dart double getElevation(final int distance) { final OperationResult resultString = objectMethod( pointerId, 'RouteTerrainProfile', 'getElevation', args: distance, ); return resultString['result']; } ``` -------------------------------- ### startRecording Method Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/sense/Recorder/startRecording.html Starts the recording session. Initiates the recorder and transitions status to RecorderStatus.starting and then to RecorderStatus.recording on success. Always await the returned future to ensure the operation has completed. ```APIDOC ## startRecording() ### Description Starts the recording session. Initiates the recorder and transitions status to [RecorderStatus.starting](../../sense/RecorderStatus.html) and then to [RecorderStatus.recording](../../sense/RecorderStatus.html) on success. Always `await` the returned future to ensure the operation has completed. ### Method ```dart Future<GemError> startRecording() ``` ### Returns * [GemError.success](../../core/GemError.html) The recorder started and is in [RecorderStatus.recording](../../sense/RecorderStatus.html). * [GemError.busy](../../core/GemError.html) The recorder is busy and could not start. * [GemError.invalidInput](../../core/GemError.html) The provided configuration is invalid (for example none of the requested [RecorderConfiguration.recordedTypes](../../sense/RecorderConfiguration/recordedTypes.html) are available). * [GemError.noDiskSpace](../../core/GemError.html) Not enough disk space to start recording. * [GemError.overheated](../../core/GemError.html) Device temperature prevents starting the recorder. * [GemError.accessDenied](../../core/GemError.html) Required permissions are missing to start recording (check audio recording permissions). * [GemError.general](../../core/GemError.html) A generic error occurred. ### Implementation Example ```dart Future<GemError> startRecording() async { final String? resultString = await GemKitPlatform.instance .getChannel(mapId: -1) .invokeMethod<String>( 'callObjectMethod', jsonEncode(<String, Object>{ 'id': pointerId, 'class': 'Recorder', 'method': 'startRecording', 'args': <dynamic, dynamic>{}, }), ); return GemErrorExtension.fromCode(jsonDecode(resultString!)['result']); } ``` ``` -------------------------------- ### Get Coordinate on Route by Distance Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/core/RouteBase/getCoordinateOnRoute.html Retrieves the coordinate on the route at a specified distance from the start. Returns an invalid coordinate if the distance is out of bounds. ```dart Coordinates getCoordinateOnRoute(final int distance) { final OperationResult resultString = objectMethod( pointerId, 'RouteBase', 'getCoordinateOnRoute', args: distance, ); return Coordinates.fromJson(resultString['result']); } ``` -------------------------------- ### Get enableAudio Property Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/sense/RecorderConfiguration/enableAudio.html Retrieves the current status of whether audio tracks are enabled for recordings. This is useful for checking the configuration before starting a recording. ```dart bool get enableAudio { final OperationResult resultString = objectMethod( pointerId, 'RecorderConfiguration', 'getEnableAudio', ); return resultString['result']; } ``` -------------------------------- ### Get isTrackedPositions Property Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/map/MapViewExtensions/isTrackedPositions.html Retrieves the current status of position tracking. Use this to check if visualization is active before attempting to start or stop tracking. ```dart bool get isTrackedPositions { final OperationResult resultString = objectMethod( _pointerId, 'MapViewExtensions', 'isTrackedPositions', dependencyId: _mapControllerId, ); return resultString['result'] as bool; } ``` -------------------------------- ### Initialize GemKit and Run App Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/examples/17_routing-navigation/23_simulate-navigation-without-map.md Initializes the GemKit SDK with an API token and runs the main application. Ensure you have set the 'YOUR_API_TOKEN_HERE' environment variable. ```dart const projectApiToken = String.fromEnvironment('YOUR_API_TOKEN_HERE'); Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); await GemKit.initialize(appAuthorization: projectApiToken); runApp(const MyApp()); } ``` -------------------------------- ### Step-by-Step Address Search Example Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/guides/6_search/02_search-geocoding-features.md Demonstrates using the `searchAddress` function to progressively find landmarks for country, city, street, and house number. Assumes `showSnackbar` is defined elsewhere. ```dart final countryLandmark = GuidedAddressSearchService.getCountryLevelItem('ESP'); showSnackbar('Country: ${countryLandmark!.name}'); // Use the address search to get a landmark for a city in Spain (e.g., Barcelona). final cityLandmark = await searchAddress( landmark: countryLandmark, detailLevel: AddressDetailLevel.city, text: 'Barcelona', ); if (cityLandmark == null) return; showSnackbar('City: ${cityLandmark.name}'); // Use the address search to get a predefined street's landmark in the city (e.g., Carrer de Mallorca). final streetLandmark = await searchAddress( landmark: cityLandmark, detailLevel: AddressDetailLevel.street, text: 'Carrer de Mallorca', ); if (streetLandmark == null) return; showSnackbar('Street: ${streetLandmark.name}'); // Use the address search to get a predefined house number's landmark on the street (e.g., House Number 401). final houseNumberLandmark = await searchAddress( landmark: streetLandmark, detailLevel: AddressDetailLevel.houseNumber, text: '401', ); if (houseNumberLandmark == null) return; showSnackbar('House number: ${houseNumberLandmark.name}'); ``` -------------------------------- ### MapDownloaderService Constructor Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/map/MapDownloaderService/MapDownloaderService.html Creates a new MapDownloaderService instance. Use this constructor to obtain a service instance for starting downloads and getting transfer statistics. ```dart factory MapDownloaderService() { return MapDownloaderService._create(); } ``` -------------------------------- ### Get startTime Property Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/driver_behaviour/DriverBehaviourAnalysis/startTime.html Retrieves the start time of the session in milliseconds since the Unix epoch (UTC). This getter is part of the DriverBehaviourAnalysis class. ```Dart int get startTime { final OperationResult resultString = objectMethod( pointerId, 'DriverBehaviourAnalysis', 'getStartTime', ); return resultString['result']; } ``` -------------------------------- ### startSimulation Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/navigation/NavigationService/startSimulation.html Starts a simulated navigation session. Provides comprehensive event callbacks for instruction updates, waypoint arrivals, route recalculations, better route detection, and error handling. Simulation continues until destination is reached, cancelled, or an error occurs. ```APIDOC ## startSimulation static method ### Description Simulated navigation session. Starts turn-by-turn navigation using simulated position data based on the [Route]. Provides comprehensive event callbacks for instruction updates, waypoint arrivals, route recalculations, better route detection, and error handling. Simulation continues until destination is reached, cancelled, or an error occurs. ### Parameters * `route` (Route) - Required - Route to navigate. Obtain via [RoutingService.calculateRoute]. * `onNavigationInstruction` (void Function(NavigationInstruction instruction, Set<NavigationInstructionUpdateEvents> events)?) - Optional - Callback for instruction updates. Arguments: * `instruction`: Updated navigation instruction. * `events`: Set of events triggering the update (turn updated, lane info updated, etc.). Cannot be combined with `onNavigationInstructionOptimized`. * `onNavigationInstructionOptimized` (void Function(NavigationInstruction instruction, NavigationInstructionUpdateInfo updateInfo)?) - Optional - Optimized callback for instruction updates. Arguments: * `instruction`: Updated navigation instruction. * `updateInfo`: Detailed update info containing the set of changed fields, a new-route flag, and the triggering events. Use [NavigationInstructionUpdateInfo.differences] to redraw only affected UI components. Cannot be combined with `onNavigationInstruction`. * `onNavigationStarted` (void Function()?) - Optional - Callback when navigation begins (first valid position received). * `onTextToSpeechInstruction` (void Function(String textInstruction)?) - Optional - Callback for TTS text. Arguments: * `textInstruction`: Text to be spoken by TTS engine. See [SoundPlayingService] to enable TTS. * `onWaypointReached` (void Function(Landmark landmark)?) - Optional - Callback when intermediate waypoint reached. Arguments: * `landmark`: Reached waypoint landmark. * `onDestinationReached` (void Function(Landmark landmark)?) - Optional - Callback when the destination is reached. * `onRouteUpdated` (void Function(Route route)?) - Optional - Callback when the route is updated. * `onBetterRouteDetected` (void Function(Route route, int travelTime, int delay, int timeGain)?) - Optional - Callback when a better route is detected. * `onBetterRouteRejected` (void Function(GemError reason)?) - Optional - Callback when a better route is rejected. * `onBetterRouteInvalidated` (void Function()?) - Optional - Callback when a better route is invalidated. * `onSkipNextIntermediateDestinationDetected` (void Function()?) - Optional - Callback when the next intermediate destination is skipped. * `onTurnAround` (void Function()?) - Optional - Callback when a turn around is required. * `onRestrictionsUpdated` (void Function(Set<RouteRestrictionType> exitRestrictions, Set<RouteRestrictionType> enterRestrictions)?) - Optional - Callback when route restrictions are updated. * `onError` (void Function(GemError reason)?) - Optional - Callback for general errors. * `onNotifyStatusChange` (void Function(NavigationStatus status)?) - Optional - Callback to notify status changes. * `onRouteCalculationStarted` (void Function()?) - Optional - Callback when route calculation starts. * `onRouteCalculationCompleted` (void Function(GemError reason)?) - Optional - Callback when route calculation completes. * `speedMultiplier` (double) - Optional - Default: 1.0 - Multiplier for the simulation speed. ``` -------------------------------- ### Basic App Structure with Map Integration Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/examples/17_routing-navigation/06_gpx-route.md Sets up the main MaterialApp, MyHomePage widget, AppBar with route-related actions, and the GemMap widget. Handles map controller creation and basic state management for route building and simulation. ```dart class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp(debugShowCheckedModeBanner: false, title: 'GPX Route', home: MyHomePage()); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { late GemMapController _mapController; bool _isSimulationActive = false; bool _isGpxDataLoaded = false; bool _areRoutesBuilt = false; // We use the handler to cancel the navigation. TaskHandler? _navigationHandler; @override void initState() { _copyGpxToAppDocsDir(); super.initState(); } @override void dispose() { GemKit.release(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.deepPurple[900], title: const Text("GPX Route", style: TextStyle(color: Colors.white)), actions: [ if (!_isSimulationActive && _areRoutesBuilt) IconButton( onPressed: _startSimulation, icon: const Icon(Icons.play_arrow, color: Colors.white), ), if (_isSimulationActive) IconButton( onPressed: _stopSimulation, icon: const Icon(Icons.stop, color: Colors.white), ), if (!_areRoutesBuilt) IconButton( onPressed: _importGPX, icon: const Icon(Icons.route, color: Colors.white), ), ], ), body: GemMap(key: ValueKey("GemMap"), onMapCreated: _onMapCreated, appAuthorization: projectApiToken), ); } // The callback for when map is ready to use. void _onMapCreated(GemMapController controller) { // Save controller for further usage. _mapController = controller; } ``` -------------------------------- ### chunkDurationSeconds getter Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/sense/RecorderConfiguration/chunkDurationSeconds.html Gets the chunk duration in seconds used to split recordings. A value of 0 disables chunking. When enabled, the recorder verifies sufficient disk space before starting a chunk. If continuous recording is true, a new recording starts automatically after a chunk finishes. ```APIDOC ## get chunkDurationSeconds ### Description Gets the chunk duration (seconds) used to split recordings. A value of 0 disables chunking. When enabled, the recorder verifies there is enough disk space to store a full chunk before starting. When a chunk finishes, the current recording stops; if [continuousRecording](../../sense/RecorderConfiguration/continuousRecording.html) is true, a new recording starts automatically. ### Method GET ### Endpoint /RecorderConfiguration/chunkDurationSeconds ### Response #### Success Response (200) - **chunkDurationSeconds** (int) - The duration in seconds for recording chunks. ``` -------------------------------- ### Get Previous Route Instruction Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/navigation/NavigationInstruction/previousInstruction.html Retrieves the RouteInstruction immediately before the current navigation position. Returns null if unavailable, such as at the start of the route or if an error occurs. ```dart RouteInstruction? get previousInstruction { final OperationResult resultString = objectMethod( pointerId, 'NavigationInstruction', 'getPreviousInstruction', ); final GemError gemApiError = GemErrorExtension.fromCode( resultString['gemApiError'], ); if (gemApiError != GemError.success) { return null; } return RouteInstruction.init(resultString['result']); } ``` -------------------------------- ### SettingsService Constructors Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/core/SettingsService-class-sidebar.html Details on how to create and initialize instances of the SettingsService. ```APIDOC ## SettingsService() ### Description Creates a new instance of the SettingsService. ### Method Constructor ### Endpoint N/A (Dart Class Constructor) ## SettingsService.init() ### Description Initializes the SettingsService. This is the primary way to create and set up a service instance. ### Method Constructor ### Endpoint N/A (Dart Class Constructor) ``` -------------------------------- ### Flutter App Setup Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/examples/17_routing-navigation/07_truck-profile.md Sets up the basic MaterialApp and MyHomePage widget for the Flutter application. ```dart class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, title: 'Truck Profile', home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } ``` -------------------------------- ### Get Recorded Types Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/sense/RecorderConfiguration/recordedTypes.html Retrieves the list of data types that are configured to be recorded by the recorder. If any requested type is not produced by the configured dataSource, the recorder will refuse to start. ```APIDOC ## GET recordedTypes ### Description Retrieves the list of [DataType] values that the recorder will capture. If any requested type is not produced by the configured [dataSource], the recorder will refuse to start. ### Method GET ### Endpoint RecorderConfiguration.recordedTypes ### Response #### Success Response (200) - **recordedTypes** (List<DataType>) - The list of data types to be recorded. ``` -------------------------------- ### Basic SettingsService Usage Source: https://github.com/magiclane/magiclane-maps-sdk-for-flutter-docs-context7/blob/main/api-references/3.1.9/core/SettingsService-class.html Demonstrates setting and retrieving string and integer values, and ensuring persistence with flush. Includes a default value for retrieval. ```dart final settings = SettingsService(); settings.setString('username', 'alice'); settings.setInt('launchCount', 1); settings.flush(); // ensure values are persisted final name = settings.getString('username', defaultValue: 'guest'); ```