Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Fix CarPlay crashing on big browse lists

Barnabas18291d014f1e
diff --git a/lib/services/android_auto_service.dart b/lib/services/android_auto_service.dart
index b8498729..6aa8fd25 100644
--- a/lib/services/android_auto_service.dart
+++ b/lib/services/android_auto_service.dart
@@ -1233,7 +1233,10 @@ class AndroidAutoService {
// any bucket that's still too big - so a huge letter splits rather than being
// truncated. We also skip characters that don't split (e.g. the space in
// "The ") so the pile breaks by the real word.
- static const int bucketThreshold = 100;
+ // 50 keeps final lists short and scannable (more letter drilldown) on both
+ // surfaces; CarPlay's memory is handled by the patched plugin image loader,
+ // so this is a navigation-feel choice, not a crash guard.
+ static const int bucketThreshold = 50;
// Cached full (title-sorted) book list per library so re-navigating doesn't
// re-fetch the whole library each time.
diff --git a/packages/flutter_carplay/CHANGELOG.md b/packages/flutter_carplay/CHANGELOG.md
new file mode 100644
index 00000000..149c9863
--- /dev/null
+++ b/packages/flutter_carplay/CHANGELOG.md
@@ -0,0 +1,123 @@
+## 1.2.11
+
+- Fix `List<CPTemplate>` is not a subtype of `Iterable<CPListTemplate>` in `updateTemplates` (#92) (ty @EArminjon)
+- Fix failed cast on `updateCPListItem` when item is not in root template (#91) (ty @RedC4ke)
+
+## 1.2.10
+
+- Add `@objc(FlutterCarPlaySceneDelegate)` annotation for iOS 26 compatibility (#87)
+
+This enables apps to reference the delegate class as `flutter_carplay.FlutterCarPlaySceneDelegate` in their scene manifest configuration. Required for runtime class discovery via `NSClassFromString`. Thanks @APIUM!
+
+## 1.2.9
+
+- Add missing `@available(iOS 14.0, *)` annotations to `makeUIImage` and `loadUIImageAsync` (#84)
+
+These functions reference `SwiftFlutterCarplayPlugin` which requires iOS 14.0+, so Swift requires the availability annotation to propagate. This was missing since v1.2.5.
+
+## 1.2.8
+
+- Fix build failure on Xcode without iOS 26 SDK (follow up to #84)
+
+The v1.2.7 fix using `#if compiler(>=6.0)` didn't work because Swift 6.0 shipped with Xcode 16 (iOS 18), before iOS 26. Now uses dynamic selector invocation to avoid compile time symbol lookup for `updateImage`.
+
+## 1.2.7
+
+- Fix build failure on Xcode versions without iOS 26 SDK (#84)
+
+The `CPGridButton.updateImage()` API introduced in 1.2.5 is only available in iOS 26+. This caused compile errors on older Xcode versions since `#available` only handles runtime checks, not compile time SDK availability. iOS 26 specific code is now wrapped in `#if compiler(>=6.0)` to ensure older toolchains skip it entirely.
+
+- Fix type mismatch in `updateTabBarTemplates` that prevented compilation
+
+## 1.2.6
+
+- Fix compatibility with Dart's `--obfuscate` flag by using explicit type checks instead of `runtimeType.toString()` (fixes #28)
+- Add security policy (SECURITY.md)
+
+## 1.2.5
+
+- Fix main thread image loading crash for CPListItem and CPGridButton in https://github.com/oguzhnatly/flutter_carplay/pull/79 (ty @EArminjon)
+
+This fixes a crash caused by creating UIImage on background threads. Network images are now loaded asynchronously using URLSession, and placeholder images are shown until the actual image loads. For iOS 26+, CPGridButton uses the new `updateImage()` API for async updates.
+
+## 1.2.4
+
+- Fix file URI percent encoding for album art paths with spaces in https://github.com/oguzhnatly/flutter_carplay/pull/82 (ty @APIUM)
+- Add `sectionIndexEnabled` option to CPListTemplate for hiding section index letters in https://github.com/oguzhnatly/flutter_carplay/pull/83 (ty @APIUM)
+
+## 1.2.3
+
+- Update tab bar template to support mixed template types in https://github.com/oguzhnatly/flutter_carplay/pull/81
+
+This enhances the tab bar template by enabling support for multiple template types (not just list templates) as tab bar children. Supported template types: CPListTemplate, CPPointOfInterestTemplate, CPGridTemplate, CPInformationTemplate (ty @shihabkandil).
+
+## 1.2.2
+
+**Issues:**
+Calling `updateTemplates` or `updateSections` updates the layout correctly when the CarPlay is already active, but fail to do when CarPlay not yet started. Using `updateTemplates` or `updateSections` doesn’t refresh ListItem's handler properly, causing missing callbacks. This results in items showing a loading indicator for several seconds because the end event never fires.
+
+It's been updated by @EArminjon in https://github.com/oguzhnatly/flutter_carplay/pull/77
+
+**Fixes :**
+- Ensure `updateTemplate` and `updateSections` correctly refresh all relevant data and update the `final _super.handler`.
+- Reformatted the code.
+- Reuse existing `CPTemplate` instances instead of recreating them.
+- Renamed variables to improve clarity.
+
+## 1.2.1
+
+- Update tabBar templates in https://github.com/oguzhnatly/flutter_carplay/pull/71
+
+This allow updating a tabBar without removing entire stack. This is useful to add, update or remove tabs.
+
+**Bug fixes :**
+- Ensure that updateSections only recreate necessary entries.
+- Ensure that updateSections take and memorise new entries (by using List.from).
+
+## 1.2.0
+
+- Add early support for Android Auto under a new controller `FlutterAndroidAuto`. Not all features are supported yet, see the README for more details. ([#71](https://github.com/oguzhnatly/flutter_carplay/pull/71)) (ty @EArminjon).
+- History have been reworked to ensure that all templates are well ordered, presents and synchronized.
+- Rename some classes to avoid confusion between Android Auto and CarPlay (breaking change)
+ - `CPConnectionStatusTypes` -> `ConnectionStatusTypes`
+ - `CPEnumUtils` -> `EnumUtils`
+
+## 1.1.3
+
+- Documentation and packaging improvements
+- Automated publishing setup with GitHub Actions
+
+## 1.1.1
+
+- Add automated publishing support to pub.dev
+
+## 1.1.0
+
+- Add showNowPlaying, it can be called multiple times safely ([#33](https://github.com/oguzhnatly/flutter_carplay/issues/33)) (ty @vanlooverenkoen, @EArminjon)
+- Add support for HTTP(s) images (ty @vanlooverenkoen)
+- Add support to launch CarPlay without manually launch the iOS app ([#25](https://github.com/oguzhnatly/flutter_carplay/pull/25)) (ty @vanlooverenkoen)
+- Update the iOS integration and its doc to fix various issues ([#17](https://github.com/oguzhnatly/flutter_carplay/issues/17), [#35](https://github.com/oguzhnatly/flutter_carplay/issues/35), [#38](https://github.com/oguzhnatly/flutter_carplay/issues/38), [#61](https://github.com/oguzhnatly/flutter_carplay/issues/61), [#67](https://github.com/oguzhnatly/flutter_carplay/issues/67)) (ty @EArminjon, @snipd-mikel)
+
+## 1.0.3
+
+- Build fix for the issue [#7](https://github.com/oguzhnatly/flutter_carplay/issues/7)
+
+## 1.0.2+1
+
+- Point Of Interest and Information Template added. Previews added to README.md.
+
+## 1.0.2
+
+- Point Of Interest and Information Template added.
+
+## 1.0.1
+
+- CarPlay List Template issue #4 fixed.
+
+## 1.0.0+1
+
+- Initial release of Flutter Apple CarPlay Package. Previews added to README.md.
+
+## 1.0.0
+
+- Initial release of Flutter Apple CarPlay Package.
diff --git a/packages/flutter_carplay/CONTRIBUTING.md b/packages/flutter_carplay/CONTRIBUTING.md
new file mode 100644
index 00000000..257b075a
--- /dev/null
+++ b/packages/flutter_carplay/CONTRIBUTING.md
@@ -0,0 +1,6 @@
+## Contributing
+
+- Pull Requests are always welcome.
+- Pull Request Reviews are even more welcome! I need help in testing.
+- If you are interested in contributing more actively, please contact me at [email protected] Thanks!
+- If you want to help in coding, join [Discord Server](https://discord.gg/Xz6WVezFfh), so we can chat over there.
diff --git a/packages/flutter_carplay/LICENSE b/packages/flutter_carplay/LICENSE
new file mode 100644
index 00000000..1ae99106
--- /dev/null
+++ b/packages/flutter_carplay/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2021 Oğuzhan Atalay
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
diff --git a/packages/flutter_carplay/README.md b/packages/flutter_carplay/README.md
new file mode 100644
index 00000000..c1ecc9a6
--- /dev/null
+++ b/packages/flutter_carplay/README.md
@@ -0,0 +1,903 @@
+![Flutter CarPlay](https://raw.githubusercontent.com/oguzhnatly/flutter_carplay/master/previews/banner.png)
+
+# CarPlay and Android Auto with Flutter 🚗
+
+[![License: MIT](https://img.shields.io/badge/License-MIT-orange.svg)](https://opensource.org/licenses/MIT)
+![Pub Version (including pre-releases)](https://img.shields.io/pub/v/flutter_carplay?include_prereleases)
+![Dart Pub Likes](https://badgen.net/pub/likes/flutter_carplay)
+![Dart Pub Multi-Platform](https://badgen.net/pub/flutter-platform/flutter_carplay)
+![DartPub Dart SDK](https://badgen.net/pub/sdk-version/flutter_carplay)
+
+Flutter Apps now on Apple CarPlay and Android Auto ! `flutter_carplay` aims to make it safe to use apps made with Flutter in the car by integrating with CarPlay and Android Auto. The package takes the things you want to do while driving and puts them on the car's built-in display.
+
+**✨ New in v1.2.0**: Android Auto support with limited list of feature. First step to future improvements.
+
+**✨ New in v1.1.0**: CarPlay apps can now launch automatically without requiring the Flutter app to be opened first, supporting true background launch capabilities.
+
+> Apple announced some great features in iOS 14, one of which is users download CarPlay apps from the App Store and use them on iPhone like any other app. When an iPhone with a CarPlay app is connected to a CarPlay vehicle, the app icon appears on the CarPlay home screen. CarPlay apps are not separate apps—you add CarPlay support to an existing app.
+>
+> Your app uses the CarPlay framework to present UI elements to the user. iOS manages the display of UI elements and handles the interface with the car. Your app does not need to manage the layout of UI elements for different screen resolutions, or support different input hardware such as touchscreens, knobs, or touch pads.
+
+It supports **only iOS 14.0+**. For general design guidance, see [Human Interface Guidelines for CarPlay Apps](https://developer.apple.com/design/human-interface-guidelines/carplay/overview/introduction/).
+
+## 📚 Documentation
+
+For detailed guides and examples, check out the **[Wiki](https://github.com/oguzhnatly/flutter_carplay/wiki)**:
+
+- [Getting Started](https://github.com/oguzhnatly/flutter_carplay/wiki/Getting-Started) — Installation and basic setup
+- [iOS Setup](https://github.com/oguzhnatly/flutter_carplay/wiki/iOS-Setup) — CarPlay entitlements and configuration
+- [Android Auto Setup](https://github.com/oguzhnatly/flutter_carplay/wiki/Android-Auto-Setup) — Android Auto configuration
+- [Templates](https://github.com/oguzhnatly/flutter_carplay/wiki/Templates) — All templates with code examples
+- [Troubleshooting](https://github.com/oguzhnatly/flutter_carplay/wiki/Troubleshooting) — Common issues and solutions
+- [FAQ](https://github.com/oguzhnatly/flutter_carplay/wiki/FAQ) — Frequently asked questions
+
+# Summary
+
+- [Overview](#overview)
+- [Templates](#templates)
+- [Supports](#supports)
+- [What's New in latest versions](#whats-new-in-latest-versions)
+- [Road Map](#road-map)
+- [Contributing](#contributing)
+- [Requesting the CarPlay Entitlements](#requesting-the-carplay-entitlements)
+- [Disclaimer Before The Installation](#disclaimer-before-the-installation)
+- [Get Started](#get-started)
+- [Solve problems configuring your project](#solve-problems-configuring-your-project)
+- [Usage & Features](#usage--features)
+- [Templates](#templates-1)
+- [LICENSE](#license)
+
+# Overview
+
+![Flutter CarPlay Introduction](https://user-images.githubusercontent.com/54781138/131184549-3cb62678-ad3f-4d67-85fb-1410bd05eaff.gif)
+
+Before you begin CarPlay integration, you must carefully read this section.
+
+[_The official App Programming Guidelines from Apple_](https://developer.apple.com/carplay/documentation/CarPlay-App-Programming-Guide.pdf) is the most valuable resource for understanding the needs, limits, and capabilities of CarPlay Apps. This documentation is a 49-page which clearly spells out the some actions required, and you are strongly advised to read it. If you are interested in a CarPlay System, [learn more about the MFi Program](https://mfi.apple.com/).
+
+# Templates
+
+## Car Play Templates
+
+CarPlay apps are built from a fixed set of user interface templates that iOS renders on the CarPlay screen. Each CarPlay app category can only use a restricted number of templates. Your app entitlement determines your access to templates.
+
+![Flutter CarPlay](https://raw.githubusercontent.com/oguzhnatly/flutter_carplay/master/previews/templates.png)
+
+## Android Auto Templates
+
+Android Auto apps built with the Android for Cars App Library are constructed using a fixed set of vehicle-optimized templates that the host renders on the car screen. Each Android Auto app category (e.g., Navigation, Point-of-Interest, IoT, etc.) can only use a restricted number of templates, and access to the Android for Cars App Library and its templates is generally restricted to supported app categories.
+
+https://developer.android.com/design/ui/cars/guides/templates/overview
+
+# Supports
+
+## Car Play Support
+
+`flutter_carplay` currently supports:
+
+- [x] Action Sheet Template
+- [x] Alert Template
+- [x] Grid Template
+- [x] List Template
+- [x] Tab Bar Template
+- [x] Information Template (contribution from [OSch11](https://github.com/OSch11/flutter_carplay))
+- [x] Point of Interest Template (contribution from [OSch11](https://github.com/OSch11/flutter_carplay))
+- [x] Now Playing Template (v1.1.0)
+
+By evaluating this information, you can request for the relevant entitlement from Apple.
+
+## Android Auto Support
+
+- [x] List Template (limited support)
+- [x] Now Playing Template (Automatically handled by Android Auto system)
+
+# What's New in latest versions
+
+## v1.2.0
+
+- **🤖 Android Auto Support**: Initial support for Android Auto with limited
+ features (Thanks to [@EArminjon](https://github.com/EArminjon))
+
+## v1.1.0
+
+- **🚀 Background Launch Support**: CarPlay apps can now start automatically without requiring the Flutter app to be opened first (Thanks to [@vanlooverenkoen](https://github.com/vanlooverenkoen) and [@EArminjon](https://github.com/EArminjon))
+- **🎵 Now Playing Template**: Navigate to the shared instance of the Now Playing Template with `FlutterCarplay.showSharedNowPlaying()`
+- **🌐 Flexible Image Sources**: Load images from assets, local files (`file://`), or URLs (`https://`) (Thanks to [@vanlooverenkoen](https://github.com/vanlooverenkoen))
+- **🔧 Improved Completion Handlers**: Better reliability for list item interactions and template transitions
+- **📱 Flutter 3.32.x Compatibility**: Updated for the latest Flutter versions
+
+Special thanks to [@EArminjon](https://github.com/EArminjon), [@vanlooverenkoen](https://github.com/vanlooverenkoen), [@snipd-mikel](https://github.com/snipd-mikel), [@APIUM](https://github.com/APIUM), and all contributors who made this release possible!
+
+# Road Map
+
+Other templates will be supported in the future releases by `flutter_carplay`.
+
+## Car Play Road Map
+
+- [ ] Map Template
+- [ ] Search Template
+- [ ] Voice Control & "Hey Siri" for hands-free voice activation
+- [ ] Contact Template
+
+## Android Auto Road Map
+- [ ] Grid Template
+- [ ] Alert Template
+- [ ] Action Sheet Template
+- [ ] Information Template
+- [ ] Point of Interest Template
+- [ ] Map Template
+- [ ] Search Template
+- [ ] Voice Control & "Hey Google" for hands-free voice activation
+- [ ] Contact Template
+
+# Contributing
+
+- Pull Requests are always welcome.
+- Pull Request Reviews are even more welcome! I need help in testing.
+- If you are interested in contributing more actively, please contact me at [email protected] Thanks!
+- If you want to help in coding, join [Discord Server](https://discord.gg/Xz6WVezFfh), so we can chat over there.
+
+# Requesting the CarPlay Entitlements
+
+> All CarPlay apps require a CarPlay app entitlement.
+
+If you want to build, run and publish your app on Apple with CarPlay compatibility or test or share the app with others through the TestfFlight or AdHoc, you must first request Apple to approve your Developer account for CarPlay access. The process can take from a few days to weeks or even months. It depends on the type of Entitlement you are requesting.
+
+To request a CarPlay app entitlement from Apple, go to https://developer.apple.com/contact/carplay and provide information about your app, including the CarPlay App Category. You must also agree to the CarPlay Entitlement Addendum.
+
+With this project, you can start developing and testing through Apple's CarPlay Simulator without waiting for CarPlay Entitlements. Apple will review your request. If your app meets the criteria for a CarPlay app, Apple will assign a CarPlay app entitlement to your Apple Developer Account and will notify you.
+
+Whether you are running the app through a simulator or developing it for distribution, you must ensure that the relevant entitlement key is added to the `Entitlements.plist` file. You must create an Entitlements.plist file if you do not already have one.
+
+## After you receive the CarPlay Entitlement
+
+After you receive the entitlement, you need to configure your Xcode project to use it, which involves several steps. You create and import a provisioning profile, and add an `Entitlements.plist` file. Your project’s code signing settings also require minor changes.
+
+For more detailed instructions about how to create and import the CarPlay Provisioning Profile and add an Entitlements File to Xcode Project, go to [Configure your CarPlay-enabled app with the entitlements it requires.](https://developer.apple.com/documentation/carplay/requesting_the_carplay_entitlements)
+
+# Disclaimer Before The Installation
+
+You are about to make some minor changes to your Xcode project after installing this package. This is due to the fact that It requires bitcode compilation which is missing in Flutter. You will procedure that will relocate (we won't remove or edit) some Flutter and its package engines. If you're planning to add this package to a critical project for you, you should proceed cautiously.
+
+**Please check [THE EXAMPLE PROJECT](https://github.com/oguzhnatly/flutter_carplay/tree/master/example) before you begin to the installation.**
+
+THE INSTALLATION STEPS MAY BE DIFFICULT OR MAY NOT WORK PROPERLY WITH A FEW PACKAGES IN YOUR CURRENT PROJECT THAT COMMUNICATE WITH THE FLUTTER ENGINE. IF YOU ARE NOT COMPLETELY SURE WHAT YOU ARE DOING, PLEASE CREATE AN ISSUE, SO THAT I CAN HELP YOU TO SOLVE YOUR PROBLEM OR EXPLAIN WHAT YOU NEED TO.
+
+WHILE THE INSTALLATION PROGRESS, IF YOU TRY TO CHANGE ANYTHING (E.G. ANYTHING WORKS WITH FLUTTER ENGINE, ANYTHING IN GENERATED PLUGIN REGISTRANT SPECIFICALLY ITS LOCATION, ANY FILE NAME, ANY CLASS NAME, OR ANY OTHER FUNCTION THAT WORKS ON APPDELEGATE CLASS, TEMPLATE OR WINDOW APPLICATION DELEGATE SCENE NAMES USED IN INFO.PLIST, INCLUDED STORYBOARD NAMES, BUT NOT LIMITED TO THESE), YOU ARE MOST LIKELY TO ENCOUNTER IRREVERSIBLE ERRORS AND IT MAY DAMAGE TO YOUR PROJECT. I STRONGLY RECOMMEND THAT YOU SHOULD COPY YOUR EXISTING PROJECT BEFORE THE INSTALLATION.
+
+# Get Started
+
+## Car Play Get Started
+
+### Requirement Actions after Installation of the Package
+
+1. The iOS platform version must be set to 14.0. To make it global, navigate to `ios/Podfile` and copy the first two lines:
+
+```diff
+# Uncomment this line to define a global platform for your project
++ platform :ios, '14.0'
+- # platform :ios, '9.0'
+```
+
+After changing the platform version, execute the following command in your terminal to update your pod files:
+
+```shell
+// For Apple Silicon M1 chips:
+$ cd ios && arch -x86_64 pod install --repo-update
+
+// For Intel chips:
+$ cd ios && pod install --repo-update
+```
+
+2. Open `ios/Runner.xcworkspace` in Xcode. In your project navigator, open `AppDelegate.swift`.
+
+ ![Flutter CarPlay](https://raw.githubusercontent.com/oguzhnatly/flutter_carplay/master/previews/step2.png)
+
+ Delete the specified codes below from the application function in `AppDelegate.swift`, and change it with the code below:
+
+```diff
+import UIKit
+import Flutter
+
+let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadlessExecution: true)
+
+@UIApplicationMain
+@objc class AppDelegate: FlutterAppDelegate {
+ override func application( _ application: UIApplication,
+ didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
++ flutterEngine.run()
++ GeneratedPluginRegistrant.register(with: flutterEngine)
+ return super.application(application, didFinishLaunchingWithOptions: launchOptions)
+ }
+}
+```
+
+3. Create a swift file named `SceneDelegate.swift` in the Runner folder (not in the xcode main project file) and add the code below:
+
+ ```swift
+ @available(iOS 13.0, *)
+ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
+ var window: UIWindow?
+
+ func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
+ guard let windowScene = scene as? UIWindowScene else { return }
+
+ window = UIWindow(windowScene: windowScene)
+
+ let controller = FlutterViewController.init(engine: flutterEngine, nibName: nil, bundle: nil)
+ controller.loadDefaultSplashScreenView()
+ window?.rootViewController = controller
+ window?.makeKeyAndVisible()
+ }
+ }
+ ```
+
+ ![Flutter CarPlay](https://raw.githubusercontent.com/oguzhnatly/flutter_carplay/master/previews/step3.png)
+
+4. One more step, open the `Info.plist` file whether in your favorite code editor or in the Xcode. I'm going to share the base code, so if you open in the Xcode, you can fill with the raw keys with the values.
+
+ ```xml
+ <key>UIApplicationSceneManifest</key>
+ <dict>
+ <key>UIApplicationSupportsMultipleScenes</key>
+ <false />
+ <key>UISceneConfigurations</key>
+ <dict>
+ <key>CPTemplateApplicationSceneSessionRoleApplication</key>
+ <array>
+ <dict>
+ <key>UISceneConfigurationName</key>
+ <string>CarPlay Configuration</string>
+ <key>UISceneDelegateClassName</key>
+ <string>flutter_carplay.FlutterCarPlaySceneDelegate</string>
+ </dict>
+ </array>
+ <key>UIWindowSceneSessionRoleApplication</key>
+ <array>
+ <dict>
+ <key>UISceneConfigurationName</key>
+ <string>Default Configuration</string>
+ <key>UISceneDelegateClassName</key>
+ <string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
+ <key>UISceneStoryboardFile</key>
+ <string>Main</string>
+ </dict>
+ </array>
+ </dict>
+ </dict>
+ ```
+
+### That's it, you're ready to build your first CarPlay app! 🚀 😎
+
+## Android Auto Get Started
+
+### Requirement Actions after Installation of the Package
+
+1. The Android platform version must be set to 21. Update your `android/app/build.gradle.kts` as below:
+
+```diff
+# Update to use at minimum api 21
++ minSdk = 21
+- minSdk = 19
+```
+
+2. To setup Android Auto, you need to add a metadata tag in your `AndroidManifest.xml` file. Open `android/app/src/main/AndroidManifest.xml` and add the following :
+
+
+Inside the `<manifest>` tag:
+
+```xml
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+ <uses-feature
+ android:name="android.software.car.app.library"
+ android:required="false" />
+ <uses-permission android:name="androidx.car.app.MEDIA_TEMPLATES"/>
+
+</manifest>
+```
+
+Inside the `<application>` tag:
+
+```xml
+<application>
+
+ <meta-data
+ android:name="com.google.android.gms.car.application"
+ android:resource="@xml/automotive_app_desc" />
+ <meta-data
+ android:name="androidx.car.app.minCarApiLevel"
+ android:value="1" />
+ <service
+ android:name="com.oguzhnatly.flutter_android_auto.AndroidAutoService"
+ android:exported="true">
+
+ <intent-filter>
+ <action android:name="androidx.car.app.CarAppService" />
+ <category android:name="androidx.car.app.category.MEDIA"/>
+ </intent-filter>
+ </service>
+
+</application>
+```
+
+3. Create a new directory named `xml` inside `android/app/src/main/res/` if it doesn't already exist. Then, create a new XML file named `automotive_app_desc.xml` in the `res/xml/` directory and add the following content:
+
+```xml
+<?xml version="1.0" encoding="utf-8"?>
+<automotiveApp xmlns:android="http://schemas.android.com/apk/res/android">
+
+ <uses name="template" />
+ <uses name="media" />
+
+</automotiveApp>
+```
+
+For others use, please check official [Android Auto documentation](https://developer.android.com/training/cars/apps/auto).
+
+4. In your `MainActivity.kt` file, make the necessary to resuse and cache the engine as follow :
+
+On Android Auto Service, use the same engine as the app if the app is already running, otherwise create a new one and cache using the id `FAAConstants.flutterEngineId`.
+To avoid creating multiple engines, you need to override the `provideFlutterEngine` and `configureFlutterEngine` methods as below :
+
+```kotlin
+package com.example.flutter_carplay_example
+
+import android.content.Context
+import io.flutter.embedding.android.FlutterActivity
+import io.flutter.embedding.engine.FlutterEngine
+import io.flutter.embedding.engine.FlutterEngineCache
+import io.flutter.embedding.engine.dart.DartExecutor
+import com.oguzhnatly.flutter_android_auto.FAAConstants
+
+class MainActivity : FlutterActivity() {
+ override fun provideFlutterEngine(context: Context): FlutterEngine? {
+ // Use engine from cache if it has been started by Android Auto.
+ return FlutterEngineCache.getInstance().get(FAAConstants.flutterEngineId);
+ }
+
+ override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
+ // Cache the engine to make it usable by Android Auto.
+ FlutterEngineCache.getInstance().put(FAAConstants.flutterEngineId, flutterEngine)
+ super.configureFlutterEngine(flutterEngine)
+ }
+}
+```
+
+## Solve problems configuring your project
+
+Take a look at [this detailed issue reply](https://github.com/oguzhnatly/flutter_carplay/issues/3#issuecomment-926146126) if you got any error.
+
+## Usage & Features
+
+To see a complete example for both CarPlay and Android Auto, check the example project.
+
+[**See Full Example**](https://github.com/oguzhnatly/flutter_carplay/blob/master/example/lib/main.dart)
+
+### Basic Usage for Car Play
+
+- Import the all classes that you need from just one file:
+
+```dart
+import 'package:flutter_carplay/flutter_carplay.dart';
+```
+
+- Initialize the CarPlay Controllers, set a root template for the CarPlay view hierarchy and ensure to well update the root template :
+
+```dart
+final FlutterCarplay _flutterCarplay = FlutterCarplay();
+
+await FlutterCarplay.setRootTemplate(
+ rootTemplate: CPTabBarTemplate(
+ templates: [
+ CPListTemplate(
+ sections: [
+ CPListSection(
+ items: [
+ CPListItem(
+ text: "Item 1",
+ detailText: "Detail Text",
+ onPress: (complete, self) {
+ self.setDetailText("You can change the detail text.. 🚀");
+ Future.delayed(const Duration(seconds: 1), () {
+ self.setDetailText("Customizable Detail Text");
+ complete();
+ });
+ },
+ ),
+ ],
+ header: "First Section",
+ ),
+ ],
+ title: "Home",
+ showsTabBadge: false,
+ systemIcon: "house.fill",
+ ),
+ ],
+ ),
+ animated: true,
+);
+_flutterCarplay.forceUpdateRootTemplate();
+```
+
+> You can set a root template without initializing the CarPlay Controllers, but some callback functions may not work or most likely you will get an error.
+
+> It's recommended that you should set the root template in the first initState of your app.
+
+### Listen Connection Changes
+
+You can detect connection changes, such as when CarPlay is connected to iPhone, is in the background, or is completely disconnected.
+
+```dart
+/// Add the listener
+_flutterCarplay.addListenerOnConnectionChange(onCarplayConnectionChange);
+
+void onCarplayConnectionChange(ConnectionStatusTypes status) {
+ // Do things when carplay connection status is:
+ // - ConnectionStatusTypes.connected
+ // - ConnectionStatusTypes.background
+ // - ConnectionStatusTypes.disconnected
+ // - ConnectionStatusTypes.unknown
+}
+
+/// Remove the listener
+_flutterCarplay.removeListenerOnConnectionChange();
+```
+
+### CarPlay API Methods
+
+#### **CarPlay.setRootTemplate**
+
+Sets the root template of the navigation hierarchy. If a navigation
+hierarchy already exists, CarPlay replaces the entire hierarchy.
+
+- rootTemplate is a template to use as the root of a new navigation hierarchy. If one exists,
+ it will replace the current rootTemplate. **Must be one of the type:**
+ **CPTabBarTemplate**, **CPGridTemplate**, **CPListTemplate**. If not, it will throw an **TypeError**.
+- If animated is true, CarPlay animates the presentation of the template, but will be ignored
+ this flag when there isn’t an existing navigation hierarchy to replace.
+
+> CarPlay cannot have more than 5 templates on one screen.
+
+```dart
+FlutterCarplay.setRootTemplate(
+ rootTemplate: /* CPTabBarTemplate, CPGridTemplate or CPListTemplate */,
+ animated: true,
+);
+// You need to call _flutterCarplay.forceUpdateRootTemplate(); after setting the root template
+```
+
+#### **CarPlay.push**
+
+Adds a template to the navigation hierarchy and displays it.
+
+- template is to add to the navigation hierarchy. **Must be one of the type:** **CPGridTemplate**, **CPListTemplate**. If not, it will throw an **TypeError**.
+- If animated is true, CarPlay animates the transition between templates.
+
+> There is a limit to the number of templates that you can push onto the screen. All apps are limited to pushing up to 5 templates in depth, including the root template.
+
+```dart
+FlutterCarplay.push(
+ template: /* CPGridTemplate or CPListTemplate */,
+ animated: true,
+);
+```
+
+#### **CarPlay.pop**
+
+Removes the top-most template from the navigation hierarchy.
+
+- If animated is true, CarPlay animates the transition between templates.
+- count represents how many times this function will occur.
+
+```dart
+FlutterCarplay.pop();
+// OR
+FlutterCarplay.pop(animated: true, count: 1);
+```
+
+#### **CarPlay.popToRoot**
+
+Removes all of the templates from the navigation hierarchy except the root template.
+
+- If animated is true, CarPlay animates the presentation of the template.
+
+```dart
+FlutterCarplay.popToRoot(animated: true);
+```
+
+#### **CarPlay.popModal**
+
+Removes a modal template. Since **CPAlertTemplate** and **CPActionSheetTemplate** are both modals, they can be removed.
+
+- If animated is true, CarPlay animates the transition between templates.
+
+```dart
+FlutterCarplay.popModal(animated: true);
+```
+
+#### **CarPlay.showSharedNowPlaying**
+
+Navigate to the shared instance of the Now Playing Template. This allows users to control media playback directly from CarPlay.
+
+- If animated is true, CarPlay animates the transition to the Now Playing template.
+
+```dart
+FlutterCarplay.showSharedNowPlaying(animated: true);
+```
+
+#### **CarPlay.connectionStatus**
+
+Getter for current CarPlay connection status. It will return one of **ConnectionStatusTypes** as String.
+
+```dart
+FlutterCarplay.connectionStatus
+```
+
+## Templates
+
+CarPlay supports general purpose templates such as alerts, lists, and tab bars. They are used to display contents on the CarPlay screen from the app. [The Developer Guide](https://developer.apple.com/carplay/documentation/CarPlay-App-Programming-Guide.pdf) contains more information on the templates that Apple supports.
+
+> If you attempt to use a template not supported by your entitlement, an exception will occur at runtime.
+
+### Tab Bar Template
+
+![Flutter CarPlay](https://raw.githubusercontent.com/oguzhnatly/flutter_carplay/master/previews/tabbar_template.png)
+
+The tab bar is a multi-purpose container for other templates, with each template occupying one tab in the tab bar.
+
+```dart
+final CPTabBarTemplate tabBarTemplate = CPTabBarTemplate(
+ templates: [
+ CPListTemplate(
+ sections: [
+ CPListSection(
+ items: [
+ CPListItem(
+ text: "Item 1",
+ detailText: "Detail Text",
+ onPress: (complete, self) {
+ // Returns the self class so that the item
+ // can be updated within self while loading
+ self.setDetailText("You can change the detail text.. 🚀");
+ // complete function stops the loading
+ complete();
+ },
+ // Supports three image formats (v1.1.0+):
+ // - Asset: 'images/logo_flutter_1080px_clr.png'
+ // - File: 'file:///path/to/local/image.png'
+ // - URL: 'https://example.com/image.png'
+ image: 'images/logo_flutter_1080px_clr.png',
+ ),
+ CPListItem(
+ text: "Item 2",
+ detailText: "Start progress bar",
+ isPlaying: false,
+ playbackProgress: 0,
+ // asset name defined in pubspec.yaml
+ image: 'images/logo_flutter_1080px_clr.png',
+ onPress: (complete, self) {
+ complete();
+ },
+ ),
+ ],
+ header: "First Section",
+ ),
+ ],
+ title: "Home",
+ showsTabBadge: false,
+ systemIcon: "house.fill",
+ ),
+ CPListTemplate(
+ sections: [],
+ title: "Settings",
+ // If there is no section in the list template,
+ // empty view title and subtitle variants will be shown
+ emptyViewTitleVariants: ["Settings"],
+ emptyViewSubtitleVariants: [
+ "No settings have been added here yet. You can start adding right away"
+ ],
+ showsTabBadge: false,
+ systemIcon: "gear",
+ ),
+ ],
+);
+
+FlutterCarplay.setRootTemplate(rootTemplate: tabBarTemplate, animated: true);
+```
+
+### Grid Template
+
+![Flutter CarPlay](https://raw.githubusercontent.com/oguzhnatly/flutter_carplay/master/previews/grid_template.png)
+
+Grid Template is a specific style of menu that presents up to 8 items represented by an image and a title. Use the grid template to let people select from a fixed list of categories.
+
+```dart
+final CPGridTemplate gridTemplate = CPGridTemplate(
+ title: "Grid Template",
+ buttons: [
+ for (var i = 1; i < 9; i++)
+ CPGridButton(
+ titleVariants: ["Item $i"],
+ image: 'images/logo_flutter_1080px_clr.png',
+ onPress: () {
+ print("Grid Button $i pressed");
+ },
+ ),
+ ],
+);
+
+FlutterCarplay.push(template: gridTemplate, animated: true);
+// OR
+FlutterCarplay.setRootTemplate(rootTemplate: gridTemplate, animated: true);
+// You need to call _flutterCarplay.forceUpdateRootTemplate(); after setting the root template
+```
+
+### Alert Template
+
+![Flutter CarPlay](https://raw.githubusercontent.com/oguzhnatly/flutter_carplay/master/previews/alert_template.png)
+
+Alerts provide important information about your app's status. An alert consists of a title and one or more buttons, depending on the type.
+
+> If underlying conditions permit, alerts can be dismissed programatically.
+
+```dart
+final CPAlertTemplate alertTemplate = CPAlertTemplate(
+ titleVariants: ["Alert Title"],
+ actions: [
+ CPAlertAction(
+ title: "Okay",
+ style: CPAlertActionStyles.normal,
+ onPress: () {
+ print("Okay pressed");
+ FlutterCarplay.popModal(animated: true);
+ },
+ ),
+ CPAlertAction(
+ title: "Cancel",
+ style: CPAlertActionStyles.cancel,
+ onPress: () {
+ print("Cancel pressed");
+ FlutterCarplay.popModal(animated: true);
+ },
+ ),
+ CPAlertAction(
+ title: "Remove",
+ style: CPAlertActionStyles.destructive,
+ onPress: () {
+ print("Remove pressed");
+ FlutterCarplay.popModal(animated: true);
+ },
+ ),
+ ],
+),
+
+FlutterCarplay.showAlert(template: alertTemplate, animated: true);
+```
+
+### Action Sheet Template
+
+![Flutter CarPlay](https://raw.githubusercontent.com/oguzhnatly/flutter_carplay/master/previews/actionsheet_template.png)
+
+Action Sheet Template is a type of alert that appears when control or action is taken and gives a collection of options based on the current context.
+
+> Use action sheets to let people initiate tasks, or to request confirmation before performing a potentially destructive operation.
+
+```dart
+final CPActionSheetTemplate actionSheetTemplate = CPActionSheetTemplate(
+ title: "Action Sheet Template",
+ message: "This is an example message.",
+ actions: [
+ CPAlertAction(
+ title: "Cancel",
+ style: CPAlertActionStyles.cancel,
+ onPress: () {
+ print("Cancel pressed in action sheet");
+ FlutterCarplay.popModal(animated: true);
+ },
+ ),
+ CPAlertAction(
+ title: "Dismiss",
+ style: CPAlertActionStyles.destructive,
+ onPress: () {
+ print("Dismiss pressed in action sheet");
+ FlutterCarplay.popModal(animated: true);
+ },
+ ),
+ CPAlertAction(
+ title: "Ok",
+ style: CPAlertActionStyles.normal,
+ onPress: () {
+ print("Ok pressed in action sheet");
+ FlutterCarplay.popModal(animated: true);
+ },
+ ),
+ ],
+);
+
+FlutterCarplay.showActionSheet(template: actionSheetTemplate, animated: true);
+```
+
+### List Template
+
+![Flutter CarPlay](https://raw.githubusercontent.com/oguzhnatly/flutter_carplay/master/previews/list_template.png)
+
+A list presents data as a scrolling, single-column table of rows that can be divided into sections. Lists are ideal for text-based content, and can be used as a means of navigation for hierarchical information. Each item in a list can include attributes such as an icon, title, subtitle, disclosure indicator, progress indicator, playback status, or read status.
+
+> Some cars dynamically limit lists to a maximum of 12 items. You always need to be prepared to handle the case where only 12 items can be shown. Items beyond the maximum will not be shown.
+
+```dart
+final CPListTemplate listTemplate = CPListTemplate(
+ sections: [
+ CPListSection(
+ items: [
+ CPListItem(
+ text: "Item 1",
+ detailText: "Detail Text",
+ onPress: (complete, self) {
+ // Returns the self class so that the item
+ // can be updated within self while loading
+ self.setDetailText("You can change the detail text.. 🚀");
+ // complete function stops the loading
+ complete();
+ },
+ image: 'images/logo_flutter_1080px_clr.png',
+ ),
+ CPListItem(
+ text: "Item 2",
+ detailText: "Start progress bar",
+ isPlaying: false,
+ playbackProgress: 0,
+ // asset name defined in pubspec.yaml
+ image: 'images/logo_flutter_1080px_clr.png',
+ onPress: (complete, self) {
+ complete();
+ },
+ ),
+ ],
+ header: "First Section",
+ ),
+ ],
+ title: "Home",
+ showsTabBadge: false,
+ systemIcon: "house.fill",
+ // If there is no section in the list template,
+ // empty view title and subtitle variants will be shown
+ emptyViewTitleVariants: ["Home"],
+ emptyViewSubtitleVariants: [
+ "Nothing has added here yet. You can start adding right away"
+ ],
+);
+
+FlutterCarplay.push(template: listTemplate, animated: true);
+// OR
+FlutterCarplay.setRootTemplate(rootTemplate: listTemplate, animated: true);
+// You need to call _flutterCarplay.forceUpdateRootTemplate(); after setting the root template
+```
+
+### Information Template
+
+![Flutter CarPlay](https://raw.githubusercontent.com/oguzhnatly/flutter_carplay/master/previews/information_template.png)
+
+An Information Template shows a list of items, and actions (max. three)) as array of text buttons.
+
+> The list is limited to 10 items. Items beyond the maximum will not be shown. Up to three actions are supported.
+
+```dart
+final CPInformationTemplate informationTemplate = CPInformationTemplate(
+ title: "Title",
+ layout: CPInformationTemplateLayout.twoColumn,
+ actions: [
+ CPTextButton(
+ title: "Button Title 1",
+ onPress: () {
+ print("Button 1");
+ }
+ ),
+ CPTextButton(
+ title: "Button Title 2",
+ onPress: () {
+ print("Button 2");
+ }
+ ),
+ ],
+ informationItems: [
+ CPInformationItem(title: "Title", detail: "Detail"),
+ ]
+);
+
+FlutterCarplay.push(template: informationTemplate, animated: true);
+// OR
+FlutterCarplay.setRootTemplate(rootTemplate: informationTemplate, animated: true);
+// You need to call _flutterCarplay.forceUpdateRootTemplate(); after setting the root template
+```
+
+### Point Of Interest Template
+
+![Flutter CarPlay](https://raw.githubusercontent.com/oguzhnatly/flutter_carplay/master/previews/point_of_interest_template.png)
+
+A Point Of Interest template shows multiple points of interest on a Map
+The map section is determined by the points of interest.
+
+> The Template is limited to 12 Points of Interest.
+
+```dart
+ final CPPointOfInterestTemplate pointOfInterestTemplate =
+ CPPointOfInterestTemplate(title: "Title", poi: [
+ CPPointOfInterest(
+ latitude: 51.5052,
+ longitude: 7.4938,
+ title: "Title",
+ subtitle: "Subtitle",
+ summary: "Summary",
+ detailTitle: "DetailTitle",
+ detailSubtitle: "detailSubtitle",
+ detailSummary: "detailSummary",
+ image: "images/logo_flutter_1080px_clr.png",
+ primaryButton: CPTextButton(
+ title: "Primary",
+ onPress: () {
+ print("Primary button pressed");
+ }
+ ),
+ secondaryButton: CPTextButton(
+ title: "Secondary",
+ onPress: () {
+ print("Secondary button pressed");
+ }))
+ ]);
+
+ FlutterCarplay.push(template: pointOfInterestTemplate, animated: true);
+ // OR
+ FlutterCarplay.setRootTemplate(rootTemplate: pointOfInterestTemplate, animated: true);
+ // You need to call _flutterCarplay.forceUpdateRootTemplate(); after setting the root template
+```
+
+### Now Playing Template
+
+The Now Playing template provides a standardized interface for media playback controls in CarPlay. It uses the system's shared instance and integrates with your app's media session.
+
+```dart
+// Navigate to the Now Playing template
+FlutterCarplay.showSharedNowPlaying(animated: true);
+```
+
+> **Note**: The Now Playing template displays information from your app's active media session. Make sure your app is properly configured with AVAudioSession and media playback controls for the best experience.
+
+> **Multiple Calls Safe**: The `showSharedNowPlaying()` method can be called multiple times safely without causing issues.
+
+# Support
+
+If this package has been helpful, consider supporting its development:
+
+[![Sponsor on GitHub](https://img.shields.io/badge/Sponsor-GitHub-ea4aaa?logo=github)](https://github.com/sponsors/oguzhnatly)
+
+Your support helps maintain and improve this package! ❤️
+
+# Star History
+
+[![Star History Chart](https://api.star-history.com/svg?repos=oguzhnatly/flutter_carplay&type=Date)](https://star-history.com/#oguzhnatly/flutter_carplay&Date)
+
+# LICENSE
+
+[**MIT License**](https://github.com/oguzhnatly/flutter_carplay/blob/master/LICENSE)
+
+Copyright (c) 2021 Oğuzhan Atalay
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/packages/flutter_carplay/SECURITY.md b/packages/flutter_carplay/SECURITY.md
new file mode 100644
index 00000000..b210f22e
--- /dev/null
+++ b/packages/flutter_carplay/SECURITY.md
@@ -0,0 +1,27 @@
+# Security Policy
+
+## Supported Versions
+
+| Version | Supported |
+| ------- | ------------------ |
+| 1.2.x | :white_check_mark: |
+| 1.1.x | :white_check_mark: |
+| < 1.1 | :x: |
+
+## Reporting a Vulnerability
+
+If you discover a security vulnerability in flutter_carplay, please report it responsibly:
+
+1. **Do not** open a public GitHub issue
+2. Use GitHub's [private vulnerability reporting](https://github.com/oguzhnatly/flutter_carplay/security/advisories/new) to submit your report
+3. Or email: [email protected]
+
+Please include:
+- Description of the vulnerability
+- Steps to reproduce
+- Potential impact
+- Suggested fix (if any)
+
+I will acknowledge receipt within 48 hours and aim to provide a fix within 7 days for critical issues.
+
+Thank you for helping keep flutter_carplay secure!
diff --git a/packages/flutter_carplay/analysis_options.yaml b/packages/flutter_carplay/analysis_options.yaml
new file mode 100644
index 00000000..e0b53705
--- /dev/null
+++ b/packages/flutter_carplay/analysis_options.yaml
@@ -0,0 +1,14 @@
+include: package:flutter_lints/flutter.yaml
+
+# Additional information about this file can be found at
+# https://dart.dev/guides/language/analysis-options
+
+formatter:
+ page_width: 80
+linter:
+ rules:
+ avoid_redundant_argument_values: true
+ prefer_final_locals: true
+ prefer_const_constructors: true
+ avoid_print: true
+ prefer_single_quotes: true
diff --git a/packages/flutter_carplay/android/build.gradle b/packages/flutter_carplay/android/build.gradle
new file mode 100644
index 00000000..938ab2ff
--- /dev/null
+++ b/packages/flutter_carplay/android/build.gradle
@@ -0,0 +1,53 @@
+group = "com.example.flutter_carplay"
+version = "1.0-SNAPSHOT"
+
+buildscript {
+ ext.kotlin_version = "2.1.0"
+ repositories {
+ google()
+ mavenCentral()
+ }
+
+ dependencies {
+ classpath("com.android.tools.build:gradle:8.7.3")
+ classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")
+ }
+}
+
+allprojects {
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+apply plugin: "com.android.library"
+apply plugin: "kotlin-android"
+
+android {
+ namespace = "com.oguzhnatly.flutter_android_auto"
+
+ compileSdk = 35
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_11
+ targetCompatibility = JavaVersion.VERSION_11
+ }
+
+ kotlinOptions {
+ jvmTarget = JavaVersion.VERSION_11
+ }
+
+ sourceSets {
+ main.java.srcDirs += "src/main/kotlin"
+ test.java.srcDirs += "src/test/kotlin"
+ }
+
+ defaultConfig {
+ minSdk = 21
+ }
+
+ dependencies {
+ implementation("androidx.car.app:app:1.7.0")
+ }
+}
diff --git a/packages/flutter_carplay/android/gradle/wrapper/gradle-wrapper.properties b/packages/flutter_carplay/android/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 00000000..b82aa23a
--- /dev/null
+++ b/packages/flutter_carplay/android/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,7 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
+networkTimeout=10000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/packages/flutter_carplay/android/settings.gradle b/packages/flutter_carplay/android/settings.gradle
new file mode 100644
index 00000000..de8e5222
--- /dev/null
+++ b/packages/flutter_carplay/android/settings.gradle
@@ -0,0 +1 @@
+rootProject.name = 'flutter_carplay'
diff --git a/packages/flutter_carplay/android/src/main/AndroidManifest.xml b/packages/flutter_carplay/android/src/main/AndroidManifest.xml
new file mode 100644
index 00000000..3ea6bff5
--- /dev/null
+++ b/packages/flutter_carplay/android/src/main/AndroidManifest.xml
@@ -0,0 +1,3 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.oguzhnatly.flutter_android_auto">
+</manifest>
diff --git a/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/AndroidAutoService.kt b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/AndroidAutoService.kt
new file mode 100644
index 00000000..e030ac6f
--- /dev/null
+++ b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/AndroidAutoService.kt
@@ -0,0 +1,39 @@
+package com.oguzhnatly.flutter_android_auto
+
+import androidx.car.app.CarAppService
+import androidx.car.app.validation.HostValidator
+import androidx.car.app.Session
+import io.flutter.embedding.engine.FlutterEngine
+import io.flutter.embedding.engine.dart.DartExecutor
+import io.flutter.embedding.engine.FlutterEngineCache;
+
+class AndroidAutoService : CarAppService() {
+ companion object {
+ /// The Android Auto session that this service is handling.
+ var session: AndroidAutoSession? = null
+ }
+
+ override fun onCreate() {
+ super.onCreate()
+ val engineCache = FlutterEngineCache.getInstance()
+ val flutterEngineId = FAAConstants.flutterEngineId
+
+ if (engineCache.get(flutterEngineId) != null) return;
+
+ // Create new engine in headless mode
+ val flutterEngine = FlutterEngine(this)
+ flutterEngine.dartExecutor.executeDartEntrypoint(
+ DartExecutor.DartEntrypoint.createDefault()
+ )
+ // Cache the engine
+ engineCache.put(flutterEngineId, flutterEngine)
+ }
+
+
+ override fun createHostValidator() = HostValidator.ALLOW_ALL_HOSTS_VALIDATOR
+
+ override fun onCreateSession(): Session {
+ session = AndroidAutoSession()
+ return session!!
+ }
+}
diff --git a/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/FAAConstants.kt b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/FAAConstants.kt
new file mode 100644
index 00000000..cfa64cef
--- /dev/null
+++ b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/FAAConstants.kt
@@ -0,0 +1,5 @@
+package com.oguzhnatly.flutter_android_auto
+
+object FAAConstants {
+ val flutterEngineId = "android_auto_id"
+}
diff --git a/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/FAAEnums.kt b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/FAAEnums.kt
new file mode 100644
index 00000000..d9814d70
--- /dev/null
+++ b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/FAAEnums.kt
@@ -0,0 +1,19 @@
+package com.oguzhnatly.flutter_android_auto
+
+enum class FAAConnectionTypes {
+ connected,
+ background,
+ disconnected,
+}
+
+enum class FAAChannelTypes {
+ onAndroidAutoConnectionChange,
+ setRootTemplate,
+ forceUpdateRootTemplate,
+ pushTemplate,
+ popTemplate,
+ popToRootTemplate,
+ onListItemSelected,
+ onListItemSelectedComplete,
+ onScreenBackButtonPressed,
+}
diff --git a/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/FAAHelpers.kt b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/FAAHelpers.kt
new file mode 100644
index 00000000..03b92e57
--- /dev/null
+++ b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/FAAHelpers.kt
@@ -0,0 +1,36 @@
+package com.oguzhnatly.flutter_android_auto
+
+import android.content.Context
+import android.graphics.BitmapFactory
+import androidx.car.app.model.CarIcon
+import androidx.core.graphics.drawable.IconCompat
+import java.net.HttpURLConnection
+import java.net.URL
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+
+object FAAHelpers {
+ fun makeFCPChannelId(event: String): String {
+ return "com.oguzhnatly.flutter_android_auto" + event
+ }
+}
+
+suspend fun loadCarImageAsync(imageUrl: String): CarIcon? {
+ return withContext(Dispatchers.IO) {
+ try {
+ val url = URL(imageUrl)
+ val connection = url.openConnection() as HttpURLConnection
+ connection.doInput = true
+ connection.connect()
+ val inputStream = connection.inputStream
+ val bitmap = BitmapFactory.decodeStream(inputStream)
+ val iconCompat = IconCompat.createWithBitmap(bitmap)
+ CarIcon.Builder(iconCompat).build()
+ } catch (e: Exception) {
+ e.printStackTrace()
+ null
+ }
+ }
+}
+
diff --git a/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/FlutterAndroidAutoPlugin.kt b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/FlutterAndroidAutoPlugin.kt
new file mode 100644
index 00000000..c900db9b
--- /dev/null
+++ b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/FlutterAndroidAutoPlugin.kt
@@ -0,0 +1,325 @@
+package com.oguzhnatly.flutter_android_auto
+
+import androidx.car.app.CarContext
+import androidx.car.app.model.Action
+import androidx.car.app.model.CarIcon
+import androidx.car.app.model.CarText
+import androidx.car.app.model.ItemList
+import androidx.car.app.model.ListTemplate
+import androidx.car.app.model.SectionedItemList
+import androidx.car.app.model.Row
+import androidx.car.app.model.Template
+import androidx.car.app.Screen
+import androidx.car.app.ScreenManager
+import io.flutter.embedding.engine.plugins.FlutterPlugin
+import io.flutter.plugin.common.EventChannel
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.LifecycleEventObserver
+import androidx.lifecycle.LifecycleOwner
+
+
+class FlutterAndroidAutoPlugin : FlutterPlugin, EventChannel.StreamHandler {
+ private val pluginScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
+
+ lateinit var channel: MethodChannel
+ lateinit var eventChannel: EventChannel
+
+ companion object {
+ var events: EventChannel.EventSink? = null
+ var currentTemplate: Template? = null
+ var currentScreen: Screen? = null
+
+ fun sendEvent(type: String, data: Map<String, Any>) {
+ events?.success(
+ mapOf(
+ "type" to type, "data" to data
+ )
+ )
+ }
+
+ fun onAndroidAutoConnectionChange(status: FAAConnectionTypes) {
+ sendEvent(
+ type = FAAChannelTypes.onAndroidAutoConnectionChange.name,
+ data = mapOf("status" to status.name)
+ )
+ }
+ }
+
+ override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
+ channel = MethodChannel(
+ flutterPluginBinding.binaryMessenger,
+ FAAHelpers.makeFCPChannelId("")
+ )
+ eventChannel = EventChannel(
+ flutterPluginBinding.binaryMessenger,
+ FAAHelpers.makeFCPChannelId("/event")
+ )
+ setUpHandlers()
+ }
+
+ private fun setUpHandlers() {
+ channel.setMethodCallHandler { call, result ->
+ try {
+ when (call.method) {
+ FAAChannelTypes.forceUpdateRootTemplate.name -> forceUpdateRootTemplate(
+ call, result
+ )
+
+ FAAChannelTypes.setRootTemplate.name -> setRootTemplate(
+ call, result
+ )
+
+ FAAChannelTypes.pushTemplate.name -> pushTemplate(
+ call, result
+ )
+
+ FAAChannelTypes.popTemplate.name -> popTemplate(
+ call, result
+
+ )
+
+ FAAChannelTypes.popToRootTemplate.name -> popToRootTemplate(
+ call, result
+ )
+
+ FAAChannelTypes.onListItemSelectedComplete.name
+
+ -> onListItemSelectedComplete(
+ call, result
+ )
+
+ else -> result.notImplemented()
+ }
+ } catch (e: Exception) {
+ e.printStackTrace()
+ result.error("Error: $e", null, null)
+ }
+ }
+ eventChannel.setStreamHandler(this)
+ }
+
+ private fun forceUpdateRootTemplate(
+ call: MethodCall, result: MethodChannel.Result
+ ) {
+ val carContext = AndroidAutoService.session?.carContext
+ if (carContext == null) return;
+
+ currentScreen?.let {
+ it.invalidate()
+ result.success(true)
+ } ?: run {
+ result.error(
+ "No screen found", "You must set a RootTemplate first", null
+ )
+ }
+ }
+
+ private fun popTemplate(
+ call: MethodCall, result: MethodChannel.Result
+ ) {
+ val carContext = AndroidAutoService.session?.carContext
+ if (carContext == null) return;
+
+ val screenManager = carContext.getCarService(ScreenManager::class.java)
+ if (screenManager.stackSize > 1) {
+ screenManager.pop()
+ result.success(true)
+ } else {
+ result.error("No screens to pop", "You are at root screen", null)
+ }
+ }
+
+ private fun popToRootTemplate(
+ call: MethodCall, result: MethodChannel.Result
+ ) {
+ val carContext = AndroidAutoService.session?.carContext
+ if (carContext == null) return;
+
+ val screenManager = carContext.getCarService(ScreenManager::class.java)
+ if (screenManager.stackSize > 1) {
+ screenManager.popToRoot()
+ result.success(true)
+ } else {
+ result.error("No screens to pop", "You are at root screen", null)
+ }
+ }
+
+
+ private fun onListItemSelectedComplete(
+ call: MethodCall, result: MethodChannel.Result
+ ) {
+ result.success(true)
+ }
+
+ private fun pushTemplate(
+ call: MethodCall, result: MethodChannel.Result
+ ) {
+ val carContext = AndroidAutoService.session?.carContext
+ if (carContext == null) return;
+
+ val runtimeType = call.argument<String>("runtimeType") ?: ""
+ val data = call.argument<Map<String, Any?>>("template")!!
+ val elementId = data["_elementId"] as? String ?: ""
+
+ pluginScope.launch {
+ val template = when (runtimeType) {
+ "FAAListTemplate" -> getListTemplate(
+ call, result, data
+ )
+
+ else -> null
+ }
+ if (template == null) {
+ result.error(
+ "Unsupported template type",
+ "Template type: $runtimeType is not supported",
+ null
+ )
+ } else {
+ val newScreen = object : Screen(carContext) {
+ override fun onGetTemplate(): Template = template
+
+ init {
+ lifecycle.addObserver(object : LifecycleEventObserver {
+ override fun onStateChanged(
+ source: LifecycleOwner, event: Lifecycle.Event
+ ) {
+ when (event) {
+ Lifecycle.Event.ON_DESTROY -> {
+ sendEvent(
+ type = FAAChannelTypes.onScreenBackButtonPressed.name,
+ data = mapOf("elementId" to elementId)
+ )
+ }
+
+ else -> {}
+ }
+ }
+ })
+ }
+ }
+
+ carContext.getCarService(ScreenManager::class.java)
+ .push(newScreen)
+
+ result.success(true)
+ }
+ }
+ }
+
+ private fun setRootTemplate(
+ call: MethodCall, result: MethodChannel.Result
+ ) {
+ val runtimeType = call.argument<String>("runtimeType") ?: ""
+ val data = call.argument<Map<String, Any?>>("template")!!
+
+ pluginScope.launch {
+ val template = when (runtimeType) {
+ "FAAListTemplate" -> getListTemplate(
+ call, result, data, false
+ )
+
+ else -> null
+ }
+
+ if (template == null) {
+ result.error(
+ "Unsupported template type",
+ "Template type: $runtimeType is not supported",
+ null,
+ )
+ } else {
+ currentTemplate = template
+ currentScreen?.invalidate()
+ result.success(true)
+ }
+ }
+ }
+
+ private suspend fun getListTemplate(
+ call: MethodCall,
+ result: MethodChannel.Result,
+ data: Map<String, Any?>,
+ addBackButton: Boolean = true
+ ): Template {
+ val template = FAAListTemplate.fromJson(data)
+ val listTemplateBuilder =
+ ListTemplate.Builder().setTitle(template.title)
+
+ if (template.sections.size == 0) {
+ listTemplateBuilder.setLoading(true)
+ } else {
+ listTemplateBuilder.setLoading(false)
+ val isSingleList =
+ template.sections.size == 1 && template.sections.first().title.isEmpty()
+
+ if (isSingleList) {
+ val itemListBuilder = ItemList.Builder()
+ val sectionItems = template.sections.first().items
+ for (item in sectionItems) {
+ itemListBuilder.addItem(createRowFromItem(item))
+ }
+ listTemplateBuilder.setSingleList(itemListBuilder.build())
+ } else {
+ for (section in template.sections) {
+ val itemListBuilder = ItemList.Builder()
+ for (item in section.items) {
+ itemListBuilder.addItem(createRowFromItem(item))
+ }
+ val sectionedItemList = SectionedItemList.create(
+ itemListBuilder.build(), section.title ?: ""
+ )
+ listTemplateBuilder.addSectionedList(sectionedItemList)
+ }
+ }
+ }
+
+ if (addBackButton) {
+ listTemplateBuilder.setHeaderAction(Action.BACK)
+ }
+
+ return listTemplateBuilder.build()
+ }
+
+ // Helper function to create a Row from an FAAListItem, avoiding code duplication
+ private suspend fun createRowFromItem(item: FAAListItem): Row {
+ val rowBuilder = Row.Builder().setTitle(CarText.create(item.title))
+
+ item.subtitle?.let { rowBuilder.addText(CarText.create(it)) }
+
+ item.imageUrl?.let {
+ loadCarImageAsync(it)?.let { carIcon ->
+ rowBuilder.setImage(carIcon)
+ }
+ }
+
+ if (item.isOnPressListenerActive) {
+ rowBuilder.setOnClickListener {
+ sendEvent(
+ type = FAAChannelTypes.onListItemSelected.name,
+ data = mapOf("elementId" to item.elementId)
+ )
+ }
+ }
+ return rowBuilder.build()
+ }
+
+ override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
+ FlutterAndroidAutoPlugin.events = events
+ }
+
+ override fun onCancel(arguments: Any?) {
+ events?.endOfStream()
+ }
+
+ override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
+ channel.setMethodCallHandler(null)
+ eventChannel.setStreamHandler(null)
+ }
+}
diff --git a/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/Screen.kt b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/Screen.kt
new file mode 100644
index 00000000..f2058b6c
--- /dev/null
+++ b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/Screen.kt
@@ -0,0 +1,36 @@
+package com.oguzhnatly.flutter_android_auto
+
+
+import android.Manifest
+import android.content.Intent
+import android.net.Uri
+import android.service.credentials.Action
+import android.text.Spannable
+import android.text.SpannableString
+import androidx.annotation.OptIn
+import androidx.car.app.CarAppService
+import androidx.car.app.CarContext
+import androidx.car.app.Screen
+import androidx.car.app.Session
+import androidx.car.app.annotations.ExperimentalCarApi
+import androidx.car.app.model.CarLocation
+import androidx.car.app.model.ItemList
+import androidx.car.app.model.Metadata
+import androidx.car.app.model.PlaceListMapTemplate
+import androidx.car.app.model.PlaceMarker
+import androidx.car.app.model.Row
+import androidx.car.app.model.Template
+import androidx.car.app.model.ListTemplate
+
+class MainScreen(carContext: CarContext) : Screen(carContext) {
+ init {}
+
+ override fun onGetTemplate(): Template {
+ val appName =
+ carContext.applicationInfo.loadLabel(carContext.packageManager)
+ .toString() ?: ""
+
+ return FlutterAndroidAutoPlugin.currentTemplate
+ ?: ListTemplate.Builder().setTitle(appName).setLoading(true).build()
+ }
+}
diff --git a/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/Session.kt b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/Session.kt
new file mode 100644
index 00000000..2192e0a7
--- /dev/null
+++ b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/Session.kt
@@ -0,0 +1,40 @@
+package com.oguzhnatly.flutter_android_auto
+
+import android.content.Intent
+import androidx.car.app.Screen
+import androidx.car.app.Session
+import androidx.lifecycle.DefaultLifecycleObserver
+import androidx.lifecycle.LifecycleOwner
+
+class AndroidAutoSession : Session() {
+ override fun onCreateScreen(intent: Intent): Screen {
+ val screen = MainScreen(carContext)
+ FlutterAndroidAutoPlugin.currentScreen = screen
+
+ lifecycle.addObserver(object : DefaultLifecycleObserver {
+ override fun onStart(owner: LifecycleOwner) {
+ FlutterAndroidAutoPlugin.onAndroidAutoConnectionChange(
+ FAAConnectionTypes.connected
+ )
+ super.onStart(owner)
+ }
+
+
+ override fun onResume(owner: LifecycleOwner) {
+ FlutterAndroidAutoPlugin.onAndroidAutoConnectionChange(
+ FAAConnectionTypes.connected
+ )
+ super.onResume(owner)
+ }
+
+ override fun onStop(owner: LifecycleOwner) {
+ FlutterAndroidAutoPlugin.onAndroidAutoConnectionChange(
+ FAAConnectionTypes.disconnected
+ )
+ super.onStop(owner)
+ }
+ })
+
+ return screen
+ }
+}
diff --git a/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/models/list/FAAListItem.kt b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/models/list/FAAListItem.kt
new file mode 100644
index 00000000..684cbbe2
--- /dev/null
+++ b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/models/list/FAAListItem.kt
@@ -0,0 +1,23 @@
+package com.oguzhnatly.flutter_android_auto
+
+data class FAAListItem(
+ val elementId: String,
+ val title: String,
+ val subtitle: String? = null,
+ val imageUrl: String? = null,
+ val isOnPressListenerActive: Boolean,
+) {
+ companion object {
+ fun fromJson(map: Map<String, Any?>): FAAListItem {
+ val elementId = map["_elementId"] as? String ?: ""
+ val title = map["title"] as? String ?: ""
+ val subtitle = map["subtitle"] as? String
+ val imageUrl = map["imageUrl"] as? String
+ val isOnPressListenerActive = map["onPress"] as? Boolean ?: false
+
+ return FAAListItem(
+ elementId, title, subtitle, imageUrl, isOnPressListenerActive
+ )
+ }
+ }
+}
diff --git a/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/models/list/FAAListSection.kt b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/models/list/FAAListSection.kt
new file mode 100644
index 00000000..9339bae7
--- /dev/null
+++ b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/models/list/FAAListSection.kt
@@ -0,0 +1,20 @@
+package com.oguzhnatly.flutter_android_auto
+
+data class FAAListSection(
+ val elementId: String,
+ val title: String,
+ val items: List<FAAListItem>,
+) {
+ companion object {
+ fun fromJson(map: Map<String, Any?>): FAAListSection {
+ val elementId = map["_elementId"] as? String ?: ""
+ val title = map["title"] as? String ?: ""
+ val items = (map["items"] as? List<*>)?.mapNotNull {
+ (it as? Map<*, *>)?.mapKeys { entry -> entry.key.toString() }
+ ?.let { FAAListItem.fromJson(it) }
+ } ?: emptyList()
+
+ return FAAListSection(elementId, title, items)
+ }
+ }
+}
diff --git a/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/models/list/FAAListTemplate.kt b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/models/list/FAAListTemplate.kt
new file mode 100644
index 00000000..4499f454
--- /dev/null
+++ b/packages/flutter_carplay/android/src/main/kotlin/com/oguzhnatly/flutter_android_auto/models/list/FAAListTemplate.kt
@@ -0,0 +1,20 @@
+package com.oguzhnatly.flutter_android_auto
+
+data class FAAListTemplate(
+ val elementId: String,
+ val title: String,
+ val sections: List<FAAListSection>,
+) {
+ companion object {
+ fun fromJson(map: Map<String, Any?>): FAAListTemplate {
+ val elementId = map["_elementId"] as? String ?: ""
+ val title = map["title"] as? String ?: ""
+ val sections = (map["sections"] as? List<*>)?.mapNotNull {
+ (it as? Map<*, *>)?.mapKeys { entry -> entry.key.toString() }
+ ?.let { FAAListSection.fromJson(it) }
+ } ?: emptyList()
+
+ return FAAListTemplate(elementId, title, sections)
+ }
+ }
+}
diff --git a/packages/flutter_carplay/ios/Classes/FCPEnums.swift b/packages/flutter_carplay/ios/Classes/FCPEnums.swift
new file mode 100644
index 00000000..995ea4ab
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/FCPEnums.swift
@@ -0,0 +1,46 @@
+//
+// FCPEnums.swift
+// flutter_carplay
+//
+// Created by Oğuzhan Atalay on 21.08.2021.
+//
+
+enum FCPConnectionTypes {
+ static let connected = "CONNECTED"
+ static let background = "BACKGROUND"
+ static let disconnected = "DISCONNECTED"
+}
+
+enum FCPChannelTypes {
+ static let onCarplayConnectionChange = "onCarplayConnectionChange"
+ static let setRootTemplate = "setRootTemplate"
+ static let forceUpdateRootTemplate = "forceUpdateRootTemplate"
+ static let updateListTemplateSections = "updateListTemplateSections"
+ static let updateTabBarTemplates = "updateTabBarTemplates"
+ static let updateListItem = "updateListItem"
+ static let onListItemSelected = "onFCPListItemSelected"
+ static let onListItemSelectedComplete = "onFCPListItemSelectedComplete"
+ static let onAlertActionPressed = "onFCPAlertActionPressed"
+ static let setAlert = "setAlert"
+ static let onPresentStateChanged = "onPresentStateChanged"
+ static let popTemplate = "popTemplate"
+ static let pushTemplate = "pushTemplate"
+ static let showNowPlaying = "showNowPlaying"
+ static let closePresent = "closePresent"
+ static let onGridButtonPressed = "onGridButtonPressed"
+ static let setActionSheet = "setActionSheet"
+ static let onBarButtonPressed = "onBarButtonPressed"
+ static let onTextButtonPressed = "onTextButtonPressed"
+ static let popToRootTemplate = "popToRootTemplate"
+ static let onScreenBackButtonPressed = "onScreenBackButtonPressed"
+}
+
+enum FCPAlertActionTypes {
+ case ACTION_SHEET
+ case ALERT
+}
+
+enum FCPListTemplateTypes {
+ case PART_OF_GRID_TEMPLATE
+ case DEFAULT
+}
diff --git a/packages/flutter_carplay/ios/Classes/FCPExtensions.swift b/packages/flutter_carplay/ios/Classes/FCPExtensions.swift
new file mode 100644
index 00000000..d1936f06
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/FCPExtensions.swift
@@ -0,0 +1,174 @@
+//
+// FCPExtensions.swift
+// flutter_carplay
+//
+// Created by Oğuzhan Atalay on 21.08.2021.
+//
+
+import UIKit
+import ImageIO
+
+// Image Source (no UIImage creation here)
+enum ImageSource {
+ case url(URL)
+ case file(String)
+ case flutterAsset(String)
+}
+
+// String → ImageSource
+extension String {
+ func toImageSource() -> ImageSource {
+ if self.starts(with: "http") {
+ return .url(URL(string: self)!)
+ } else if self.starts(with: "file://") {
+ return .file(self.replacingOccurrences(of: "file://", with: ""))
+ } else {
+ return .flutterAsset(self)
+ }
+ }
+}
+
+func makeSafeUIPlaceholder() -> UIImage {
+ if Thread.isMainThread {
+ return makeUIPlaceholder()
+ } else {
+ return DispatchQueue.main.sync {
+ makeUIPlaceholder()
+ }
+ }
+}
+
+func makeUIPlaceholder() -> UIImage {
+ UIGraphicsBeginImageContextWithOptions(CGSize(width: 100, height: 100), false, 0)
+ let img = UIGraphicsGetImageFromCurrentImageContext()!
+ UIGraphicsEndImageContext()
+ return img
+}
+
+// UIImage creation (MAIN THREAD ONLY)
+@available(iOS 14.0, *)
+func makeUIImage(from source: ImageSource) -> UIImage {
+ switch source {
+ case .url(let url):
+ let data = try? Data(contentsOf: url) // Synchronous URL loading (kept for compatibility but avoid using on main thread)
+ return data.flatMap { UIImage(data: $0) } ?? UIImage(systemName: "questionmark")!
+
+ case .file(let path):
+ return UIImage(contentsOfFile: path) ?? UIImage(systemName: "questionmark")!
+
+ case .flutterAsset(let name):
+ let key = SwiftFlutterCarplayPlugin.registrar!.lookupKey(forAsset: name)
+ return UIImage(imageLiteralResourceName: key)
+ }
+}
+
+// ─── Absorb local patch: downsampled + cached CarPlay list thumbnails ───
+//
+// The stock plugin decoded every cover at full resolution and started a load
+// for every item the moment a list was built. A large list (e.g. an
+// alphabetical browse) decoded ~100 multi-megabyte images at once and ran
+// CarPlay out of its tight memory budget. We downsample to a small thumbnail
+// at decode time (the real fix) and cache the result so re-navigating is
+// instant. URLSession's per-host connection limit keeps concurrent loads in
+// check.
+private let fcpThumbnailCache: NSCache<NSURL, UIImage> = {
+ let cache = NSCache<NSURL, UIImage>()
+ cache.countLimit = 300
+ return cache
+}()
+
+// CarPlay list rows are small; 240px is sharp at @3x while keeping each decoded
+// image near ~230 KB instead of several MB.
+private let fcpThumbnailMaxPixels = 240
+
+private func fcpDownsample(_ source: CGImageSource, maxPixelSize: Int) -> UIImage? {
+ let options: [CFString: Any] = [
+ kCGImageSourceCreateThumbnailFromImageAlways: true,
+ kCGImageSourceCreateThumbnailWithTransform: true,
+ kCGImageSourceShouldCacheImmediately: true,
+ kCGImageSourceThumbnailMaxPixelSize: maxPixelSize,
+ ]
+ guard let cg = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil }
+ return UIImage(cgImage: cg)
+}
+
+private func fcpDownsampledImage(data: Data, maxPixelSize: Int) -> UIImage? {
+ let opts: [CFString: Any] = [kCGImageSourceShouldCache: false]
+ guard let src = CGImageSourceCreateWithData(data as CFData, opts as CFDictionary) else { return nil }
+ return fcpDownsample(src, maxPixelSize: maxPixelSize)
+}
+
+private func fcpDownsampledImage(fileURL: URL, maxPixelSize: Int) -> UIImage? {
+ let opts: [CFString: Any] = [kCGImageSourceShouldCache: false]
+ guard let src = CGImageSourceCreateWithURL(fileURL as CFURL, opts as CFDictionary) else { return nil }
+ return fcpDownsample(src, maxPixelSize: maxPixelSize)
+}
+
+// Asynchronous image loader. Always calls completion on main thread.
+@available(iOS 14.0, *)
+func loadUIImageAsync(from source: ImageSource, completion: @escaping (UIImage?) -> Void) {
+ switch source {
+ case .url(let url):
+ if let cached = fcpThumbnailCache.object(forKey: url as NSURL) {
+ DispatchQueue.main.async { completion(cached) }
+ return
+ }
+ let task = URLSession.shared.dataTask(with: url) { data, response, error in
+ var image: UIImage? = nil
+ if let data = data {
+ // Downsample at decode time; fall back to a full decode only if
+ // the source can't produce a thumbnail.
+ image = fcpDownsampledImage(data: data, maxPixelSize: fcpThumbnailMaxPixels) ?? UIImage(data: data)
+ }
+ if let image = image {
+ fcpThumbnailCache.setObject(image, forKey: url as NSURL)
+ DispatchQueue.main.async { completion(image) }
+ } else {
+ DispatchQueue.main.async { completion(UIImage(systemName: "questionmark")) }
+ }
+ }
+ task.resume()
+
+ case .file(let path):
+ DispatchQueue.global(qos: .userInitiated).async {
+ let image = fcpDownsampledImage(fileURL: URL(fileURLWithPath: path), maxPixelSize: fcpThumbnailMaxPixels)
+ ?? UIImage(contentsOfFile: path)
+ ?? UIImage(systemName: "questionmark")
+ DispatchQueue.main.async { completion(image) }
+ }
+
+ case .flutterAsset(let name):
+ DispatchQueue.main.async {
+ let key = SwiftFlutterCarplayPlugin.registrar!.lookupKey(forAsset: name)
+ let image = UIImage(imageLiteralResourceName: key)
+ completion(image)
+ }
+ }
+}
+
+// UIImage utilities (safe, UI only)
+extension UIImage {
+ func resizeImageTo(size: CGSize) -> UIImage {
+ UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
+ draw(in: CGRect(origin: .zero, size: size))
+ let newImage = UIGraphicsGetImageFromCurrentImageContext()!
+ UIGraphicsEndImageContext()
+ return newImage
+ }
+}
+
+// Regex helper
+extension String {
+ func match(_ regex: String) -> [[String]] {
+ let nsString = self as NSString
+ return (try? NSRegularExpression(pattern: regex))?
+ .matches(in: self, range: NSRange(location: 0, length: nsString.length))
+ .map { match in
+ (0..<match.numberOfRanges).map {
+ match.range(at: $0).location == NSNotFound
+ ? ""
+ : nsString.substring(with: match.range(at: $0))
+ }
+ } ?? []
+ }
+}
diff --git a/packages/flutter_carplay/ios/Classes/FCPHelpers.swift b/packages/flutter_carplay/ios/Classes/FCPHelpers.swift
new file mode 100644
index 00000000..b24b8bb1
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/FCPHelpers.swift
@@ -0,0 +1,10 @@
+//
+// FCPHelpers.swift
+// flutter_carplay
+//
+// Created by Oğuzhan Atalay on 21.08.2021.
+//
+
+func makeFCPChannelId(event: String?) -> String {
+ return "com.oguzhnatly.flutter_carplay" + event!
+}
diff --git a/packages/flutter_carplay/ios/Classes/FCPProtocols.swift b/packages/flutter_carplay/ios/Classes/FCPProtocols.swift
new file mode 100644
index 00000000..fce114f6
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/FCPProtocols.swift
@@ -0,0 +1,14 @@
+//
+// FCPProtocols.swift
+// flutter_carplay
+//
+// Created by Oğuzhan Atalay on 25.08.2021.
+//
+import CarPlay
+
+public protocol FCPPresentTemplate: AnyObject {}
+
+public protocol FCPRootTemplate: AnyObject {
+ var get: CPTemplate { get }
+ var elementId: String { get }
+}
diff --git a/packages/flutter_carplay/ios/Classes/FCPStreamHandlerPlugin.swift b/packages/flutter_carplay/ios/Classes/FCPStreamHandlerPlugin.swift
new file mode 100644
index 00000000..3c760486
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/FCPStreamHandlerPlugin.swift
@@ -0,0 +1,48 @@
+//
+// FCPStreamHandlerPlugin.swift
+// flutter_carplay
+//
+// Created by Oğuzhan Atalay on 21.08.2021.
+//
+
+import Flutter
+
+@available(iOS 14.0, *)
+class FCPStreamHandlerPlugin: NSObject, FlutterStreamHandler {
+ private static var eventSink: FlutterEventSink?
+
+ public required init(registrar: FlutterPluginRegistrar) {
+ super.init()
+ let eventChannel = FlutterEventChannel(name: makeFCPChannelId(event: "/event"),
+ binaryMessenger: registrar.messenger())
+ eventChannel.setStreamHandler(self)
+ return
+ }
+
+ public func onListen(withArguments arguments: Any?,
+ eventSink: @escaping FlutterEventSink) -> FlutterError? {
+ FCPStreamHandlerPlugin.eventSink = eventSink
+ return nil
+ }
+
+ public func sendCarplayConnectionChangeEvent(status: String) {
+ FCPStreamHandlerPlugin.sendEvent(type: FCPChannelTypes.onCarplayConnectionChange, data: ["status": status])
+ }
+
+ public static func sendEvent(type: String, data: Dictionary<String, Any>) {
+ guard let eventSink = FCPStreamHandlerPlugin.eventSink else {
+ return
+ }
+
+ eventSink([
+ "type": type,
+ "data": data,
+ ] as Dictionary<String, Any>)
+ }
+
+ public func onCancel(withArguments arguments: Any?) -> FlutterError? {
+ FCPStreamHandlerPlugin.eventSink = nil
+ return nil
+ }
+}
+
diff --git a/packages/flutter_carplay/ios/Classes/FlutterCarplayPlugin.h b/packages/flutter_carplay/ios/Classes/FlutterCarplayPlugin.h
new file mode 100644
index 00000000..a7fdf9f5
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/FlutterCarplayPlugin.h
@@ -0,0 +1,4 @@
+#import <Flutter/Flutter.h>
+
+@interface FlutterCarplayPlugin : NSObject<FlutterPlugin>
+@end
diff --git a/packages/flutter_carplay/ios/Classes/FlutterCarplayPlugin.m b/packages/flutter_carplay/ios/Classes/FlutterCarplayPlugin.m
new file mode 100644
index 00000000..6cfdaa30
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/FlutterCarplayPlugin.m
@@ -0,0 +1,15 @@
+#import "FlutterCarplayPlugin.h"
+#if __has_include(<flutter_carplay/flutter_carplay-Swift.h>)
+#import <flutter_carplay/flutter_carplay-Swift.h>
+#else
+// Support project import fallback if the generated compatibility header
+// is not copied when this plugin is created as a library.
+// https://forums.swift.org/t/swift-static-libraries-dont-copy-generated-objective-c-header/19816
+#import "flutter_carplay-Swift.h"
+#endif
+
+@implementation FlutterCarplayPlugin
++ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
+ [SwiftFlutterCarplayPlugin registerWithRegistrar:registrar];
+}
+@end
diff --git a/packages/flutter_carplay/ios/Classes/FlutterCarplayPluginSceneDelegate.swift b/packages/flutter_carplay/ios/Classes/FlutterCarplayPluginSceneDelegate.swift
new file mode 100644
index 00000000..b65bc74f
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/FlutterCarplayPluginSceneDelegate.swift
@@ -0,0 +1,152 @@
+//
+// FlutterCarPlayPluginsSceneDelegate.swift
+// flutter_carplay
+//
+// Created by Oğuzhan Atalay on 21.08.2021.
+//
+
+import CarPlay
+
+extension CPTemplate {
+ private static var elementIdKey: UInt8 = 0
+
+ var elementId: String? {
+ get {
+ return objc_getAssociatedObject(self, &CPTemplate.elementIdKey) as? String
+ }
+ set {
+ objc_setAssociatedObject(self, &CPTemplate.elementIdKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
+ }
+ }
+}
+
+@available(iOS 14.0, *)
+@objc(FlutterCarPlaySceneDelegate)
+class FlutterCarPlaySceneDelegate: UIResponder, CPTemplateApplicationSceneDelegate, CPInterfaceControllerDelegate {
+ static private var interfaceController: CPInterfaceController?
+
+ static public func forceUpdateRootTemplate() {
+ let rootTemplate = SwiftFlutterCarplayPlugin.rootTemplate
+ let animated = SwiftFlutterCarplayPlugin.animated
+
+ self.interfaceController?.setRootTemplate(rootTemplate!, animated: animated)
+ }
+
+ // https://developer.apple.com/documentation/carplay/cplisttemplate/updatesections(_:)
+ static public func updateListTemplateSections(elementId: String, sections: [FCPListSection]) {
+ guard let templateFromHistory = SwiftFlutterCarplayPlugin.getTemplateFromHistory(elementId: elementId) as? FCPListTemplate else {
+ NSLog("FlutterCarPlaySceneDelegate - updateListTemplateSections: Template from history with elementId \(elementId) not found.")
+ return
+ }
+
+ templateFromHistory.updateSections(sections: sections)
+ }
+
+ // https://developer.apple.com/documentation/carplay/cptabbartemplate/updatetemplates(_:)
+ static public func updateTabBarTemplates(elementId: String, templates: Array<[String: Any]>) {
+ guard let templateFromHistory = SwiftFlutterCarplayPlugin.getTemplateFromHistory(elementId: elementId) as? FCPTabBarTemplate else {
+ NSLog("FlutterCarPlaySceneDelegate - updateTabBarTemplates: TabBar template from history with elementId \(elementId) not found.")
+ return
+ }
+
+ templateFromHistory.updateTemplates(newTemplatesData: templates)
+ }
+
+ // Fired when just before the carplay become active
+ func sceneDidBecomeActive(_ scene: UIScene) {
+ SwiftFlutterCarplayPlugin.onCarplayConnectionChange(status: FCPConnectionTypes.connected)
+ }
+
+ // Fired when carplay entered background
+ func sceneDidEnterBackground(_ scene: UIScene) {
+ SwiftFlutterCarplayPlugin.onCarplayConnectionChange(status: FCPConnectionTypes.background)
+ }
+
+ static public func pop(animated: Bool) {
+ self.interfaceController?.popTemplate(animated: animated)
+ }
+
+ static public func popToRootTemplate(animated: Bool) {
+ self.interfaceController?.popToRootTemplate(animated: animated)
+ }
+
+ static public func push(template: CPTemplate, animated: Bool) -> Bool {
+ guard let interfaceController = self.interfaceController else { return false }
+ guard interfaceController.rootTemplate != nil else { return false }
+
+ interfaceController.pushTemplate(template, animated: animated)
+ return true
+ }
+
+ static public func pushIfNotExist(template: CPTemplate, animated: Bool) -> Bool {
+ guard let interfaceController = self.interfaceController else { return false }
+ guard interfaceController.rootTemplate != nil else { return false }
+
+ let isAlreadyPushed = interfaceController.templates.contains { $0 === template }
+ let isTopSameInstance = interfaceController.topTemplate === template
+
+ if !isAlreadyPushed && !isTopSameInstance {
+ interfaceController.pushTemplate(template, animated: animated)
+ return true
+ }
+ return false
+ }
+
+ func templateDidDisappear(_ template: CPTemplate, animated: Bool) {
+ guard let interfaceController = FlutterCarPlaySceneDelegate.interfaceController else { return }
+
+ let currentTemplates = interfaceController.templates
+
+ SwiftFlutterCarplayPlugin.templateStack.removeAll { stackTemplate in
+ if !currentTemplates.contains(where: { $0.elementId == stackTemplate.elementId }) {
+ SwiftFlutterCarplayPlugin.sendOnScreenBackButtonPressed(elementId: stackTemplate.elementId)
+ return true
+ }
+ return false
+ }
+ }
+
+ static public func closePresent(animated: Bool) {
+ self.interfaceController?.dismissTemplate(animated: animated)
+ }
+
+ static public func presentTemplate(template: CPTemplate, animated: Bool,
+ onPresent: @escaping (_ completed: Bool) -> Void) {
+ self.interfaceController?.presentTemplate(template, animated: animated, completion: { completed, error in
+ guard error != nil else {
+ onPresent(false)
+ return
+ }
+ onPresent(completed)
+ })
+ }
+
+ func templateApplicationScene(_ templateApplicationScene: CPTemplateApplicationScene,
+ didConnect interfaceController: CPInterfaceController) {
+ FlutterCarPlaySceneDelegate.interfaceController = interfaceController
+ interfaceController.delegate = self
+
+ SwiftFlutterCarplayPlugin.onCarplayConnectionChange(status: FCPConnectionTypes.connected)
+ let rootTemplate = SwiftFlutterCarplayPlugin.rootTemplate
+
+ if rootTemplate != nil {
+ FlutterCarPlaySceneDelegate.interfaceController?.setRootTemplate(rootTemplate!, animated: SwiftFlutterCarplayPlugin.animated, completion: nil)
+ }
+ }
+
+ func templateApplicationScene(_ templateApplicationScene: CPTemplateApplicationScene,
+ didDisconnect interfaceController: CPInterfaceController, from window: CPWindow) {
+ SwiftFlutterCarplayPlugin.onCarplayConnectionChange(status: FCPConnectionTypes.disconnected)
+
+ interfaceController.delegate = nil
+ FlutterCarPlaySceneDelegate.interfaceController = nil
+ }
+
+ func templateApplicationScene(_ templateApplicationScene: CPTemplateApplicationScene,
+ didDisconnectInterfaceController interfaceController: CPInterfaceController) {
+ SwiftFlutterCarplayPlugin.onCarplayConnectionChange(status: FCPConnectionTypes.disconnected)
+
+ interfaceController.delegate = nil
+ FlutterCarPlaySceneDelegate.interfaceController = nil
+ }
+}
diff --git a/packages/flutter_carplay/ios/Classes/SwiftFlutterCarplayPlugin.swift b/packages/flutter_carplay/ios/Classes/SwiftFlutterCarplayPlugin.swift
new file mode 100644
index 00000000..949da42a
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/SwiftFlutterCarplayPlugin.swift
@@ -0,0 +1,330 @@
+//
+// SwiftFlutterCarplayPlugin.swift
+// flutter_carplay
+//
+// Created by Oğuzhan Atalay on 21.08.2021.
+//
+
+import Flutter
+import CarPlay
+
+@available(iOS 14.0, *)
+public class SwiftFlutterCarplayPlugin: NSObject, FlutterPlugin {
+ private static var streamHandler: FCPStreamHandlerPlugin?
+ private(set) static var registrar: FlutterPluginRegistrar?
+ private static var objcRootTemplate: FCPRootTemplate?
+ static var templateStack: [FCPRootTemplate] = []
+ private static var _rootTemplate: CPTemplate?
+ public static var animated: Bool = false
+ private var objcPresentTemplate: FCPPresentTemplate?
+
+ public static var rootTemplate: CPTemplate? {
+ get {
+ return _rootTemplate
+ }
+ set(tabBarTemplate) {
+ _rootTemplate = tabBarTemplate
+ }
+ }
+
+ public static func register(with registrar: FlutterPluginRegistrar) {
+ let channel = FlutterMethodChannel(name: makeFCPChannelId(event: ""),
+ binaryMessenger: registrar.messenger())
+ let instance = SwiftFlutterCarplayPlugin()
+ registrar.addMethodCallDelegate(instance, channel: channel)
+ self.registrar = registrar
+
+ self.streamHandler = FCPStreamHandlerPlugin(registrar: registrar)
+ }
+
+ public static func sendOnScreenBackButtonPressed(elementId: String) {
+ FCPStreamHandlerPlugin.sendEvent(type: FCPChannelTypes.onScreenBackButtonPressed, data: ["elementId": elementId])
+ }
+
+ public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
+ switch call.method {
+ case FCPChannelTypes.setRootTemplate:
+ guard let args = call.arguments as? [String : Any] else {
+ result(false)
+ return
+ }
+ var rootTemplate: FCPRootTemplate?
+ switch args["runtimeType"] as! String {
+ case String(describing: FCPTabBarTemplate.self):
+ rootTemplate = FCPTabBarTemplate(obj: args["rootTemplate"] as! [String : Any])
+ let tabBarTemplate = rootTemplate as! FCPTabBarTemplate
+ if tabBarTemplate.getTemplates().count > CPTabBarTemplate.maximumTabCount {
+ result(FlutterError(code: "ERROR",
+ message: "CarPlay cannot have more than \(CPTabBarTemplate.maximumTabCount) templates on one screen.",
+ details: nil))
+ return
+ }
+ break
+ case String(describing: FCPGridTemplate.self):
+ rootTemplate = FCPGridTemplate(obj: args["rootTemplate"] as! [String : Any])
+ break
+ case String(describing: FCPInformationTemplate.self):
+ rootTemplate = FCPInformationTemplate(obj: args["rootTemplate"] as! [String : Any])
+ break
+ case String(describing: FCPPointOfInterestTemplate.self):
+ rootTemplate = FCPPointOfInterestTemplate(obj: args["rootTemplate"] as! [String : Any])
+ break
+ case String(describing: FCPListTemplate.self):
+ rootTemplate = FCPListTemplate(obj: args["rootTemplate"] as! [String : Any], templateType: FCPListTemplateTypes.DEFAULT)
+ break
+ default:
+ result(false)
+ return
+ }
+
+ SwiftFlutterCarplayPlugin.rootTemplate = rootTemplate!.get
+ if !(SwiftFlutterCarplayPlugin.templateStack.isEmpty ?? true) {
+ SwiftFlutterCarplayPlugin.templateStack[0] = rootTemplate!
+ } else {
+ SwiftFlutterCarplayPlugin.templateStack = [rootTemplate!]
+ }
+ SwiftFlutterCarplayPlugin.objcRootTemplate = rootTemplate!
+ let animated = args["animated"] as! Bool
+ SwiftFlutterCarplayPlugin.animated = animated
+ result(true)
+ break
+ case FCPChannelTypes.forceUpdateRootTemplate:
+ FlutterCarPlaySceneDelegate.forceUpdateRootTemplate()
+ result(true)
+ break
+ case FCPChannelTypes.updateListTemplateSections:
+ guard let args = call.arguments as? [String : Any] else {
+ result(false)
+ return
+ }
+ let elementId = args["elementId"] as! String
+ let sections = (args["sections"] as! Array<[String: Any]>).map {
+ FCPListSection(obj: $0)
+ }
+ FlutterCarPlaySceneDelegate.updateListTemplateSections(elementId: elementId, sections: sections)
+ result(true)
+ break
+ case FCPChannelTypes.updateTabBarTemplates:
+ guard let args = call.arguments as? [String : Any] else {
+ result(false)
+ return
+ }
+ let elementId = args["elementId"] as! String
+ let templates = args["templates"] as! Array<[String: Any]>
+ if templates.count > CPTabBarTemplate.maximumTabCount {
+ result(FlutterError(code: "ERROR",
+ message: "CarPlay cannot have more than \(CPTabBarTemplate.maximumTabCount) templates on one screen.",
+ details: nil))
+ return
+ }
+ FlutterCarPlaySceneDelegate.updateTabBarTemplates(elementId: elementId, templates: templates)
+ result(true)
+ break
+ case FCPChannelTypes.updateListItem:
+ guard let args = call.arguments as? [String : Any] else {
+ result(false)
+ return
+ }
+ let elementId = args["_elementId"] as! String
+ let text = args["text"] as? String
+ let detailText = args["detailText"] as? String
+ let image = args["image"] as? String
+ let playbackProgress = args["playbackProgress"] as? CGFloat
+ let isPlaying = args["isPlaying"] as? Bool
+ let playingIndicatorLocation = args["playingIndicatorLocation"] as? String
+ let accessoryType = args["accessoryType"] as? String
+ SwiftFlutterCarplayPlugin.findItem(elementId: elementId, actionWhenFound: { item in
+ item.update(text: text, detailText: detailText, image: image, playbackProgress: playbackProgress, isPlaying: isPlaying, playingIndicatorLocation: playingIndicatorLocation, accessoryType: accessoryType)
+ })
+ result(true)
+ break
+ case FCPChannelTypes.onListItemSelectedComplete:
+ guard let args = call.arguments as? String else {
+ result(false)
+ return
+ }
+ SwiftFlutterCarplayPlugin.findItem(elementId: args, actionWhenFound: { item in
+ item.stopHandler()
+ })
+ result(true)
+ break
+ case FCPChannelTypes.setAlert:
+ guard self.objcPresentTemplate == nil else {
+ result(FlutterError(code: "ERROR",
+ message: "CarPlay can only present one modal template at a time.",
+ details: nil))
+ return
+ }
+ guard let args = call.arguments as? [String : Any] else {
+ result(false)
+ return
+ }
+ let alertTemplate = FCPAlertTemplate.init(obj: args["rootTemplate"] as! [String : Any])
+ self.objcPresentTemplate = alertTemplate
+ let animated = args["animated"] as! Bool
+ FlutterCarPlaySceneDelegate
+ .presentTemplate(template: alertTemplate.get, animated: animated, onPresent: { completed in
+ FCPStreamHandlerPlugin.sendEvent(type: FCPChannelTypes.onPresentStateChanged,
+ data: ["completed": completed])
+ })
+ result(true)
+ break
+ case FCPChannelTypes.setActionSheet:
+ guard self.objcPresentTemplate == nil else {
+ result(FlutterError(code: "ERROR",
+ message: "CarPlay can only present one modal template at a time.",
+ details: nil))
+ return
+ }
+ guard let args = call.arguments as? [String : Any] else {
+ result(false)
+ return
+ }
+ let actionSheetTemplate = FCPActionSheetTemplate.init(obj: args["rootTemplate"] as! [String : Any])
+ self.objcPresentTemplate = actionSheetTemplate
+ let animated = args["animated"] as! Bool
+ FlutterCarPlaySceneDelegate.presentTemplate(template: actionSheetTemplate.get, animated: animated, onPresent: {_ in })
+ result(true)
+ break
+ case FCPChannelTypes.popTemplate:
+ guard let args = call.arguments as? [String : Any],
+ SwiftFlutterCarplayPlugin.templateStack.count >= 2 else {
+ result(false)
+ return
+ }
+ for _ in 1...(args["count"] as! Int) {
+ FlutterCarPlaySceneDelegate.pop(animated: args["animated"] as! Bool)
+ }
+ result(true)
+ break
+ case FCPChannelTypes.closePresent:
+ guard let animated = call.arguments as? Bool else {
+ result(false)
+ return
+ }
+ FlutterCarPlaySceneDelegate.closePresent(animated: animated)
+ self.objcPresentTemplate = nil
+ result(true)
+ break
+ case FCPChannelTypes.showNowPlaying:
+ guard let animated = call.arguments as? Bool else {
+ result(false)
+ return
+ }
+ let template = FCPSharedNowPlayingTemplate()
+
+ let isCompleted = FlutterCarPlaySceneDelegate.pushIfNotExist(template: template.get as CPTemplate, animated: animated)
+ if isCompleted {
+ SwiftFlutterCarplayPlugin.templateStack.append(template)
+ result(true)
+ } else {
+ result(false)
+ }
+ break
+ case FCPChannelTypes.pushTemplate:
+ guard let args = call.arguments as? [String : Any] else {
+ result(false)
+ return
+ }
+ var template: FCPRootTemplate?
+ let animated = args["animated"] as! Bool
+ switch args["runtimeType"] as! String {
+ case String(describing: FCPGridTemplate.self):
+ template = FCPGridTemplate(obj: args["template"] as! [String : Any])
+ break
+ case String(describing: FCPPointOfInterestTemplate.self):
+ template = FCPPointOfInterestTemplate(obj: args["template"] as! [String : Any])
+ break
+ case String(describing: FCPInformationTemplate.self):
+ template = FCPInformationTemplate(obj: args["template"] as! [String : Any])
+ break
+ case String(describing: FCPListTemplate.self):
+ template = FCPListTemplate(obj: args["template"] as! [String : Any], templateType: FCPListTemplateTypes.DEFAULT)
+ break
+ default:
+ result(false)
+ return
+ }
+
+ let isCompleted = FlutterCarPlaySceneDelegate.push(template: template!.get, animated: animated)
+ if isCompleted {
+ SwiftFlutterCarplayPlugin.templateStack.append(template!)
+ result(true)
+ } else {
+ result(false)
+ }
+ break
+ case FCPChannelTypes.popToRootTemplate:
+ guard let animated = call.arguments as? Bool,
+ SwiftFlutterCarplayPlugin.templateStack.count >= 2 else {
+ result(false)
+ return
+ }
+
+ FlutterCarPlaySceneDelegate.popToRootTemplate(animated: animated)
+ self.objcPresentTemplate = nil
+ result(true)
+ break
+ default:
+ result(false)
+ break
+ }
+ }
+
+ static func createEventChannel(event: String?) -> FlutterEventChannel {
+ let eventChannel = FlutterEventChannel(name: makeFCPChannelId(event: event),
+ binaryMessenger: SwiftFlutterCarplayPlugin.registrar!.messenger())
+ return eventChannel
+ }
+
+ static func onCarplayConnectionChange(status: String) {
+ FCPStreamHandlerPlugin.sendEvent(type: FCPChannelTypes.onCarplayConnectionChange,
+ data: ["status": status])
+ }
+
+ static func findItem(elementId: String, actionWhenFound: (_ item: FCPListItem) -> Void) {
+ var collected: [FCPListTemplate] = []
+
+ for template in SwiftFlutterCarplayPlugin.templateStack {
+ if let tabBar = template as? FCPTabBarTemplate {
+ for child in tabBar.getTemplates() {
+ if let listTemplate = child as? FCPListTemplate {
+ collected.append(listTemplate)
+ }
+ }
+ } else if let list = template as? FCPListTemplate {
+ collected.append(list)
+ }
+ }
+
+ for t in collected {
+ for s in t.getSections() {
+ for i in s.getItems() {
+ if (i.elementId == elementId) {
+ actionWhenFound(i)
+ return
+ }
+ }
+ }
+ }
+ NSLog("FCP: Item not found with elementId: \(elementId)")
+ }
+
+ static public func getTemplateFromHistory(elementId: String) -> FCPRootTemplate? {
+ for i in 0..<SwiftFlutterCarplayPlugin.templateStack.count {
+ if SwiftFlutterCarplayPlugin.templateStack[i].elementId == elementId {
+ return SwiftFlutterCarplayPlugin.templateStack[i]
+ }
+
+ if let tabBar = SwiftFlutterCarplayPlugin.templateStack[i] as? FCPTabBarTemplate {
+ let subTemplates = tabBar.getTemplates()
+ for j in 0..<subTemplates.count {
+ if subTemplates[j].elementId == elementId {
+ return subTemplates[j] as? FCPRootTemplate
+ }
+ }
+ }
+ }
+ return nil
+ }
+}
diff --git a/packages/flutter_carplay/ios/Classes/models/FCPSharedNowPlayingTemplate.swift b/packages/flutter_carplay/ios/Classes/models/FCPSharedNowPlayingTemplate.swift
new file mode 100644
index 00000000..5e2e0e6a
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/models/FCPSharedNowPlayingTemplate.swift
@@ -0,0 +1,24 @@
+//
+// FCPSharedNowPlaying.swift
+// flutter_carplay
+//
+// Created by Koen Van Looveren on 16/09/2022.
+//
+
+import CarPlay
+
+@available(iOS 14.0, *)
+class FCPSharedNowPlayingTemplate {
+ var get: CPTemplate {
+ return CPNowPlayingTemplate.shared
+ }
+
+ init() {}
+}
+
+@available(iOS 14.0, *)
+extension FCPSharedNowPlayingTemplate: FCPRootTemplate {
+ var elementId: String {
+ return "FCPSharedNowPlayingTemplate"
+ }
+}
diff --git a/packages/flutter_carplay/ios/Classes/models/action_sheet/FCPActionSheetTemplate.swift b/packages/flutter_carplay/ios/Classes/models/action_sheet/FCPActionSheetTemplate.swift
new file mode 100644
index 00000000..852967e0
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/models/action_sheet/FCPActionSheetTemplate.swift
@@ -0,0 +1,40 @@
+//
+// FCPActionSheetTemplate.swift
+// flutter_carplay
+//
+// Created by Oğuzhan Atalay on 25.08.2021.
+//
+
+import CarPlay
+
+@available(iOS 14.0, *)
+class FCPActionSheetTemplate {
+ private(set) var _super: CPActionSheetTemplate?
+ private(set) var elementId: String
+ private var title: String?
+ private var message: String?
+ private var actions: [CPAlertAction]
+ private var objcActions: [FCPAlertAction]
+
+ init(obj: [String : Any]) {
+ self.elementId = obj["_elementId"] as! String
+ self.title = obj["title"] as? String
+ self.message = obj["message"] as? String
+ self.objcActions = (obj["actions"] as! Array<[String : Any]>).map {
+ FCPAlertAction(obj: $0, type: FCPAlertActionTypes.ACTION_SHEET)
+ }
+ self.actions = self.objcActions.map {
+ $0.get
+ }
+ }
+
+ var get: CPActionSheetTemplate {
+ let actionSheetTemplate = CPActionSheetTemplate.init(title: self.title, message: self.message, actions: self.actions)
+ actionSheetTemplate.elementId = self.elementId
+ self._super = actionSheetTemplate
+ return actionSheetTemplate
+ }
+}
+
+@available(iOS 14.0, *)
+extension FCPActionSheetTemplate: FCPPresentTemplate { }
diff --git a/packages/flutter_carplay/ios/Classes/models/alert/FCPAlertAction.swift b/packages/flutter_carplay/ios/Classes/models/alert/FCPAlertAction.swift
new file mode 100644
index 00000000..88f3b6d1
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/models/alert/FCPAlertAction.swift
@@ -0,0 +1,39 @@
+//
+// FCPAlertAction.swift
+// flutter_carplay
+//
+// Created by Oğuzhan Atalay on 21.08.2021.
+//
+
+import CarPlay
+
+@available(iOS 14.0, *)
+class FCPAlertAction {
+ private(set) var _super: CPAlertAction?
+ private(set) var elementId: String
+ private var title: String
+ private var style: CPAlertAction.Style
+ private var handlerType: FCPAlertActionTypes
+
+ init(obj: [String : Any], type: FCPAlertActionTypes) {
+ self.elementId = obj["_elementId"] as! String
+ self.title = obj["title"] as! String
+ let style = obj["style"] as! String
+ self.style = style.elementsEqual("normal")
+ ? CPAlertAction.Style.default
+ : style.elementsEqual("destructive")
+ ? CPAlertAction.Style.destructive
+ : CPAlertAction.Style.cancel
+ self.handlerType = type
+ }
+
+ var get: CPAlertAction {
+ let alertAction = CPAlertAction.init(title: title, style: style, handler: { _ in
+ DispatchQueue.main.async {
+ FCPStreamHandlerPlugin.sendEvent(type: FCPChannelTypes.onAlertActionPressed, data: ["elementId": self.elementId])
+ }
+ })
+ self._super = alertAction
+ return alertAction
+ }
+}
diff --git a/packages/flutter_carplay/ios/Classes/models/alert/FCPAlertTemplate.swift b/packages/flutter_carplay/ios/Classes/models/alert/FCPAlertTemplate.swift
new file mode 100644
index 00000000..c1fb75c7
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/models/alert/FCPAlertTemplate.swift
@@ -0,0 +1,38 @@
+//
+// FCPAlertTemplate.swift
+// flutter_carplay
+//
+// Created by Oğuzhan Atalay on 21.08.2021.
+//
+
+import CarPlay
+
+@available(iOS 14.0, *)
+class FCPAlertTemplate {
+ private(set) var _super: CPAlertTemplate?
+ private(set) var elementId: String
+ private var titleVariants: [String]
+ private var actions: [CPAlertAction]
+ private var objcActions: [FCPAlertAction]
+
+ init(obj: [String : Any]) {
+ self.elementId = obj["_elementId"] as! String
+ self.titleVariants = obj["titleVariants"] as! [String]
+ self.objcActions = (obj["actions"] as! Array<[String : Any]>).map {
+ FCPAlertAction(obj: $0, type: FCPAlertActionTypes.ALERT)
+ }
+ self.actions = self.objcActions.map {
+ $0.get
+ }
+ }
+
+ var get: CPAlertTemplate {
+ let alertTemplate = CPAlertTemplate.init(titleVariants: titleVariants, actions: actions)
+ alertTemplate.elementId = self.elementId
+ self._super = alertTemplate
+ return alertTemplate
+ }
+}
+
+@available(iOS 14.0, *)
+extension FCPAlertTemplate: FCPPresentTemplate { }
diff --git a/packages/flutter_carplay/ios/Classes/models/button/FCPBarButton.swift b/packages/flutter_carplay/ios/Classes/models/button/FCPBarButton.swift
new file mode 100644
index 00000000..a5f87d46
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/models/button/FCPBarButton.swift
@@ -0,0 +1,38 @@
+//
+// FCPBarButton.swift
+// flutter_carplay
+//
+// Created by Oğuzhan Atalay on 25.08.2021.
+//
+
+import CarPlay
+
+@available(iOS 14.0, *)
+class FCPBarButton {
+ private(set) var _super: CPBarButton?
+ private(set) var elementId: String
+ private var title: String
+ private var style: CPBarButtonStyle
+
+ init(obj: [String : Any]) {
+ self.elementId = obj["_elementId"] as! String
+ self.title = obj["title"] as! String
+ let style = obj["style"] as? String
+ if style == nil || style == "rounded" {
+ self.style = CPBarButtonStyle.rounded
+ } else {
+ self.style = CPBarButtonStyle.none
+ }
+ }
+
+ var get: CPBarButton {
+ let barButton = CPBarButton.init(title: title, handler: { _ in
+ DispatchQueue.main.async {
+ FCPStreamHandlerPlugin.sendEvent(type: FCPChannelTypes.onBarButtonPressed, data: ["elementId": self.elementId])
+ }
+ })
+ barButton.buttonStyle = self.style
+ self._super = barButton
+ return barButton
+ }
+}
diff --git a/packages/flutter_carplay/ios/Classes/models/button/FCPTextButton.swift b/packages/flutter_carplay/ios/Classes/models/button/FCPTextButton.swift
new file mode 100644
index 00000000..8a3c2c59
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/models/button/FCPTextButton.swift
@@ -0,0 +1,47 @@
+//
+// FCPTextButton.swift
+// Runner
+//
+// Created by Olaf Schneider on 17.02.22.
+//
+
+import CarPlay
+
+@available(iOS 14.0, *)
+class FCPTextButton {
+ private(set) var _super: CPTextButton?
+ private(set) var elementId: String
+ private var title: String
+ private var style: CPTextButtonStyle
+
+ init(obj: [String : Any]) {
+ self.elementId = obj["_elementId"] as! String
+ self.title = obj["title"] as! String
+ let style = obj["style"] as? String
+ if style == nil || style == "normal" {
+ self.style = CPTextButtonStyle.normal
+ } else {
+ if style == "cancel"{
+ self.style = CPTextButtonStyle.cancel
+ }
+ else {
+ if style == "confirm"{
+ self.style = CPTextButtonStyle.confirm
+ }
+ else {
+ self.style = CPTextButtonStyle.normal
+ }
+ }
+ }
+ }
+
+ var get: CPTextButton {
+ let textButton = CPTextButton.init(title: title, textStyle:self.style, handler: { _ in
+ DispatchQueue.main.async {
+ FCPStreamHandlerPlugin.sendEvent(type: FCPChannelTypes.onTextButtonPressed, data: ["elementId": self.elementId])
+ }
+ })
+ self._super = textButton
+ return textButton
+ }
+}
diff --git a/packages/flutter_carplay/ios/Classes/models/grid/FCPGridButton.swift b/packages/flutter_carplay/ios/Classes/models/grid/FCPGridButton.swift
new file mode 100644
index 00000000..0058c342
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/models/grid/FCPGridButton.swift
@@ -0,0 +1,59 @@
+//
+// FCPGridButton.swift
+// flutter_carplay
+//
+// Created by Oğuzhan Atalay on 21.08.2021.
+//
+
+import CarPlay
+
+@available(iOS 14.0, *)
+class FCPGridButton {
+ private(set) var _super: CPGridButton?
+ private(set) var elementId: String
+ private var titleVariants: [String]
+ private var image: String
+
+ init(obj: [String : Any]) {
+ self.elementId = obj["_elementId"] as! String
+ self.titleVariants = obj["titleVariants"] as! [String]
+ self.image = obj["image"] as! String
+ }
+
+ var get: CPGridButton {
+ var gridButton: CPGridButton!
+ let image: UIImage
+ let imageSource = self.image.toImageSource()
+
+ if #available(iOS 26.0, *) {
+ image = makeSafeUIPlaceholder()
+ } else {
+ image = makeUIImage(from: imageSource)
+ }
+
+ gridButton = CPGridButton(
+ titleVariants: self.titleVariants,
+ image: image,
+ handler: { _ in
+ DispatchQueue.main.async {
+ FCPStreamHandlerPlugin.sendEvent(
+ type: FCPChannelTypes.onGridButtonPressed,
+ data: ["elementId": self.elementId]
+ )
+ }
+ }
+ )
+
+ if #available(iOS 26.0, *) {
+ loadUIImageAsync(from: imageSource) { uiImage in
+ if let uiImage = uiImage {
+ gridButton.perform(Selector("updateImage:"), with: uiImage)
+ }
+ }
+ }
+
+ gridButton.isEnabled = true
+ self._super = gridButton
+ return gridButton
+ }
+}
diff --git a/packages/flutter_carplay/ios/Classes/models/grid/FCPGridTemplate.swift b/packages/flutter_carplay/ios/Classes/models/grid/FCPGridTemplate.swift
new file mode 100644
index 00000000..cfcd07be
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/models/grid/FCPGridTemplate.swift
@@ -0,0 +1,38 @@
+//
+// FCPGridTemplate.swift
+// flutter_carplay
+//
+// Created by Oğuzhan Atalay on 21.08.2021.
+//
+
+import CarPlay
+
+@available(iOS 14.0, *)
+class FCPGridTemplate {
+ private(set) var _super: CPGridTemplate?
+ private(set) var elementId: String
+ private var title: String
+ private var buttons: [CPGridButton]
+ private var objcButtons: [FCPGridButton]
+
+ init(obj: [String : Any]) {
+ self.elementId = obj["_elementId"] as! String
+ self.title = obj["title"] as! String
+ self.objcButtons = (obj["buttons"] as! Array<[String : Any]>).map {
+ FCPGridButton(obj: $0)
+ }
+ self.buttons = self.objcButtons.map {
+ $0.get
+ }
+ }
+
+ var get: CPTemplate {
+ let gridTemplate = CPGridTemplate.init(title: self.title, gridButtons: self.buttons)
+ gridTemplate.elementId = self.elementId
+ self._super = gridTemplate
+ return gridTemplate
+ }
+}
+
+@available(iOS 14.0, *)
+extension FCPGridTemplate: FCPRootTemplate { }
diff --git a/packages/flutter_carplay/ios/Classes/models/information/FCPInformationItem.swift b/packages/flutter_carplay/ios/Classes/models/information/FCPInformationItem.swift
new file mode 100644
index 00000000..e815d9fa
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/models/information/FCPInformationItem.swift
@@ -0,0 +1,31 @@
+//
+// FCPPointOfInterestTemplate.swift
+// flutter_carplay
+//
+// Created by Olaf Schneider on 17.02.22.
+//
+
+import CarPlay
+
+@available(iOS 14.0, *)
+class FCPInformationItem {
+ private(set) var _super: CPInformationItem?
+ private(set) var elementId: String
+ private var title: String?
+ private var detail: String?
+
+
+
+ init(obj: [String : Any]) {
+ self.elementId = obj["_elementId"] as! String
+ self.title = obj["title"] as? String
+ self.detail = obj["detail"] as? String
+ }
+
+ var get: CPInformationItem {
+ let informationItem = CPInformationItem.init(title: self.title, detail: self.detail)
+ self._super = informationItem
+ return informationItem
+ }
+}
+
diff --git a/packages/flutter_carplay/ios/Classes/models/information/FCPInformationTemplate.swift b/packages/flutter_carplay/ios/Classes/models/information/FCPInformationTemplate.swift
new file mode 100644
index 00000000..22efdd07
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/models/information/FCPInformationTemplate.swift
@@ -0,0 +1,55 @@
+//
+// FCPPointOfInterestTemplate.swift
+// flutter_carplay
+//
+// Created by Olaf Schneider on 15.02.22.
+//
+
+import CarPlay
+
+@available(iOS 14.0, *)
+class FCPInformationTemplate {
+ private(set) var _super: CPInformationTemplate?
+ private(set) var elementId: String
+ private var title: String
+ private var layout: CPInformationTemplateLayout
+
+ private var informationItems: [CPInformationItem]
+ private var objcInformationItems: [FCPInformationItem]
+
+ private var actions: [CPTextButton]
+ private var objcActions: [FCPTextButton]
+
+ init(obj: [String : Any]) {
+ self.elementId = obj["_elementId"] as! String
+
+ self.layout = obj["layout"] as! String == "twoColumn"
+ ? CPInformationTemplateLayout.twoColumn
+ : CPInformationTemplateLayout.leading
+
+ self.title = obj["title"] as! String
+
+ self.objcInformationItems = (obj["informationItems"] as! Array<[String : Any]>).map {
+ FCPInformationItem(obj: $0)
+ }
+ self.informationItems = self.objcInformationItems.map {
+ $0.get
+ }
+
+ self.objcActions = (obj["actions"] as! Array<[String : Any]>).map {
+ FCPTextButton(obj: $0)
+ }
+ self.actions = self.objcActions.map {
+ $0.get
+ }
+
+ }
+
+ var get: CPTemplate {
+ let informationTemplate = CPInformationTemplate.init(title: self.title,layout:self.layout,items:informationItems,actions:actions);
+ informationTemplate.elementId = self.elementId
+ return informationTemplate
+ }
+}
+@available(iOS 14.0, *)
+extension FCPInformationTemplate: FCPRootTemplate { }
diff --git a/packages/flutter_carplay/ios/Classes/models/list/FCPListItem.swift b/packages/flutter_carplay/ios/Classes/models/list/FCPListItem.swift
new file mode 100644
index 00000000..a95ee377
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/models/list/FCPListItem.swift
@@ -0,0 +1,156 @@
+//
+// FCPListItem.swift
+// flutter_carplay
+//
+// Created by Oğuzhan Atalay on 21.08.2021.
+//
+
+import CarPlay
+
+@available(iOS 14.0, *)
+class FCPListItem {
+ private(set) var _super: CPListItem?
+ private(set) var elementId: String
+ private var text: String
+ private var detailText: String?
+ private var isOnPressListenerActive: Bool = false
+ private var completeHandler: (() -> Void)?
+ private var image: String?
+ private var playbackProgress: CGFloat?
+ private var isPlaying: Bool?
+ private var playingIndicatorLocation: CPListItemPlayingIndicatorLocation?
+ private var accessoryType: CPListItemAccessoryType?
+
+ init(obj: [String : Any]) {
+ self.elementId = obj["_elementId"] as! String
+ self.text = obj["text"] as! String
+ self.detailText = obj["detailText"] as? String
+ self.isOnPressListenerActive = obj["onPress"] as? Bool ?? false
+ self.image = obj["image"] as? String
+ self.playbackProgress = obj["playbackProgress"] as? CGFloat
+ self.isPlaying = obj["isPlaying"] as? Bool
+ self.setPlayingIndicatorLocation(fromString: obj["playingIndicatorLocation"] as? String)
+ self.setAccessoryType(fromString: obj["accessoryType"] as? String)
+ }
+
+ private func handler(selectedItem: CPSelectableListItem, complete: @escaping () -> Void) {
+ if isOnPressListenerActive {
+ completeHandler = complete
+
+ DispatchQueue.main.async {
+ FCPStreamHandlerPlugin.sendEvent(
+ type: FCPChannelTypes.onListItemSelected,
+ data: ["elementId": self.elementId]
+ )
+ }
+ } else {
+ complete()
+ }
+ }
+
+ var get: CPListItem {
+ let listItem = CPListItem.init(text: text, detailText: detailText)
+ listItem.handler = self.handler
+ if image != nil {
+ listItem.setImage(makeSafeUIPlaceholder())
+ let imageSource = self.image!.toImageSource()
+ loadUIImageAsync(from: imageSource) { uiImage in
+ if let uiImage = uiImage {
+ listItem.setImage(uiImage)
+ }
+ }
+ }
+ if playbackProgress != nil {
+ listItem.playbackProgress = playbackProgress!
+ }
+ if isPlaying != nil {
+ listItem.isPlaying = isPlaying!
+ }
+ if playingIndicatorLocation != nil {
+ listItem.playingIndicatorLocation = playingIndicatorLocation!
+ }
+ if accessoryType != nil {
+ listItem.accessoryType = accessoryType!
+ }
+ self._super = listItem
+ return listItem
+ }
+
+ public func stopHandler() {
+ guard self.completeHandler != nil else {
+ return
+ }
+ self.completeHandler!()
+ self.completeHandler = nil
+ }
+
+ public func update(text: String?, detailText: String?, image: String?, playbackProgress: CGFloat?, isPlaying: Bool?, playingIndicatorLocation: String?, accessoryType: String?) {
+ if text != nil {
+ self._super?.setText(text!)
+ self.text = text!
+ }
+ if detailText != nil {
+ self._super?.setDetailText(detailText)
+ self.detailText = detailText
+ }
+
+ if let image = image, image != self.image {
+ self._super?.setImage(makeSafeUIPlaceholder())
+ let imageSource = image.toImageSource()
+ loadUIImageAsync(from: imageSource) { uiImage in
+ if let uiImage = uiImage {
+ self._super?.setImage(uiImage)
+ }
+ }
+ self.image = image
+ } else if image == nil {
+ self.image = nil
+ self._super?.setImage(nil)
+ }
+
+ if playbackProgress != nil {
+ self._super?.playbackProgress = playbackProgress!
+ self.playbackProgress = playbackProgress
+ }
+ if isPlaying != nil {
+ self._super?.isPlaying = isPlaying!
+ self.isPlaying = isPlaying
+ }
+ if playingIndicatorLocation != nil {
+ self.setPlayingIndicatorLocation(fromString: playingIndicatorLocation)
+ if self.playingIndicatorLocation != nil {
+ self._super?.playingIndicatorLocation = self.playingIndicatorLocation!
+ }
+ }
+ if accessoryType != nil {
+ self.setAccessoryType(fromString: accessoryType)
+ if self.accessoryType != nil {
+ self._super?.accessoryType = self.accessoryType!
+ }
+ }
+ }
+
+ private func setPlayingIndicatorLocation(fromString: String?) {
+ if fromString == "leading" {
+ self.playingIndicatorLocation = CPListItemPlayingIndicatorLocation.leading
+ } else if fromString == "trailing" {
+ self.playingIndicatorLocation = CPListItemPlayingIndicatorLocation.trailing
+ }
+ }
+
+ private func setAccessoryType(fromString: String?) {
+ if fromString == "cloud" {
+ self.accessoryType = CPListItemAccessoryType.cloud
+ } else if fromString == "disclosureIndicator" {
+ self.accessoryType = CPListItemAccessoryType.disclosureIndicator
+ } else {
+ self.accessoryType = CPListItemAccessoryType.none
+ }
+ }
+
+ public func merge(with: FCPListItem) -> FCPListItem {
+ with._super = self._super
+ with._super?.handler = with.handler
+ return with;
+ }
+}
diff --git a/packages/flutter_carplay/ios/Classes/models/list/FCPListSection.swift b/packages/flutter_carplay/ios/Classes/models/list/FCPListSection.swift
new file mode 100644
index 00000000..01d913d1
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/models/list/FCPListSection.swift
@@ -0,0 +1,71 @@
+//
+// FCPListSection.swift
+// flutter_carplay
+//
+// Created by Oğuzhan Atalay on 21.08.2021.
+//
+
+import CarPlay
+
+@available(iOS 14.0, *)
+class FCPListSection {
+ private(set) var _super: CPListSection?
+ private(set) var elementId: String
+ private var header: String?
+ private var items: [CPListTemplateItem]
+ private var objcItems: [FCPListItem]
+ private var sectionIndexEnabled: Bool
+
+ init(obj: [String : Any], sectionIndexEnabled: Bool = true) {
+ self.elementId = obj["_elementId"] as! String
+ self.header = obj["header"] as? String
+ self.sectionIndexEnabled = sectionIndexEnabled
+ self.objcItems = (obj["items"] as! Array<[String : Any]>).map {
+ FCPListItem(obj: $0)
+ }
+ self.items = self.objcItems.map {
+ $0.get
+ }
+ }
+
+ var get: CPListSection {
+ let indexTitle = sectionIndexEnabled ? header : nil
+ let listSection = CPListSection.init(items: items, header: header, sectionIndexTitle: indexTitle)
+ self._super = listSection
+ return listSection
+ }
+
+ public func getItems() -> [FCPListItem] {
+ return objcItems
+ }
+
+ public func merge(with: FCPListSection) -> FCPListSection {
+ let copy = with
+ self.updateItems(items: copy.objcItems)
+ copy._super = self._super
+ copy.objcItems = self.objcItems;
+ copy.items = self.items;
+ return copy;
+ }
+
+ public func updateItems(items: [FCPListItem]) {
+ let fcpListTemplateItem: [String: FCPListItem] = Dictionary(uniqueKeysWithValues: self.objcItems.map { ($0.elementId, $0) })
+ let cpListTemplateItem = Dictionary(uniqueKeysWithValues: zip(self.objcItems.map { $0.elementId }, self.items))
+
+ /// Keep Flutter CarPlay object if necessary, use new instance.
+ self.objcItems = items.map { item in
+ if let existing = fcpListTemplateItem[item.elementId] {
+ return existing.merge(with: item) // Merge old instance with newest to keep some data (eg: completeHandler)
+ } else {
+ return item // Use new instance
+ }
+ }
+ self.items = items.map { item in
+ if let existing = cpListTemplateItem[item.elementId] {
+ return existing // Reuse existing CP template
+ } else {
+ return item.get // New CP template
+ }
+ }
+ }
+}
diff --git a/packages/flutter_carplay/ios/Classes/models/list/FCPListTemplate.swift b/packages/flutter_carplay/ios/Classes/models/list/FCPListTemplate.swift
new file mode 100644
index 00000000..8cd8ce30
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/models/list/FCPListTemplate.swift
@@ -0,0 +1,100 @@
+//
+// FCPListTemplate.swift
+// flutter_carplay
+//
+// Created by Oğuzhan Atalay on 21.08.2021.
+//
+
+import CarPlay
+
+@available(iOS 14.0, *)
+class FCPListTemplate {
+ private(set) var _super: CPListTemplate?
+ private(set) var elementId: String
+ private var title: String?
+ private var systemIcon: String
+ private var sections: [CPListSection] = []
+ private var objcSections: [FCPListSection] = []
+ private var emptyViewTitleVariants: [String] = []
+ private var emptyViewSubtitleVariants: [String] = []
+ private var showsTabBadge: Bool = false
+ private var templateType: FCPListTemplateTypes
+ private var objcBackButton: FCPBarButton?
+ private var backButton: CPBarButton?
+ private var sectionIndexEnabled: Bool = true
+
+ init(obj: [String : Any], templateType: FCPListTemplateTypes) {
+ self.elementId = obj["_elementId"] as! String
+ self.title = obj["title"] as? String
+ self.systemIcon = obj["systemIcon"] as! String
+ self.emptyViewTitleVariants = obj["emptyViewTitleVariants"] as? [String] ?? []
+ self.emptyViewSubtitleVariants = obj["emptyViewSubtitleVariants"] as? [String] ?? []
+ self.showsTabBadge = obj["showsTabBadge"] as! Bool
+ self.sectionIndexEnabled = obj["sectionIndexEnabled"] as? Bool ?? true
+ self.templateType = templateType
+ self.objcSections = (obj["sections"] as! Array<[String : Any]>).map {
+ FCPListSection(obj: $0, sectionIndexEnabled: self.sectionIndexEnabled)
+ }
+ self.sections = self.objcSections.map {
+ $0.get
+ }
+ let backButtonData = obj["backButton"] as? [String : Any]
+ if backButtonData != nil {
+ self.objcBackButton = FCPBarButton(obj: backButtonData!)
+ self.backButton = self.objcBackButton?.get
+ }
+ }
+
+ var get: CPTemplate {
+ let listTemplate = CPListTemplate.init(title: title, sections: sections)
+ listTemplate.emptyViewTitleVariants = emptyViewTitleVariants
+ listTemplate.emptyViewSubtitleVariants = emptyViewSubtitleVariants
+ listTemplate.showsTabBadge = showsTabBadge
+ listTemplate.tabImage = UIImage(systemName: systemIcon)
+ if (templateType == FCPListTemplateTypes.DEFAULT) {
+ listTemplate.backButton = self.backButton
+ }
+ listTemplate.elementId = self.elementId
+ self._super = listTemplate
+ return listTemplate
+ }
+
+ public func getSections() -> [FCPListSection] {
+ return objcSections
+ }
+
+ public func merge(with: FCPListTemplate) -> FCPListTemplate {
+ let copy = with
+ self.updateSections(sections: copy.objcSections)
+ copy._super = self._super
+ copy.objcSections = self.objcSections
+ copy.sections = self.sections
+ return copy;
+ }
+
+ public func updateSections(sections: [FCPListSection]) {
+ let fcpSectionsMap: [String: FCPListSection] = Dictionary(uniqueKeysWithValues: self.objcSections.map { ($0.elementId, $0) })
+ let cpSectionsMap = Dictionary(uniqueKeysWithValues: zip(self.objcSections.map { $0.elementId }, self.sections))
+
+ /// Keep Flutter CarPlay object if necessary, use new instance.
+ self.objcSections = sections.map { section in
+ if let existing = fcpSectionsMap[section.elementId] {
+ return existing.merge(with: section) // Merge old instance with newest to keep some data (eg: completeHandler)
+ } else {
+ return section // Use new instance
+ }
+ }
+ self.sections = sections.map { section in
+ if let existing = cpSectionsMap[section.elementId] {
+ return existing // Reuse existing CP template
+ } else {
+ return section.get // New CP template
+ }
+ }
+
+ _super?.updateSections(self.sections)
+ }
+}
+
+@available(iOS 14.0, *)
+extension FCPListTemplate: FCPRootTemplate { }
diff --git a/packages/flutter_carplay/ios/Classes/models/poi/FCPPointOfInterest.swift b/packages/flutter_carplay/ios/Classes/models/poi/FCPPointOfInterest.swift
new file mode 100644
index 00000000..17d70086
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/models/poi/FCPPointOfInterest.swift
@@ -0,0 +1,98 @@
+//
+// FCPPointOfInterest.swift
+// Runner
+//
+// Created by Olaf Schneider on 15.02.22.
+//
+
+import CarPlay
+
+@available(iOS 14.0, *)
+class FCPPointOfInterest {
+ private(set) var _super: CPPointOfInterest?
+ private(set) var elementId: String
+ private var latitude: Double
+ private var longitude: Double
+ private var title:String
+ private var subtitle:String?
+ private var summary:String?
+ private var detailTitle:String?
+ private var detailSubtitle:String?
+ private var detailSummary:String?
+ private var image:String?
+
+ private var primaryButton: CPTextButton?
+ private var objcPrimaryButton: FCPTextButton?
+
+ private var secondaryButton: CPTextButton?
+ private var objcSecondaryButton: FCPTextButton?
+
+
+
+ static let maxPinImageSize:CGFloat = 40
+
+ init(obj: [String : Any]) {
+ self.elementId = obj["_elementId"] as! String
+
+ let lat = obj["latitude"] as! NSNumber
+ self.latitude = lat.doubleValue
+
+ let lng = obj["longitude"] as! NSNumber
+ self.longitude = lng.doubleValue
+ self.title = obj["title"] as! String
+ self.subtitle = obj["subtitle"] as? String
+ self.summary = obj["summary"] as? String
+ self.detailTitle = obj["detailTitle"] as? String
+ self.detailSubtitle = obj["detailSubtitle"] as? String
+ self.detailSummary = obj["detailSummary"] as? String
+ self.image = obj["image"] as? String
+
+
+
+ let primaryButtonData = obj["primaryButton"] as? [String : Any]
+ if primaryButtonData != nil {
+ self.objcPrimaryButton = FCPTextButton(obj: primaryButtonData!);
+ self.primaryButton = self.objcPrimaryButton?.get
+
+ }
+
+
+ let secondaryButtonData = obj["secondaryButton"] as? [String : Any]
+ if secondaryButtonData != nil {
+ self.objcSecondaryButton = FCPTextButton(obj: secondaryButtonData!);
+ self.secondaryButton = self.objcSecondaryButton?.get
+ }
+ }
+
+ var get: CPPointOfInterest {
+
+ let location = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: latitude, longitude: longitude)))
+ var pinImage:UIImage? = nil;
+
+ if let image = self.image {
+ let key = SwiftFlutterCarplayPlugin.registrar?.lookupKey(forAsset: image)
+
+ pinImage = UIImage(named: key!)
+ if let pImage = pinImage {
+ if pImage.size.height > FCPPointOfInterest.maxPinImageSize ||
+ pImage.size.width > FCPPointOfInterest.maxPinImageSize {
+ pinImage = pImage.resizeImageTo(size: CGSize(width:FCPPointOfInterest.maxPinImageSize,height:FCPPointOfInterest.maxPinImageSize))
+ }
+ }
+ }
+ let poi = CPPointOfInterest(location:location,title:title,subtitle: subtitle,summary:summary,
+ detailTitle:detailTitle,detailSubtitle: detailSubtitle,
+ detailSummary: detailSummary,pinImage: pinImage);
+
+ if let primaryButton = self.primaryButton {
+ poi.primaryButton = primaryButton
+
+ }
+ if let secondaryButton = self.secondaryButton {
+ poi.secondaryButton = secondaryButton
+ }
+
+ self._super = poi
+ return poi
+ }
+}
diff --git a/packages/flutter_carplay/ios/Classes/models/poi/FCPPointOfInterestTemplate.swift b/packages/flutter_carplay/ios/Classes/models/poi/FCPPointOfInterestTemplate.swift
new file mode 100644
index 00000000..fa4e4eee
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/models/poi/FCPPointOfInterestTemplate.swift
@@ -0,0 +1,40 @@
+//
+// FCPPointOfInterestTemplate.swift
+// flutter_carplay
+//
+// Created by Olaf Schneider on 15.02.22.
+//
+
+import CarPlay
+
+@available(iOS 14.0, *)
+class FCPPointOfInterestTemplate {
+ private(set) var _super: CPPointOfInterestTemplate?
+ private(set) var elementId: String
+ private var title: String
+ private var poi: [FCPPointOfInterest]
+
+ init(obj: [String : Any]) {
+ self.elementId = obj["_elementId"] as! String
+ self.title = obj["title"] as! String
+ self.poi = (obj["poi"] as! Array<[String : Any]>).map {
+ FCPPointOfInterest(obj: $0)
+ }
+ }
+
+ var get: CPTemplate {
+ var pois: [CPPointOfInterest] = []
+
+ for p in poi{
+ pois.append(p.get);
+ }
+
+ let pointOfInterestTemplate = CPPointOfInterestTemplate.init(title: self.title,pointsOfInterest: pois, selectedIndex: NSNotFound)
+ pointOfInterestTemplate.elementId = self.elementId
+ self._super = pointOfInterestTemplate
+ return pointOfInterestTemplate
+ }
+}
+
+@available(iOS 14.0, *)
+extension FCPPointOfInterestTemplate: FCPRootTemplate { }
diff --git a/packages/flutter_carplay/ios/Classes/models/tabbar/FCPTabBarTemplate.swift b/packages/flutter_carplay/ios/Classes/models/tabbar/FCPTabBarTemplate.swift
new file mode 100644
index 00000000..93650225
--- /dev/null
+++ b/packages/flutter_carplay/ios/Classes/models/tabbar/FCPTabBarTemplate.swift
@@ -0,0 +1,144 @@
+//
+// FCPTabBarTemplate.swift
+// flutter_carplay
+//
+// Created by Oğuzhan Atalay on 21.08.2021.
+//
+
+import CarPlay
+
+@available(iOS 14.0, *)
+protocol FCPTabBarChildTemplate {
+ var elementId: String { get }
+ var get: CPTemplate { get }
+}
+
+@available(iOS 14.0, *)
+extension FCPListTemplate: FCPTabBarChildTemplate { }
+
+@available(iOS 14.0, *)
+extension FCPPointOfInterestTemplate: FCPTabBarChildTemplate { }
+
+@available(iOS 14.0, *)
+extension FCPGridTemplate: FCPTabBarChildTemplate { }
+
+@available(iOS 14.0, *)
+extension FCPInformationTemplate: FCPTabBarChildTemplate { }
+
+@available(iOS 14.0, *)
+protocol TemplateFactory {
+ func create(from data: [String: Any]) -> FCPTabBarChildTemplate?
+}
+
+@available(iOS 14.0, *)
+struct FCPListTemplateFactory: TemplateFactory {
+ func create(from data: [String: Any]) -> FCPTabBarChildTemplate? {
+ return FCPListTemplate(obj: data, templateType: FCPListTemplateTypes.PART_OF_GRID_TEMPLATE)
+ }
+}
+
+@available(iOS 14.0, *)
+struct FCPPointOfInterestTemplateFactory: TemplateFactory {
+ func create(from data: [String: Any]) -> FCPTabBarChildTemplate? {
+ return FCPPointOfInterestTemplate(obj: data)
+ }
+}
+
+@available(iOS 14.0, *)
+struct FCPGridTemplateFactory: TemplateFactory {
+ func create(from data: [String: Any]) -> FCPTabBarChildTemplate? {
+ return FCPGridTemplate(obj: data)
+ }
+}
+
+@available(iOS 14.0, *)
+struct FCPInformationTemplateFactory: TemplateFactory {
+ func create(from data: [String: Any]) -> FCPTabBarChildTemplate? {
+ return FCPInformationTemplate(obj: data)
+ }
+}
+
+@available(iOS 14.0, *)
+struct TemplateFactoryMapper {
+ private static let factories: [String: TemplateFactory] = [
+ String(describing: FCPListTemplate.self): FCPListTemplateFactory(),
+ String(describing: FCPPointOfInterestTemplate.self): FCPPointOfInterestTemplateFactory(),
+ String(describing: FCPGridTemplate.self): FCPGridTemplateFactory(),
+ String(describing: FCPInformationTemplate.self): FCPInformationTemplateFactory(),
+ ]
+
+ private static let defaultFactory: TemplateFactory = FCPListTemplateFactory()
+
+ static func getFactory(for typeKey: String) -> TemplateFactory {
+ return factories[typeKey] ?? defaultFactory
+ }
+}
+
+@available(iOS 14.0, *)
+class FCPTabBarTemplate {
+ private(set) var _super: CPTabBarTemplate?
+ private(set) var elementId: String
+ private var title: String?
+ private var templates: [CPTemplate]
+ private var objcTemplates: [FCPTabBarChildTemplate]
+
+ init(obj: [String : Any]) {
+ self.elementId = obj["_elementId"] as! String
+ self.title = obj["title"] as? String
+ self.objcTemplates = FCPTabBarTemplate.parseTemplates(obj["templates"] as! Array<[String: Any]>)
+ self.templates = self.objcTemplates.map { $0.get }
+ }
+
+
+ private static func parseTemplates(_ templatesData: Array<[String: Any]>) -> [FCPTabBarChildTemplate] {
+ return templatesData.compactMap { data in
+ let typeKey = data["runtimeType"] as? String ?? String(describing: FCPListTemplate.self)
+ return TemplateFactoryMapper.getFactory(for: typeKey).create(from: data)
+ }
+ }
+
+ var get: CPTemplate {
+ let tabBarTemplate = CPTabBarTemplate.init(templates: templates)
+ tabBarTemplate.tabTitle = title
+ tabBarTemplate.elementId = self.elementId
+ self._super = tabBarTemplate
+ return tabBarTemplate
+ }
+
+ public func getTemplates() -> [FCPTabBarChildTemplate] {
+ return objcTemplates
+ }
+
+ public func updateTemplates(newTemplatesData: Array<[String: Any]>) {
+ let existingTemplatesById: [String: FCPTabBarChildTemplate] = Dictionary(uniqueKeysWithValues: self.objcTemplates.map { ($0.elementId, $0) })
+ let existingCPTemplatesById = Dictionary(uniqueKeysWithValues: zip(self.objcTemplates.map { $0.elementId }, self.templates))
+
+ let newTemplates = FCPTabBarTemplate.parseTemplates(newTemplatesData)
+
+ /// Keep Flutter CarPlay object if necessary, use new instance.
+ self.objcTemplates = newTemplates.map { template in
+ if let existing = existingTemplatesById[template.elementId] {
+ // For FCPListTemplate, we can merge; for others, use new instance
+ if let existingList = existing as? FCPListTemplate, let newList = template as? FCPListTemplate {
+ return existingList.merge(with: newList)
+ }
+ return template
+ } else {
+ return template // Use new instance
+ }
+ }
+
+ /// Create new CarPlay template if necessary else keep currents.
+ self.templates = newTemplates.map { template in
+ if let existing = existingCPTemplatesById[template.elementId] {
+ return existing // Reuse existing CP template
+ } else {
+ return template.get // New CP template
+ }
+ }
+ _super?.updateTemplates(self.templates)
+ }
+}
+
+@available(iOS 14.0, *)
+extension FCPTabBarTemplate: FCPRootTemplate { }
diff --git a/packages/flutter_carplay/ios/flutter_carplay.podspec b/packages/flutter_carplay/ios/flutter_carplay.podspec
new file mode 100644
index 00000000..7651bb9e
--- /dev/null
+++ b/packages/flutter_carplay/ios/flutter_carplay.podspec
@@ -0,0 +1,23 @@
+#
+# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
+# Run `pod lib lint flutter_carplay.podspec` to validate before publishing.
+#
+Pod::Spec.new do |s|
+ s.name = 'flutter_carplay'
+ s.version = '1.1.0'
+ s.summary = 'Flutter Apps are now on Apple CarPlay.'
+ s.description = <<-DESC
+Flutter Apps are now on Apple CarPlay. This package aims to make it safe to use iPhone apps made with Flutter in the car by integrating with CarPlay.
+ DESC
+ s.homepage = 'https://github.com/oguzhnatly/flutter_carplay'
+ s.license = { :file => '../LICENSE' }
+ s.author = { 'Oğuzhan Atalay' => '[email protected]' }
+ s.source = { :path => '.' }
+ s.source_files = 'Classes/**/*'
+ s.dependency 'Flutter'
+ s.platform = :ios, '14.0'
+
+ # Flutter.framework does not contain a i386 slice.
+ s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
+ s.swift_version = '5.0'
+end
diff --git a/packages/flutter_carplay/lib/aa_models/list/list_item.dart b/packages/flutter_carplay/lib/aa_models/list/list_item.dart
new file mode 100644
index 00000000..71da2c59
--- /dev/null
+++ b/packages/flutter_carplay/lib/aa_models/list/list_item.dart
@@ -0,0 +1,28 @@
+import 'package:uuid/uuid.dart';
+
+class AAListItem {
+ /// Unique id of the object.
+ final String _elementId;
+
+ final String title;
+ final String? subtitle;
+ final String? imageUrl;
+ final Function(Function() complete, AAListItem self)? onPress;
+
+ AAListItem({
+ required this.title,
+ this.subtitle,
+ this.imageUrl,
+ this.onPress,
+ }) : _elementId = const Uuid().v4();
+
+ String get uniqueId => _elementId;
+
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'title': title,
+ 'subtitle': subtitle,
+ 'imageUrl': imageUrl,
+ 'onPress': onPress != null ? true : false,
+ };
+}
diff --git a/packages/flutter_carplay/lib/aa_models/list/list_section.dart b/packages/flutter_carplay/lib/aa_models/list/list_section.dart
new file mode 100644
index 00000000..fa9b1e1b
--- /dev/null
+++ b/packages/flutter_carplay/lib/aa_models/list/list_section.dart
@@ -0,0 +1,26 @@
+import 'package:uuid/uuid.dart';
+
+import 'list_item.dart';
+
+class AAListSection {
+ /// Unique id of the object.
+ final String _elementId;
+
+ /// Required only when multiple [AAListSection] are used in the same [AAListTemplate].
+ final String? title;
+
+ final List<AAListItem> items;
+
+ AAListSection({
+ this.title,
+ required this.items,
+ }) : _elementId = const Uuid().v4();
+
+ String get uniqueId => _elementId;
+
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'title': title,
+ 'items': items.map((AAListItem item) => item.toJson()).toList(),
+ };
+}
diff --git a/packages/flutter_carplay/lib/aa_models/list/list_template.dart b/packages/flutter_carplay/lib/aa_models/list/list_template.dart
new file mode 100644
index 00000000..ddd0db2a
--- /dev/null
+++ b/packages/flutter_carplay/lib/aa_models/list/list_template.dart
@@ -0,0 +1,28 @@
+import 'package:uuid/uuid.dart';
+
+import '../template.dart';
+import 'list_section.dart';
+
+class AAListTemplate implements AATemplate {
+ /// Unique id of the object.
+ final String _elementId;
+
+ final String title;
+ final List<AAListSection> sections;
+
+ AAListTemplate({
+ required this.title,
+ required this.sections,
+ }) : _elementId = const Uuid().v4();
+
+ @override
+ String get uniqueId => _elementId;
+
+ @override
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'title': title,
+ 'sections':
+ sections.map((AAListSection section) => section.toJson()).toList(),
+ };
+}
diff --git a/packages/flutter_carplay/lib/aa_models/template.dart b/packages/flutter_carplay/lib/aa_models/template.dart
new file mode 100644
index 00000000..51cd407f
--- /dev/null
+++ b/packages/flutter_carplay/lib/aa_models/template.dart
@@ -0,0 +1,7 @@
+abstract interface class AATemplate {
+ const AATemplate();
+
+ String get uniqueId;
+
+ Map<String, dynamic> toJson();
+}
diff --git a/packages/flutter_carplay/lib/android_auto_worker.dart b/packages/flutter_carplay/lib/android_auto_worker.dart
new file mode 100644
index 00000000..a401e197
--- /dev/null
+++ b/packages/flutter_carplay/lib/android_auto_worker.dart
@@ -0,0 +1,261 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter_carplay/constants/private_constants.dart';
+import 'package:flutter_carplay/flutter_carplay.dart';
+
+import 'aa_models/template.dart';
+import 'controllers/android_auto_controller.dart';
+
+/// An object in order to integrate Android auto in navigation and
+/// manage all user interface elements appearing on your screens displayed on
+/// the Android Auto screen.
+///
+/// Using Android auto, you can display content from your app on a customized user interface
+/// that is generated and hosted by the system itself. Control over UI elements, such as
+/// touch target size, font size and color, highlights, and so on.
+///
+/// **Useful Links:**
+/// - [What is Android auto?](https://developer.android.com/training/cars?hl=fr#auto/)
+class FlutterAndroidAuto {
+ /// A main Flutter CarPlay Controller to manage the system.
+ static final FlutterAndroidAutoController _androidAutoController =
+ FlutterAndroidAutoController();
+
+ /// CarPlay main bridge as a listener from Android Auto and native side.
+ late final StreamSubscription<dynamic>? _eventBroadcast;
+
+ /// Current Android Auto and mobile app connection status.
+ static String _connectionStatus = EnumUtils.stringFromEnum(
+ ConnectionStatusTypes.unknown.toString(),
+ );
+
+ /// A listener function, which will be triggered when CarPlay connection changes
+ /// and will be transmitted to the main code, allowing the user to access
+ /// the current connection status.
+ Function(ConnectionStatusTypes status)? _onAndroidAutoConnectionChange;
+
+ /// Creates an [FlutterAndroidAuto] and starts the connection.
+ FlutterAndroidAuto() {
+ if (defaultTargetPlatform != TargetPlatform.android) return;
+
+ _eventBroadcast = _androidAutoController.eventChannel
+ .receiveBroadcastStream()
+ .listen((event) {
+ final FAAChannelTypes receivedChannelType =
+ EnumUtils.enumFromString(FAAChannelTypes.values, event['type']);
+
+ switch (receivedChannelType) {
+ case FAAChannelTypes.onAndroidAutoConnectionChange:
+ final ConnectionStatusTypes connectionStatus =
+ EnumUtils.enumFromString(
+ ConnectionStatusTypes.values,
+ event['data']['status'],
+ );
+ _connectionStatus = EnumUtils.stringFromEnum(
+ connectionStatus.toString(),
+ );
+ if (_onAndroidAutoConnectionChange != null) {
+ _onAndroidAutoConnectionChange!(connectionStatus);
+ }
+ break;
+ case FAAChannelTypes.onListItemSelected:
+ _androidAutoController.processFAAListItemSelectedChannel(
+ event['data']['elementId'],
+ );
+ break;
+ case FAAChannelTypes.onScreenBackButtonPressed:
+ FlutterAndroidAutoController.templateHistory.removeWhere(
+ (AATemplate item) => item.uniqueId == event['data']['elementId'],
+ );
+ break;
+ default:
+ break;
+ }
+ });
+ }
+
+ /// A function that will disconnect all event listeners from Android Auto. The action
+ /// will be irrevocable, and a new [FlutterAndroidAuto] controller must be created after this,
+ /// otherwise Android Auto will be unusable.
+ ///
+ /// [!] It is not recommended to use this function if you do not know what you are doing.
+ void closeConnection() {
+ _eventBroadcast!.cancel();
+ }
+
+ /// A function that will resume the paused all event listeners from Android Auto.
+ void resumeConnection() {
+ _eventBroadcast!.resume();
+ }
+
+ /// A function that will pause the all active event listeners from Android Auto.
+ void pauseConnection() {
+ _eventBroadcast!.pause();
+ }
+
+ /// Callback function will be fired when Android Auto connection status is changed.
+ /// For example, when Android Auto is connected to the device, in the background state,
+ /// or completely disconnected.
+ ///
+ /// See also: [ConnectionStatusTypes]
+ void addListenerOnConnectionChange(
+ Function(ConnectionStatusTypes status) onAndroidAutoConnectionChange,
+ ) {
+ _onAndroidAutoConnectionChange = onAndroidAutoConnectionChange;
+ }
+
+ /// Removes the callback function that has been set before in order to listen
+ /// on Android Auto connection status changed.
+ void removeListenerOnConnectionChange() {
+ _onAndroidAutoConnectionChange = null;
+ }
+
+ /// Current CarPlay connection status. It will return one of [ConnectionStatusTypes] as String.
+ static String get connectionStatus {
+ return _connectionStatus;
+ }
+
+ static Future<void> setRootTemplate({
+ required AATemplate template,
+ }) async {
+ final bool? isCompleted = await _androidAutoController
+ .flutterToNativeModule(FAAChannelTypes.setRootTemplate, {
+ 'template': template.toJson(),
+ 'runtimeType': _getAARuntimeTypeString(template),
+ });
+
+ if (isCompleted == true) {
+ if (FlutterAndroidAutoController.templateHistory.isEmpty) {
+ FlutterAndroidAutoController.templateHistory.add(template);
+ } else {
+ FlutterAndroidAutoController.templateHistory[0] = template;
+ }
+ }
+ }
+
+ /// It will set the current root template again.
+ Future<void> forceUpdateRootTemplate() {
+ return _androidAutoController.flutterToNativeModule(
+ FAAChannelTypes.forceUpdateRootTemplate,
+ );
+ }
+
+ /// Getter for current root template.
+ /// Return one of type [CPTabBarTemplate], [CPGridTemplate], [CPListTemplate]
+ static dynamic get rootTemplate {
+ return FlutterAndroidAutoController.currentRootTemplate;
+ }
+
+ /// It will present [CPAlertTemplate] modally.
+ ///
+ /// - template is to present modally.
+ /// - If animated is true, CarPlay animates the presentation of the template.
+ ///
+ /// [!] CarPlay can only present one modal template at a time.
+/*static Future<void> showAlert({
+ required CPAlertTemplate template,
+ bool animated = true,
+ }) {
+ return _androidAutoController.methodChannel.invokeMethod(
+ EnumUtils.stringFromEnum(FCPChannelTypes.setAlert.toString()),
+ <String, dynamic>{
+ 'rootTemplate': template.toJson(),
+ 'animated': animated,
+ 'onPresent': template.onPresent != null ? true : false,
+ },
+ ).then((value) {
+ if (value) {
+ FlutterCarPlayController.currentPresentTemplate = template;
+ }
+ });
+ }*/
+
+ /// It will present [CPActionSheetTemplate] modally.
+ ///
+ /// - template is to present modally.
+ /// - If animated is true, CarPlay animates the presentation of the template.
+ ///
+ /// [!] CarPlay can only present one modal template at a time.
+/* static Future<void> showActionSheet({
+ required CPActionSheetTemplate template,
+ bool animated = true,
+ }) {
+ return _androidAutoController.methodChannel.invokeMethod(
+ EnumUtils.stringFromEnum(FCPChannelTypes.setActionSheet.toString()),
+ <String, dynamic>{
+ 'rootTemplate': template.toJson(),
+ 'animated': animated,
+ },
+ ).then((value) {
+ if (value) {
+ FlutterCarPlayController.currentPresentTemplate = template;
+ }
+ });
+ }*/
+
+ /// Removes the top-most template from the navigation hierarchy.
+ ///
+ /// The history will be updated accordingly to the screen lifecycle.
+ static Future<bool> pop() async {
+ final bool? isCompleted =
+ await _androidAutoController.flutterToNativeModule(
+ FAAChannelTypes.popTemplate,
+ );
+
+ return isCompleted ?? false;
+ }
+
+ /// Removes all of the templates from the navigation hierarchy except the root template.
+ ///
+ /// The history will be updated accordingly to the screen lifecycle.
+ static Future<bool> popToRoot() async {
+ final bool? isCompleted =
+ await _androidAutoController.flutterToNativeModule(
+ FAAChannelTypes.popToRootTemplate,
+ );
+ return isCompleted ?? false;
+ }
+
+ /// Removes a modal template. Since [CPAlertTemplate] and [CPActionSheetTemplate] are both
+ /// modals, they can be removed. If animated is true, CarPlay animates the transition between templates.
+/* static Future<bool> popModal({bool animated = true}) async {
+ FlutterCarPlayController.currentPresentTemplate = null;
+ return await _androidAutoController.flutterToNativeModule(
+ FAAChannelTypes.closePresent,
+ animated,
+ );
+ }*/
+
+ /// Adds a template to the navigation hierarchy and displays it.
+ ///
+ /// - template is to add to the navigation hierarchy. **Must be one of the type:**
+ /// [AAGridTemplate] or [AAListTemplate] [AAInformationTemplat] [AAPointOfInterestTemplate]
+ ///
+ /// Be aware of the restrictions : https://developer.android.com/training/cars/apps#template-restrictions
+ /// - Max 5 templates in the navigation stack.
+ static Future<bool> push({
+ required AATemplate template,
+ }) async {
+ final bool? isCompleted = await _androidAutoController
+ .flutterToNativeModule(FAAChannelTypes.pushTemplate, <String, dynamic>{
+ 'template': template.toJson(),
+ 'runtimeType': _getAARuntimeTypeString(template),
+ });
+ if (isCompleted == true) {
+ FlutterAndroidAutoController.templateHistory.add(template);
+ }
+ return isCompleted ?? false;
+ }
+
+ /// Didn't exist on Android Auto. If the player can be displayed, a button will
+ /// be shown on the bottom right of the Android Auto screen.
+ static Future<bool> showSharedNowPlaying() async => false;
+
+ /// Returns the runtime type string for native communication.
+ /// Uses explicit type checks to ensure compatibility with Dart obfuscation.
+ static String _getAARuntimeTypeString(AATemplate template) {
+ if (template is AAListTemplate) return 'FAAListTemplate';
+ return 'FAA${template.runtimeType}';
+ }
+}
diff --git a/packages/flutter_carplay/lib/carplay_worker.dart b/packages/flutter_carplay/lib/carplay_worker.dart
new file mode 100644
index 00000000..bbeac801
--- /dev/null
+++ b/packages/flutter_carplay/lib/carplay_worker.dart
@@ -0,0 +1,384 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter_carplay/constants/private_constants.dart';
+import 'package:flutter_carplay/controllers/carplay_controller.dart';
+import 'package:flutter_carplay/flutter_carplay.dart';
+
+import 'models/template.dart';
+
+/// An object in order to integrate Apple CarPlay in navigation and
+/// manage all user interface elements appearing on your screens displayed on
+/// the CarPlay screen.
+///
+/// Using CarPlay, you can display content from your app on a customized user interface
+/// that is generated and hosted by the system itself. Control over UI elements, such as
+/// touch target size, font size and color, highlights, and so on.
+///
+/// **Useful Links:**
+/// - [What is CarPlay?](https://developer.apple.com/carplay/)
+/// - [Request CarPlay Framework](https://developer.apple.com/contact/carplay/)
+/// - [Learn more about MFi Program](https://mfi.apple.com)
+class FlutterCarplay {
+ /// A main Flutter CarPlay Controller to manage the system.
+ static final FlutterCarPlayController _carPlayController =
+ FlutterCarPlayController();
+
+ /// CarPlay main bridge as a listener from CarPlay and native side.
+ late final StreamSubscription<dynamic>? _eventBroadcast;
+
+ /// Current CarPlay and mobile app connection status.
+ static String _connectionStatus = EnumUtils.stringFromEnum(
+ ConnectionStatusTypes.unknown.toString(),
+ );
+
+ /// A listener function, which will be triggered when CarPlay connection changes
+ /// and will be transmitted to the main code, allowing the user to access
+ /// the current connection status.
+ Function(ConnectionStatusTypes status)? _onCarplayConnectionChange;
+
+ /// Creates an [FlutterCarplay] and starts the connection.
+ FlutterCarplay() {
+ if (defaultTargetPlatform != TargetPlatform.iOS) return;
+
+ _eventBroadcast = _carPlayController.eventChannel
+ .receiveBroadcastStream()
+ .listen((event) {
+ final FCPChannelTypes receivedChannelType =
+ EnumUtils.enumFromString(FCPChannelTypes.values, event['type']);
+ switch (receivedChannelType) {
+ case FCPChannelTypes.onCarplayConnectionChange:
+ final ConnectionStatusTypes connectionStatus =
+ EnumUtils.enumFromString(
+ ConnectionStatusTypes.values,
+ event['data']['status'],
+ );
+ _connectionStatus = EnumUtils.stringFromEnum(
+ connectionStatus.toString(),
+ );
+ if (_onCarplayConnectionChange != null) {
+ _onCarplayConnectionChange!(connectionStatus);
+ }
+ break;
+ case FCPChannelTypes.onFCPListItemSelected:
+ _carPlayController.processFCPListItemSelectedChannel(
+ event['data']['elementId'],
+ );
+ break;
+ case FCPChannelTypes.onFCPAlertActionPressed:
+ _carPlayController.processFCPAlertActionPressed(
+ event['data']['elementId'],
+ );
+ break;
+ case FCPChannelTypes.onPresentStateChanged:
+ _carPlayController.processFCPAlertTemplateCompleted(
+ event['data']['completed'],
+ );
+ break;
+ case FCPChannelTypes.onGridButtonPressed:
+ _carPlayController.processFCPGridButtonPressed(
+ event['data']['elementId'],
+ );
+ break;
+ case FCPChannelTypes.onBarButtonPressed:
+ _carPlayController.processFCPBarButtonPressed(
+ event['data']['elementId'],
+ );
+ break;
+ case FCPChannelTypes.onTextButtonPressed:
+ _carPlayController.processFCPTextButtonPressed(
+ event['data']['elementId'],
+ );
+ break;
+ case FCPChannelTypes.onScreenBackButtonPressed:
+ FlutterCarPlayController.templateHistory.removeWhere(
+ (CPTemplate item) => item.uniqueId == event['data']['elementId'],
+ );
+ break;
+ default:
+ break;
+ }
+ });
+ }
+
+ /// A function that will disconnect all event listeners from CarPlay. The action
+ /// will be irrevocable, and a new [FlutterCarplay] controller must be created after this,
+ /// otherwise CarPlay will be unusable.
+ ///
+ /// [!] It is not recommended to use this function if you do not know what you are doing.
+ void closeConnection() {
+ _eventBroadcast!.cancel();
+ }
+
+ /// A function that will resume the paused all event listeners from CarPlay.
+ void resumeConnection() {
+ _eventBroadcast!.resume();
+ }
+
+ /// A function that will pause the all active event listeners from CarPlay.
+ void pauseConnection() {
+ _eventBroadcast!.pause();
+ }
+
+ /// Callback function will be fired when CarPlay connection status is changed.
+ /// For example, when CarPlay is connected to the device, in the background state,
+ /// or completely disconnected.
+ ///
+ /// See also: [ConnectionStatusTypes]
+ void addListenerOnConnectionChange(
+ Function(ConnectionStatusTypes status) onCarplayConnectionChange,
+ ) {
+ _onCarplayConnectionChange = onCarplayConnectionChange;
+ }
+
+ /// Removes the callback function that has been set before in order to listen
+ /// on CarPlay connection status changed.
+ void removeListenerOnConnectionChange() {
+ _onCarplayConnectionChange = null;
+ }
+
+ /// Current CarPlay connection status. It will return one of [ConnectionStatusTypes] as String.
+ static String get connectionStatus {
+ return _connectionStatus;
+ }
+
+ /// Sets the root template of the navigation hierarchy. If a navigation
+ /// hierarchy already exists, CarPlay replaces the entire hierarchy.
+ ///
+ /// - rootTemplate is a template to use as the root of a new navigation hierarchy. If one exists,
+ /// it will replace the current rootTemplate. **Must be one of the type:**
+ /// [CPTabBarTemplate], [CPGridTemplate], [CPListTemplate] If not, it will throw an [TypeError]
+ ///
+ /// - If animated is true, CarPlay animates the presentation of the template, but will be ignored
+ /// this flag when there isn’t an existing navigation hierarchy to replace.
+ ///
+ /// [!] CarPlay cannot have more than 5 templates on one screen.
+ static Future<void> setRootTemplate({
+ required CPTemplate rootTemplate,
+ bool animated = true,
+ }) async {
+ if (rootTemplate is CPTabBarTemplate ||
+ rootTemplate is CPGridTemplate ||
+ rootTemplate is CPListTemplate ||
+ rootTemplate is CPInformationTemplate ||
+ rootTemplate is CPPointOfInterestTemplate) {
+ return _carPlayController.methodChannel
+ .invokeMethod('setRootTemplate', <String, dynamic>{
+ 'rootTemplate': rootTemplate.toJson(),
+ 'animated': animated,
+ 'runtimeType': _getCPRuntimeTypeString(rootTemplate),
+ }).then((value) {
+ if (value) {
+ if (FlutterCarPlayController.templateHistory.isEmpty) {
+ FlutterCarPlayController.templateHistory.add(rootTemplate);
+ } else {
+ FlutterCarPlayController.templateHistory[0] = rootTemplate;
+ }
+ }
+ });
+ }
+ }
+
+ /// It will set the current root template again.
+ Future<void> forceUpdateRootTemplate() {
+ return _carPlayController.methodChannel
+ .invokeMethod('forceUpdateRootTemplate');
+ }
+
+ /// It will update the sections of the [CPListTemplate] which has the given [elementId].
+ Future<void> updateListTemplateSections({
+ required String elementId,
+ required List<CPListSection> sections,
+ }) async {
+ final bool? isCompleted = await _carPlayController.methodChannel
+ .invokeMethod('updateListTemplateSections', <String, dynamic>{
+ 'elementId': elementId,
+ 'sections':
+ sections.map((CPListSection section) => section.toJson()).toList(),
+ });
+
+ if (isCompleted == true) {
+ final template =
+ FlutterCarPlayController.getTemplateFromHistory<CPListTemplate>(
+ elementId);
+ template?.updateSections(sections);
+ }
+ return;
+ }
+
+ /// It will update the templates of the [CPTabBarTemplate] which has the given [elementId].
+ /// Supported template types: [CPListTemplate], [CPPointOfInterestTemplate],
+ /// [CPGridTemplate], [CPInformationTemplate]
+ Future<void> updateTabBarTemplates({
+ required String elementId,
+ required List<CPTemplate> templates,
+ }) async {
+ final bool? isCompleted = await _carPlayController.methodChannel
+ .invokeMethod('updateTabBarTemplates', <String, dynamic>{
+ 'elementId': elementId,
+ 'templates': templates.map((CPTemplate template) {
+ final json = template.toJson();
+ if (template is CPListTemplate) {
+ json['runtimeType'] = 'FCPListTemplate';
+ } else if (template is CPPointOfInterestTemplate) {
+ json['runtimeType'] = 'FCPPointOfInterestTemplate';
+ } else if (template is CPGridTemplate) {
+ json['runtimeType'] = 'FCPGridTemplate';
+ } else if (template is CPInformationTemplate) {
+ json['runtimeType'] = 'FCPInformationTemplate';
+ }
+ return json;
+ }).toList(),
+ });
+
+ if (isCompleted == true) {
+ final template =
+ FlutterCarPlayController.getTemplateFromHistory<CPTabBarTemplate>(
+ elementId);
+ template?.updateTemplates(templates);
+ }
+ return;
+ }
+
+ /// Getter for current root template.
+ /// Return one of type [CPTabBarTemplate], [CPGridTemplate], [CPListTemplate]
+ static dynamic get rootTemplate {
+ return FlutterCarPlayController.currentRootTemplate;
+ }
+
+ /// It will present [CPAlertTemplate] modally.
+ ///
+ /// - template is to present modally.
+ /// - If animated is true, CarPlay animates the presentation of the template.
+ ///
+ /// [!] CarPlay can only present one modal template at a time.
+ static Future<void> showAlert({
+ required CPAlertTemplate template,
+ bool animated = true,
+ }) {
+ return _carPlayController.methodChannel.invokeMethod(
+ EnumUtils.stringFromEnum(FCPChannelTypes.setAlert.toString()),
+ <String, dynamic>{
+ 'rootTemplate': template.toJson(),
+ 'animated': animated,
+ 'onPresent': template.onPresent != null ? true : false,
+ },
+ ).then((value) {
+ if (value) {
+ FlutterCarPlayController.currentPresentTemplate = template;
+ }
+ });
+ }
+
+ /// It will present [CPActionSheetTemplate] modally.
+ ///
+ /// - template is to present modally.
+ /// - If animated is true, CarPlay animates the presentation of the template.
+ ///
+ /// [!] CarPlay can only present one modal template at a time.
+ static Future<void> showActionSheet({
+ required CPActionSheetTemplate template,
+ bool animated = true,
+ }) {
+ return _carPlayController.methodChannel.invokeMethod(
+ EnumUtils.stringFromEnum(FCPChannelTypes.setActionSheet.toString()),
+ <String, dynamic>{
+ 'rootTemplate': template.toJson(),
+ 'animated': animated,
+ },
+ ).then((value) {
+ if (value) {
+ FlutterCarPlayController.currentPresentTemplate = template;
+ }
+ });
+ }
+
+ /// Removes the top-most template from the navigation hierarchy.
+ ///
+ /// - If animated is true, CarPlay animates the transition between templates.
+ /// - count represents how many times this function will occur.
+ static Future<bool> pop({bool animated = true, int count = 1}) async {
+ final bool? isCompleted = await _carPlayController.flutterToNativeModule(
+ FCPChannelTypes.popTemplate,
+ <String, dynamic>{'count': count, 'animated': animated},
+ );
+
+ return isCompleted ?? false;
+ }
+
+ /// Removes all of the templates from the navigation hierarchy except the root template.
+ /// If animated is true, CarPlay animates the presentation of the template.
+ static Future<bool> popToRoot({bool animated = true}) async {
+ final bool? isCompleted = await _carPlayController.flutterToNativeModule(
+ FCPChannelTypes.popToRootTemplate,
+ animated,
+ );
+
+ return isCompleted ?? false;
+ }
+
+ /// Removes a modal template. Since [CPAlertTemplate] and [CPActionSheetTemplate] are both
+ /// modals, they can be removed. If animated is true, CarPlay animates the transition between templates.
+ static Future<bool> popModal({bool animated = true}) async {
+ FlutterCarPlayController.currentPresentTemplate = null;
+ final bool? isCompleted = await _carPlayController.flutterToNativeModule(
+ FCPChannelTypes.closePresent,
+ animated,
+ );
+
+ return isCompleted ?? false;
+ }
+
+ /// Adds a template to the navigation hierarchy and displays it.
+ ///
+ /// - template is to add to the navigation hierarchy. **Must be one of the type:**
+ /// [CPGridTemplate] or [CPListTemplate] [CPInformationTemplate] [CPPointOfInterestTemplate] If not, it will throw an [TypeError]
+ ///
+ /// - If animated is true, CarPlay animates the transition between templates.
+ static Future<bool> push({
+ required CPTemplate template,
+ bool animated = true,
+ }) async {
+ if (template is CPGridTemplate ||
+ template is CPListTemplate ||
+ template is CPInformationTemplate ||
+ template is CPPointOfInterestTemplate) {
+ final bool? isCompleted = await _carPlayController.flutterToNativeModule(
+ FCPChannelTypes.pushTemplate, <String, dynamic>{
+ 'template': template.toJson(),
+ 'animated': animated,
+ 'runtimeType': _getCPRuntimeTypeString(template),
+ });
+ if (isCompleted == true) {
+ _carPlayController.addTemplateToHistory(template);
+ }
+ return isCompleted ?? false;
+ } else {
+ throw TypeError();
+ }
+ }
+
+ /// Navigate to the shared instance of the NowPlaying Template
+ ///
+ /// - If animated is true, CarPlay animates the transition between templates.
+ static Future<bool> showSharedNowPlaying({bool animated = true}) async {
+ final bool? isCompleted = await _carPlayController.flutterToNativeModule(
+ FCPChannelTypes.showNowPlaying,
+ animated,
+ );
+ return isCompleted ?? false;
+ }
+
+ /// Returns the runtime type string for native communication.
+ /// Uses explicit type checks to ensure compatibility with Dart obfuscation.
+ static String _getCPRuntimeTypeString(CPTemplate template) {
+ if (template is CPTabBarTemplate) return 'FCPTabBarTemplate';
+ if (template is CPGridTemplate) return 'FCPGridTemplate';
+ if (template is CPListTemplate) return 'FCPListTemplate';
+ if (template is CPInformationTemplate) return 'FCPInformationTemplate';
+ if (template is CPPointOfInterestTemplate) {
+ return 'FCPPointOfInterestTemplate';
+ }
+ return 'FCP${template.runtimeType}';
+ }
+}
diff --git a/packages/flutter_carplay/lib/constants/constants.dart b/packages/flutter_carplay/lib/constants/constants.dart
new file mode 100644
index 00000000..621507e7
--- /dev/null
+++ b/packages/flutter_carplay/lib/constants/constants.dart
@@ -0,0 +1 @@
+enum ConnectionStatusTypes { connected, background, disconnected, unknown }
diff --git a/packages/flutter_carplay/lib/constants/private_constants.dart b/packages/flutter_carplay/lib/constants/private_constants.dart
new file mode 100644
index 00000000..5ce77fab
--- /dev/null
+++ b/packages/flutter_carplay/lib/constants/private_constants.dart
@@ -0,0 +1,33 @@
+enum FCPChannelTypes {
+ onCarplayConnectionChange,
+ setRootTemplate,
+ forceUpdateRootTemplate,
+ updateListItem,
+ onFCPListItemSelected,
+ onFCPListItemSelectedComplete,
+ onFCPAlertActionPressed,
+ setAlert,
+ onPresentStateChanged,
+ popTemplate,
+ closePresent,
+ pushTemplate,
+ showNowPlaying,
+ onGridButtonPressed,
+ setActionSheet,
+ onBarButtonPressed,
+ onTextButtonPressed,
+ popToRootTemplate,
+ onScreenBackButtonPressed,
+}
+
+enum FAAChannelTypes {
+ onAndroidAutoConnectionChange,
+ setRootTemplate,
+ forceUpdateRootTemplate,
+ pushTemplate,
+ popTemplate,
+ popToRootTemplate,
+ onListItemSelected,
+ onListItemSelectedComplete,
+ onScreenBackButtonPressed,
+}
diff --git a/packages/flutter_carplay/lib/controllers/android_auto_controller.dart b/packages/flutter_carplay/lib/controllers/android_auto_controller.dart
new file mode 100644
index 00000000..1abea3b0
--- /dev/null
+++ b/packages/flutter_carplay/lib/controllers/android_auto_controller.dart
@@ -0,0 +1,174 @@
+import 'package:flutter/services.dart';
+import 'package:flutter_carplay/constants/private_constants.dart';
+
+import '../aa_models/list/list_item.dart';
+import '../aa_models/template.dart';
+import '../helpers/auto_android_helper.dart';
+import '../helpers/enum_utils.dart';
+
+/// [FlutterAndroidAutoController] is an root object in order to control and communication
+/// system with the Android Auto and native functions.
+class FlutterAndroidAutoController {
+ static final FlutterAutoAndroidHelper _androidAutoHelper =
+ const FlutterAutoAndroidHelper();
+ static final MethodChannel _methodChannel = MethodChannel(
+ _androidAutoHelper.makeFAAChannelId(),
+ );
+ static final EventChannel _eventChannel = EventChannel(
+ _androidAutoHelper.makeFAAChannelId(event: '/event'),
+ );
+
+ /// [AATabBarTemplate], [AAGridTemplate], [AAListTemplate], [AAIInformationTemplate], [AAPointOfInterestTemplate] in a List
+ static List<AATemplate> templateHistory = [];
+
+ /// [AATabBarTemplate], [AAGridTemplate], [AAListTemplate], [AAIInformationTemplate], [AAPointOfInterestTemplate]
+ static AATemplate? get currentRootTemplate => templateHistory.firstOrNull;
+
+ /// [AAAlertTemplate], [AAActionSheetTemplate]
+ static AATemplate? currentPresentTemplate;
+
+ MethodChannel get methodChannel => _methodChannel;
+
+ EventChannel get eventChannel => _eventChannel;
+
+ Future<bool?> flutterToNativeModule(
+ FAAChannelTypes type, [
+ dynamic data,
+ ]) async {
+ final bool? value = await _methodChannel.invokeMethod<bool>(
+ EnumUtils.stringFromEnum(type.toString()),
+ data,
+ );
+ return value;
+ }
+
+ /* static void updateCPListItem(CPListItem updatedListItem) {
+ _methodChannel.invokeMethod('updateListItem', <String, dynamic>{
+ ...updatedListItem.toJson(),
+ }).then((value) {
+ if (value) {
+ l1:
+ for (var h in templateHistory) {
+ switch (h.runtimeType) {
+ case CPTabBarTemplate _:
+ for (var t in (h as CPTabBarTemplate).templates) {
+ for (var s in t.sections) {
+ for (var i in s.items) {
+ if (i.uniqueId == updatedListItem.uniqueId) {
+ currentRootTemplate!
+ .templates[currentRootTemplate!.templates.indexOf(t)]
+ .sections[t.sections.indexOf(s)]
+ .items[s.items.indexOf(i)] = updatedListItem;
+ break l1;
+ }
+ }
+ }
+ }
+ break;
+ case CPListTemplate _:
+ for (var s in (h as CPListTemplate).sections) {
+ for (var i in s.items) {
+ if (i.uniqueId == updatedListItem.uniqueId) {
+ currentRootTemplate!
+ .sections[currentRootTemplate!.sections.indexOf(
+ s,
+ )]
+ .items[s.items.indexOf(i)] = updatedListItem;
+ break l1;
+ }
+ }
+ }
+ break;
+ default:
+ }
+ }
+ }
+ });
+ }*/
+
+ void processFAAListItemSelectedChannel(String elementId) {
+ final AAListItem? listItem = _androidAutoHelper.findAAListItem(
+ templates: templateHistory,
+ elementId: elementId,
+ );
+ if (listItem != null) {
+ listItem.onPress!(
+ () => flutterToNativeModule(
+ FAAChannelTypes.onListItemSelectedComplete,
+ listItem.uniqueId,
+ ),
+ listItem,
+ );
+ }
+ }
+
+/*void processFAAAlertActionPressed(String elementId) {
+ CAAAlertAction selectedAlertAction = currentPresentTemplate!.actions
+ .firstWhere((e) => e.uniqueId == elementId);
+ selectedAlertAction.onPress();
+ }*/
+
+/*void processFCPAlertTemplateCompleted(bool completed) {
+ if (currentPresentTemplate?.onPresent != null) {
+ currentPresentTemplate!.onPresent!(completed);
+ }
+ }*/
+
+/*void processFCPGridButtonPressed(String elementId) {
+ CPGridButton? gridButton;
+ l1:
+ for (var t in templateHistory) {
+ if (t.runtimeType.toString() == "CPGridTemplate") {
+ for (var b in t.buttons) {
+ if (b.uniqueId == elementId) {
+ gridButton = b;
+ break l1;
+ }
+ }
+ }
+ }
+ if (gridButton != null) gridButton.onPress();
+ }*/
+
+/*void processFCPBarButtonPressed(String elementId) {
+ CPBarButton? barButton;
+ l1:
+ for (var t in templateHistory) {
+ if (t.runtimeType.toString() == "CPListTemplate") {
+ barButton = t.backButton;
+ break l1;
+ }
+ }
+ if (barButton != null) barButton.onPress();
+ }*/
+
+/*void processFCPTextButtonPressed(String elementId) {
+ l1:
+ for (var t in templateHistory) {
+ if (t.runtimeType.toString() == "CPPointOfInterestTemplate") {
+ for (CPPointOfInterest p in t.poi) {
+ if (p.primaryButton != null &&
+ p.primaryButton!.uniqueId == elementId) {
+ p.primaryButton!.onPress();
+ break l1;
+ }
+ if (p.secondaryButton != null &&
+ p.secondaryButton!.uniqueId == elementId) {
+ p.secondaryButton!.onPress();
+ break l1;
+ }
+ }
+ } else {
+ if (t.runtimeType.toString() == "CPInformationTemplate") {
+ l2:
+ for (CPTextButton b in t.actions) {
+ if (b.uniqueId == elementId) {
+ b.onPress();
+ break l2;
+ }
+ }
+ }
+ }
+ }
+ }*/
+}
diff --git a/packages/flutter_carplay/lib/controllers/carplay_controller.dart b/packages/flutter_carplay/lib/controllers/carplay_controller.dart
new file mode 100644
index 00000000..95d848da
--- /dev/null
+++ b/packages/flutter_carplay/lib/controllers/carplay_controller.dart
@@ -0,0 +1,198 @@
+import 'package:flutter/services.dart';
+import 'package:flutter_carplay/constants/private_constants.dart';
+import 'package:flutter_carplay/flutter_carplay.dart';
+import 'package:flutter_carplay/helpers/carplay_helper.dart';
+
+import '../models/template.dart';
+
+/// [FlutterCarPlayController] is an root object in order to control and communication
+/// system with the Apple CarPlay and native functions.
+class FlutterCarPlayController {
+ static final FlutterCarplayHelper _carplayHelper = FlutterCarplayHelper();
+ static final MethodChannel _methodChannel = MethodChannel(
+ _carplayHelper.makeFCPChannelId(),
+ );
+ static final EventChannel _eventChannel = EventChannel(
+ _carplayHelper.makeFCPChannelId(event: '/event'),
+ );
+
+ /// [CPTabBarTemplate], [CPGridTemplate], [CPListTemplate], [CPIInformationTemplate], [CPPointOfInterestTemplate] in a List
+ static List<CPTemplate> templateHistory = [];
+
+ /// [CPTabBarTemplate], [CPGridTemplate], [CPListTemplate], [CPIInformationTemplate], [CPPointOfInterestTemplate]
+ static CPTemplate? get currentRootTemplate => templateHistory.firstOrNull;
+
+ /// [CPAlertTemplate], [CPActionSheetTemplate]
+ static CPTemplate? currentPresentTemplate;
+
+ MethodChannel get methodChannel {
+ return _methodChannel;
+ }
+
+ EventChannel get eventChannel {
+ return _eventChannel;
+ }
+
+ Future<bool?> flutterToNativeModule(
+ FCPChannelTypes type,
+ dynamic data,
+ ) async {
+ final value = await _methodChannel.invokeMethod<bool>(
+ EnumUtils.stringFromEnum(type.toString()),
+ data,
+ );
+ return value;
+ }
+
+ static void updateCPListItem(CPListItem updatedListItem) {
+ _methodChannel.invokeMethod('updateListItem', <String, dynamic>{
+ ...updatedListItem.toJson(),
+ }).then((value) {
+ if (value) {
+ l1:
+ for (var h in templateHistory) {
+ switch (h) {
+ case CPTabBarTemplate _:
+ for (var t in h.templates) {
+ if (t is CPListTemplate) {
+ for (var s in t.sections) {
+ for (var i in s.items) {
+ if (i.uniqueId == updatedListItem.uniqueId) {
+ s.items[s.items.indexOf(i)] = updatedListItem;
+ break l1;
+ }
+ }
+ }
+ }
+ }
+ break;
+ case CPListTemplate _:
+ for (var s in h.sections) {
+ for (var i in s.items) {
+ if (i.uniqueId == updatedListItem.uniqueId) {
+ s.items[s.items.indexOf(i)] = updatedListItem;
+ break l1;
+ }
+ }
+ }
+ break;
+ default:
+ }
+ }
+ }
+ });
+ }
+
+ void addTemplateToHistory(CPTemplate template) {
+ if (template is CPTabBarTemplate ||
+ template is CPGridTemplate ||
+ template is CPInformationTemplate ||
+ template is CPPointOfInterestTemplate ||
+ template is CPListTemplate) {
+ templateHistory.add(template);
+ } else {
+ throw TypeError();
+ }
+ }
+
+ void processFCPListItemSelectedChannel(String elementId) {
+ final CPListItem? listItem = _carplayHelper.findCPListItem(
+ templates: templateHistory,
+ elementId: elementId,
+ );
+ if (listItem != null) {
+ listItem.onPress!(
+ () => flutterToNativeModule(
+ FCPChannelTypes.onFCPListItemSelectedComplete,
+ listItem.uniqueId,
+ ),
+ listItem,
+ );
+ }
+ }
+
+ void processFCPAlertActionPressed(String elementId) {
+ final CPAlertAction selectedAlertAction =
+ (currentPresentTemplate as CPActionsTemplate)
+ .actions
+ .firstWhere((e) => e.uniqueId == elementId);
+ selectedAlertAction.onPress();
+ }
+
+ void processFCPAlertTemplateCompleted(bool completed) {
+ if (currentPresentTemplate is CPAlertTemplate) {
+ (currentPresentTemplate as CPAlertTemplate).onPresent?.call(completed);
+ }
+ }
+
+ void processFCPGridButtonPressed(String elementId) {
+ CPGridButton? gridButton;
+ l1:
+ for (var t in templateHistory) {
+ if (t is CPGridTemplate) {
+ for (var b in t.buttons) {
+ if (b.uniqueId == elementId) {
+ gridButton = b;
+ break l1;
+ }
+ }
+ }
+ }
+ if (gridButton != null) gridButton.onPress();
+ }
+
+ void processFCPBarButtonPressed(String elementId) {
+ CPBarButton? barButton;
+ l1:
+ for (var t in templateHistory) {
+ if (t is CPListTemplate) {
+ barButton = t.backButton;
+ break l1;
+ }
+ }
+ if (barButton != null) barButton.onPress();
+ }
+
+ void processFCPTextButtonPressed(String elementId) {
+ l1:
+ for (var t in templateHistory) {
+ if (t is CPPointOfInterestTemplate) {
+ for (CPPointOfInterest p in t.poi) {
+ if (p.primaryButton != null &&
+ p.primaryButton!.uniqueId == elementId) {
+ p.primaryButton!.onPress();
+ break l1;
+ }
+ if (p.secondaryButton != null &&
+ p.secondaryButton!.uniqueId == elementId) {
+ p.secondaryButton!.onPress();
+ break l1;
+ }
+ }
+ } else {
+ if (t is CPInformationTemplate) {
+ l2:
+ for (CPTextButton b in t.actions) {
+ if (b.uniqueId == elementId) {
+ b.onPress();
+ break l2;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ static T? getTemplateFromHistory<T extends CPTemplate>(String elementId) {
+ for (final template in templateHistory) {
+ if (template is T && template.uniqueId == elementId) return template;
+
+ if (template is CPTabBarTemplate) {
+ for (final t in template.templates) {
+ if (t is T && t.uniqueId == elementId) return t;
+ }
+ }
+ }
+ return null;
+ }
+}
diff --git a/packages/flutter_carplay/lib/flutter_carplay.dart b/packages/flutter_carplay/lib/flutter_carplay.dart
new file mode 100644
index 00000000..7e554eb4
--- /dev/null
+++ b/packages/flutter_carplay/lib/flutter_carplay.dart
@@ -0,0 +1,45 @@
+export 'package:flutter_carplay/aa_models/list/list_item.dart' show AAListItem;
+export 'package:flutter_carplay/aa_models/list/list_section.dart'
+ show AAListSection;
+export 'package:flutter_carplay/aa_models/list/list_template.dart'
+ show AAListTemplate;
+export 'package:flutter_carplay/android_auto_worker.dart'
+ show FlutterAndroidAuto;
+export 'package:flutter_carplay/carplay_worker.dart' show FlutterCarplay;
+export 'package:flutter_carplay/constants/constants.dart'
+ show ConnectionStatusTypes;
+export 'package:flutter_carplay/helpers/enum_utils.dart';
+export 'package:flutter_carplay/models/action_sheet/action_sheet_template.dart'
+ show CPActionSheetTemplate;
+export 'package:flutter_carplay/models/alert/alert_action.dart'
+ show CPAlertAction;
+export 'package:flutter_carplay/models/alert/alert_constants.dart'
+ show CPAlertActionStyles;
+export 'package:flutter_carplay/models/alert/alert_template.dart'
+ show CPAlertTemplate;
+export 'package:flutter_carplay/models/button/alert_constants.dart'
+ show CPBarButtonStyles;
+export 'package:flutter_carplay/models/button/bar_button.dart' show CPBarButton;
+export 'package:flutter_carplay/models/button/text_button.dart'
+ show CPTextButton;
+export 'package:flutter_carplay/models/grid/grid_button.dart' show CPGridButton;
+export 'package:flutter_carplay/models/grid/grid_template.dart'
+ show CPGridTemplate;
+export 'package:flutter_carplay/models/information/information_constants.dart'
+ show CPInformationTemplateLayout;
+export 'package:flutter_carplay/models/information/information_item.dart'
+ show CPInformationItem;
+export 'package:flutter_carplay/models/information/information_template.dart'
+ show CPInformationTemplate;
+export 'package:flutter_carplay/models/list/list_constants.dart'
+ show CPListItemAccessoryTypes, CPListItemPlayingIndicatorLocations;
+export 'package:flutter_carplay/models/list/list_item.dart' show CPListItem;
+export 'package:flutter_carplay/models/list/list_section.dart'
+ show CPListSection;
+export 'package:flutter_carplay/models/list/list_template.dart'
+ show CPListTemplate;
+export 'package:flutter_carplay/models/poi/poi.dart' show CPPointOfInterest;
+export 'package:flutter_carplay/models/poi/poi_template.dart'
+ show CPPointOfInterestTemplate;
+export 'package:flutter_carplay/models/tabbar/tabbar_template.dart'
+ show CPTabBarTemplate;
diff --git a/packages/flutter_carplay/lib/helpers/auto_android_helper.dart b/packages/flutter_carplay/lib/helpers/auto_android_helper.dart
new file mode 100644
index 00000000..b67744c0
--- /dev/null
+++ b/packages/flutter_carplay/lib/helpers/auto_android_helper.dart
@@ -0,0 +1,38 @@
+import 'package:flutter_carplay/aa_models/template.dart';
+import 'package:flutter_carplay/flutter_carplay.dart';
+
+class FlutterAutoAndroidHelper {
+ const FlutterAutoAndroidHelper();
+
+ AAListItem? findAAListItem({
+ required List<AATemplate> templates,
+ required String elementId,
+ }) {
+ for (var t in templates) {
+ final List<AAListTemplate> listTemplates = [];
+
+ /*if (t.runtimeType.toString() == (AATabBarTemplate).toString()) {
+ for (var template in t.templates) {
+ listTemplates.add(template);
+ }
+ } else*/
+ if (t is AAListTemplate) {
+ listTemplates.add(t);
+ }
+
+ for (var list in listTemplates) {
+ for (var section in list.sections) {
+ for (var item in section.items) {
+ if (item.uniqueId == elementId) {
+ return item;
+ }
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ String makeFAAChannelId({String event = ''}) =>
+ 'com.oguzhnatly.flutter_android_auto$event';
+}
diff --git a/packages/flutter_carplay/lib/helpers/carplay_helper.dart b/packages/flutter_carplay/lib/helpers/carplay_helper.dart
new file mode 100644
index 00000000..e7e5efb6
--- /dev/null
+++ b/packages/flutter_carplay/lib/helpers/carplay_helper.dart
@@ -0,0 +1,39 @@
+import 'package:flutter_carplay/flutter_carplay.dart';
+
+class FlutterCarplayHelper {
+ CPListItem? findCPListItem({
+ required List<dynamic> templates,
+ required String elementId,
+ }) {
+ CPListItem? listItem;
+ l1:
+ for (var t in templates) {
+ final List<CPListTemplate> listTemplates = [];
+ if (t is CPTabBarTemplate) {
+ for (var template in t.templates) {
+ if (template is CPListTemplate) {
+ listTemplates.add(template);
+ }
+ }
+ } else if (t is CPListTemplate) {
+ listTemplates.add(t);
+ }
+ if (listTemplates.isNotEmpty) {
+ for (var list in listTemplates) {
+ for (var section in list.sections) {
+ for (var item in section.items) {
+ if (item.uniqueId == elementId) {
+ listItem = item;
+ break l1;
+ }
+ }
+ }
+ }
+ }
+ }
+ return listItem;
+ }
+
+ String makeFCPChannelId({String? event = ''}) =>
+ 'com.oguzhnatly.flutter_carplay${event!}';
+}
diff --git a/packages/flutter_carplay/lib/helpers/enum_utils.dart b/packages/flutter_carplay/lib/helpers/enum_utils.dart
new file mode 100644
index 00000000..f615da32
--- /dev/null
+++ b/packages/flutter_carplay/lib/helpers/enum_utils.dart
@@ -0,0 +1,19 @@
+class EnumUtils {
+ const EnumUtils();
+
+ static T enumFromString<T>(Iterable<T> values, String string) {
+ return values.firstWhere(
+ (f) =>
+ f
+ .toString()
+ .substring(f.toString().indexOf('.') + 1)
+ .toString()
+ .toUpperCase() ==
+ string.substring(string.indexOf('.') + 1).toString().toUpperCase(),
+ );
+ }
+
+ static String stringFromEnum(Object value) {
+ return value.toString().split('.').last;
+ }
+}
diff --git a/packages/flutter_carplay/lib/models/action_sheet/action_sheet_template.dart b/packages/flutter_carplay/lib/models/action_sheet/action_sheet_template.dart
new file mode 100644
index 00000000..b8d19c55
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/action_sheet/action_sheet_template.dart
@@ -0,0 +1,36 @@
+import 'package:flutter_carplay/models/alert/alert_action.dart';
+import 'package:uuid/uuid.dart';
+
+import '../template.dart';
+
+/// A template object that displays a modal action sheet.
+class CPActionSheetTemplate implements CPTemplate, CPActionsTemplate {
+ /// Unique id of the object.
+ final String _elementId = const Uuid().v4();
+
+ /// The title of the action sheet.
+ final String? title;
+
+ /// The descriptive message providing details about the reason for displaying the action sheet.
+ final String? message;
+
+ /// The list of actions as [CPAlertAction] available on the action sheet.
+ @override
+ final List<CPAlertAction> actions;
+
+ /// Creates [CPActionSheetTemplate] with a title, a message and a list of actions available on the action sheet.
+ CPActionSheetTemplate({this.title, this.message, required this.actions});
+
+ @override
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'title': title,
+ 'message': message,
+ 'actions': actions.map((e) => e.toJson()).toList(),
+ };
+
+ @override
+ String get uniqueId {
+ return _elementId;
+ }
+}
diff --git a/packages/flutter_carplay/lib/models/alert/alert_action.dart b/packages/flutter_carplay/lib/models/alert/alert_action.dart
new file mode 100644
index 00000000..3dba5626
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/alert/alert_action.dart
@@ -0,0 +1,36 @@
+import 'package:flutter_carplay/helpers/enum_utils.dart';
+import 'package:flutter_carplay/models/alert/alert_constants.dart';
+import 'package:uuid/uuid.dart';
+
+/// An object that encapsulates an action the user can take on [CPActionSheetTemplate] or [CPAlertTemplate].
+class CPAlertAction {
+ /// Unique id of the object.
+ final String _elementId = const Uuid().v4();
+
+ /// The action button's title.
+ final String title;
+
+ /// The display style for the action button.
+ /// Default is [CPAlertActionStyles.normal]
+ final CPAlertActionStyles style;
+
+ /// A callback function that CarPlay invokes after the user taps the action button.
+ final Function() onPress;
+
+ /// Creates [CPAlertAction] with a title, style, and action handler.
+ CPAlertAction({
+ required this.title,
+ this.style = CPAlertActionStyles.normal,
+ required this.onPress,
+ });
+
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'title': title,
+ 'style': EnumUtils.stringFromEnum(style.toString()),
+ };
+
+ String get uniqueId {
+ return _elementId;
+ }
+}
diff --git a/packages/flutter_carplay/lib/models/alert/alert_constants.dart b/packages/flutter_carplay/lib/models/alert/alert_constants.dart
new file mode 100644
index 00000000..af52b2ba
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/alert/alert_constants.dart
@@ -0,0 +1 @@
+enum CPAlertActionStyles { normal, cancel, destructive }
diff --git a/packages/flutter_carplay/lib/models/alert/alert_template.dart b/packages/flutter_carplay/lib/models/alert/alert_template.dart
new file mode 100644
index 00000000..442a9df2
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/alert/alert_template.dart
@@ -0,0 +1,48 @@
+import 'package:flutter_carplay/models/alert/alert_action.dart';
+import 'package:uuid/uuid.dart';
+
+import '../template.dart';
+
+/// A template object that displays a modal alert.
+class CPAlertTemplate implements CPTemplate, CPActionsTemplate {
+ /// Unique id of the object.
+ final String _elementId = const Uuid().v4();
+
+ /// The array of title variants.
+ /// When the system displays the alert, it selects the title that best fits
+ /// the available screen space, so arrange the titles from most to least preferred
+ /// when creating an alert template. Also, localize each title for display to the user,
+ /// and **be sure to include at least one title in the array.**
+ final List<String> titleVariants;
+
+ /// The array of actions as [CPAlertAction] will be available on the alert.
+ @override
+ final List<CPAlertAction> actions;
+
+ /// Fired when the alert presented to CarPlay. With this callback function, it can be
+ /// determined whether an error was encountered while presenting, or if it was successfully opened,
+ /// with the [bool] completed data in it.
+ ///
+ /// If completed is true, the alert successfully presented. If not, you may want to show an error to the user.
+ final Function(bool completed)? onPresent;
+
+ /// Creates [CPAlertTemplate]
+ CPAlertTemplate({
+ required this.titleVariants,
+ required this.actions,
+ this.onPresent,
+ });
+
+ @override
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'titleVariants': titleVariants,
+ 'actions': actions.map((e) => e.toJson()).toList(),
+ 'onPresent': onPresent != null ? true : false,
+ };
+
+ @override
+ String get uniqueId {
+ return _elementId;
+ }
+}
diff --git a/packages/flutter_carplay/lib/models/button/alert_constants.dart b/packages/flutter_carplay/lib/models/button/alert_constants.dart
new file mode 100644
index 00000000..d1d3ee0d
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/button/alert_constants.dart
@@ -0,0 +1 @@
+enum CPBarButtonStyles { none, rounded }
diff --git a/packages/flutter_carplay/lib/models/button/bar_button.dart b/packages/flutter_carplay/lib/models/button/bar_button.dart
new file mode 100644
index 00000000..e598ba52
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/button/bar_button.dart
@@ -0,0 +1,36 @@
+import 'package:flutter_carplay/helpers/enum_utils.dart';
+import 'package:flutter_carplay/models/button/alert_constants.dart';
+import 'package:uuid/uuid.dart';
+
+/// A button object for placement in a navigation bar.
+class CPBarButton {
+ /// Unique id of the object.
+ final String _elementId = const Uuid().v4();
+
+ /// The title displayed on the bar button.
+ final String title;
+
+ /// The style to use when displaying the button.
+ /// Default is [CPBarButtonStyles.rounded]
+ final CPBarButtonStyles style;
+
+ /// Fired when the user taps a bar button.
+ final Function() onPress;
+
+ /// Creates [CPBarButton] with a title, style and handler.
+ CPBarButton({
+ required this.title,
+ this.style = CPBarButtonStyles.rounded,
+ required this.onPress,
+ });
+
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'title': title,
+ 'style': EnumUtils.stringFromEnum(style.toString()),
+ };
+
+ String get uniqueId {
+ return _elementId;
+ }
+}
diff --git a/packages/flutter_carplay/lib/models/button/text_button.dart b/packages/flutter_carplay/lib/models/button/text_button.dart
new file mode 100644
index 00000000..0afdd31b
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/button/text_button.dart
@@ -0,0 +1,37 @@
+import 'package:flutter_carplay/helpers/enum_utils.dart';
+import 'package:uuid/uuid.dart';
+
+enum CPTextButtonStyles { normal, cancel, confirm }
+
+/// A button object for placement in a point of interest or information template.
+class CPTextButton {
+ /// Unique id of the object.
+ final String _elementId = const Uuid().v4();
+
+ /// The title displayed on the bar button.
+ final String title;
+
+ /// The style to use when displaying the button.
+ /// Default is [CPTextButtonStyles.normal]
+ final CPTextButtonStyles style;
+
+ /// Fired when the user taps a text button.
+ final Function() onPress;
+
+ /// Creates [CPTextButton] with a title, style and handler.
+ CPTextButton({
+ required this.title,
+ this.style = CPTextButtonStyles.normal,
+ required this.onPress,
+ });
+
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'title': title,
+ 'style': EnumUtils.stringFromEnum(style.toString()),
+ };
+
+ String get uniqueId {
+ return _elementId;
+ }
+}
diff --git a/packages/flutter_carplay/lib/models/grid/grid_button.dart b/packages/flutter_carplay/lib/models/grid/grid_button.dart
new file mode 100644
index 00000000..f6ddc959
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/grid/grid_button.dart
@@ -0,0 +1,44 @@
+import 'package:uuid/uuid.dart';
+
+/// A grid button object displayed on a grid template.
+class CPGridButton {
+ /// Unique id of the object.
+ final String _elementId = const Uuid().v4();
+
+ /// An array of title variants for the button.
+ /// When the system displays the button, it selects the title that best fits the available
+ /// screen space, so arrange the titles from most to least preferred when creating a grid button.
+ /// Also, localize each title for display to the user, and **be sure to include at least
+ /// one title in the array.**
+ final List<String> titleVariants;
+
+ /// The image displayed on the button.
+ ///
+ /// Supports three formats:
+ /// - **Asset path**: `images/flutter_logo.png` (from pubspec.yaml assets)
+ /// - **File path**: `file:///path/to/image.png` (local file on device)
+ /// - **Network URL**: `https://example.com/image.png` (remote image)
+ ///
+ /// **[!] When creating a grid button, do NOT provide an animated image. If you do, the button
+ /// uses the first image in the animation sequence.**
+ final String image;
+
+ /// Fired after the user taps the button.
+ final Function() onPress;
+
+ CPGridButton({
+ required this.titleVariants,
+ required this.image,
+ required this.onPress,
+ });
+
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'titleVariants': titleVariants,
+ 'image': image,
+ };
+
+ String get uniqueId {
+ return _elementId;
+ }
+}
diff --git a/packages/flutter_carplay/lib/models/grid/grid_template.dart b/packages/flutter_carplay/lib/models/grid/grid_template.dart
new file mode 100644
index 00000000..43c076ea
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/grid/grid_template.dart
@@ -0,0 +1,33 @@
+import 'package:flutter_carplay/models/grid/grid_button.dart';
+import 'package:uuid/uuid.dart';
+
+import '../template.dart';
+
+/// A template object that displays and manages a grid of items.
+class CPGridTemplate implements CPTemplate {
+ /// Unique id of the object.
+ final String _elementId = const Uuid().v4();
+
+ /// A title will be shown in the navigation bar.
+ final String title;
+
+ /// The array of grid buttons as [CPGridButton] displayed on the template.
+ final List<CPGridButton> buttons;
+
+ /// Creates [CPGridTemplate] in order to display a grid of items as buttons.
+ /// When creating the grid template, provide an array of [CPGridButton] objects.
+ /// Each button must contain a title that is shown in the grid template's navigation bar.
+ CPGridTemplate({required this.title, required this.buttons});
+
+ @override
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'title': title,
+ 'buttons': buttons.map((e) => e.toJson()).toList(),
+ };
+
+ @override
+ String get uniqueId {
+ return _elementId;
+ }
+}
diff --git a/packages/flutter_carplay/lib/models/information/information_constants.dart b/packages/flutter_carplay/lib/models/information/information_constants.dart
new file mode 100644
index 00000000..97307f73
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/information/information_constants.dart
@@ -0,0 +1 @@
+enum CPInformationTemplateLayout { leading, twoColumn }
diff --git a/packages/flutter_carplay/lib/models/information/information_item.dart b/packages/flutter_carplay/lib/models/information/information_item.dart
new file mode 100644
index 00000000..b7fcf564
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/information/information_item.dart
@@ -0,0 +1,22 @@
+import 'package:uuid/uuid.dart';
+
+/// A information item object displayed on a information template.
+class CPInformationItem {
+ /// Unique id of the object.
+ final String _elementId = const Uuid().v4();
+
+ final String? title;
+ final String? detail;
+
+ CPInformationItem({this.title, this.detail});
+
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'title': title,
+ 'detail': detail,
+ };
+
+ String get uniqueId {
+ return _elementId;
+ }
+}
diff --git a/packages/flutter_carplay/lib/models/information/information_template.dart b/packages/flutter_carplay/lib/models/information/information_template.dart
new file mode 100644
index 00000000..da5d291e
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/information/information_template.dart
@@ -0,0 +1,47 @@
+import 'package:flutter_carplay/helpers/enum_utils.dart';
+import 'package:flutter_carplay/models/button/text_button.dart';
+import 'package:uuid/uuid.dart';
+
+import '../template.dart';
+import 'information_constants.dart';
+import 'information_item.dart';
+
+/// A template object that displays and manages information items and text buttons.
+class CPInformationTemplate implements CPTemplate {
+ /// Unique id of the object.
+ final String _elementId = const Uuid().v4();
+
+ /// A title will be shown in the navigation bar.
+ final String title;
+
+ final CPInformationTemplateLayout layout;
+
+ /// The array of actions as [CPTextButton] displayed on the template.
+ final List<CPTextButton> actions;
+
+ /// The array of information items as [CPInformationItem] displayed on the template.
+
+ final List<CPInformationItem> informationItems;
+
+ /// Creates [CPInformationTemplate]
+ CPInformationTemplate({
+ required this.title,
+ required this.layout,
+ required this.actions,
+ required this.informationItems,
+ });
+
+ @override
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'layout': EnumUtils.stringFromEnum(layout.toString()),
+ 'title': title,
+ 'actions': actions.map((e) => e.toJson()).toList(),
+ 'informationItems': informationItems.map((e) => e.toJson()).toList(),
+ };
+
+ @override
+ String get uniqueId {
+ return _elementId;
+ }
+}
diff --git a/packages/flutter_carplay/lib/models/list/list_constants.dart b/packages/flutter_carplay/lib/models/list/list_constants.dart
new file mode 100644
index 00000000..9ffc04ef
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/list/list_constants.dart
@@ -0,0 +1,3 @@
+enum CPListItemPlayingIndicatorLocations { trailing, leading }
+
+enum CPListItemAccessoryTypes { none, cloud, disclosureIndicator }
diff --git a/packages/flutter_carplay/lib/models/list/list_item.dart b/packages/flutter_carplay/lib/models/list/list_item.dart
new file mode 100644
index 00000000..ab7266b4
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/list/list_item.dart
@@ -0,0 +1,134 @@
+import 'package:flutter_carplay/controllers/carplay_controller.dart';
+import 'package:flutter_carplay/helpers/enum_utils.dart';
+import 'package:flutter_carplay/models/list/list_constants.dart';
+import 'package:uuid/uuid.dart';
+
+/// A selectable list item object that appears in a list template.
+class CPListItem {
+ /// Unique id of the object.
+ final String _elementId = const Uuid().v4();
+
+ /// Text displayed in the list item cell.
+ String text;
+
+ /// Secondary text displayed below the primary text in the list item cell.
+ String? detailText;
+
+ /// An optional callback function that CarPlay invokes when the user selects the list item.
+ final Function(Function() complete, CPListItem self)? onPress;
+
+ /// Displays an image on the leading edge of the list item cell.
+ ///
+ /// Supports three formats:
+ /// - **Asset path**: `images/flutter_logo.png` (from pubspec.yaml assets)
+ /// - **File path**: `file:///path/to/image.png` (local file on device)
+ /// - **Network URL**: `https://example.com/image.png` (remote image)
+ String? image;
+
+ /// Playback progress status for the content that the list item represents.
+ double? playbackProgress;
+
+ /// Determines whether the list item displays its Now Playing indicator.
+ bool? isPlaying;
+
+ /// The location where the list item displays its Now Playing indicator.
+ CPListItemPlayingIndicatorLocations? playingIndicatorLocation;
+
+ /// An accessory that the list item displays in its trailing region.
+ CPListItemAccessoryTypes? accessoryType;
+
+ /// Creates [CPListItem] that manages the content of a single row in a [CPListTemplate].
+ /// CarPlay manages the layout of a list item and may adjust its layout to allow for
+ /// the display of auxiliary content, such as, an accessory or a Now Playing indicator.
+ /// A list item can display primary text, secondary text, now playing indicators as playback progress,
+ /// an accessory image and a trailing image.
+ CPListItem({
+ required this.text,
+ this.detailText,
+ this.onPress,
+ this.image,
+ this.playbackProgress,
+ this.isPlaying,
+ this.playingIndicatorLocation,
+ this.accessoryType,
+ });
+
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'text': text,
+ 'detailText': detailText,
+ 'onPress': onPress != null ? true : false,
+ 'image': image,
+ 'playbackProgress': playbackProgress,
+ 'isPlaying': isPlaying,
+ 'playingIndicatorLocation': EnumUtils.stringFromEnum(
+ playingIndicatorLocation.toString(),
+ ),
+ 'accessoryType': EnumUtils.stringFromEnum(accessoryType.toString()),
+ };
+
+ /// Updating the list item's primary text.
+ void setText(String text) {
+ this.text = text;
+ FlutterCarPlayController.updateCPListItem(this);
+ }
+
+ /// Updating the list item's secondary text.
+ void setDetailText(String detailText) {
+ this.detailText = detailText;
+ FlutterCarPlayController.updateCPListItem(this);
+ }
+
+ /// Updating the list item's both the primary and detail text at the same time.
+ void updateTexts({String? text, String? detailText}) {
+ this.text = text ?? this.text;
+ this.detailText = detailText ?? this.detailText;
+ FlutterCarPlayController.updateCPListItem(this);
+ }
+
+ /// Updating the image which will be displayed on the leading edge of the list item cell.
+ ///
+ /// Supports three formats:
+ /// - **Asset path**: `images/flutter_logo.png` (from pubspec.yaml assets)
+ /// - **File path**: `file:///path/to/image.png` (local file on device)
+ /// - **Network URL**: `https://example.com/image.png` (remote image)
+ set updateImage(String image) {
+ this.image = image;
+ FlutterCarPlayController.updateCPListItem(this);
+ }
+
+ /// Setter for playbackProgress
+ /// When the given value is not between 0.0 and 1.0, throws [RangeError]
+ void setPlaybackProgress(double playbackProgress) {
+ if (playbackProgress >= 0.0 && playbackProgress <= 1.0) {
+ this.playbackProgress = playbackProgress;
+ FlutterCarPlayController.updateCPListItem(this);
+ } else {
+ throw RangeError('playbackProgress must be between 0.0 and 1.0');
+ }
+ }
+
+ /// Setter for isPlaying
+ void setIsPlaying(bool isPlaying) {
+ this.isPlaying = isPlaying;
+ FlutterCarPlayController.updateCPListItem(this);
+ }
+
+ /// Setter for playingIndicatorLocation
+ void setPlayingIndicatorLocation(
+ CPListItemPlayingIndicatorLocations playingIndicatorLocation,
+ ) {
+ this.playingIndicatorLocation = playingIndicatorLocation;
+ FlutterCarPlayController.updateCPListItem(this);
+ }
+
+ /// Setter for accessoryType
+ void setAccessoryType(CPListItemAccessoryTypes accessoryType) {
+ this.accessoryType = accessoryType;
+ FlutterCarPlayController.updateCPListItem(this);
+ }
+
+ String get uniqueId {
+ return _elementId;
+ }
+}
diff --git a/packages/flutter_carplay/lib/models/list/list_section.dart b/packages/flutter_carplay/lib/models/list/list_section.dart
new file mode 100644
index 00000000..eb3d5578
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/list/list_section.dart
@@ -0,0 +1,28 @@
+import 'package:flutter_carplay/models/list/list_item.dart';
+import 'package:uuid/uuid.dart';
+
+/// A section object of list items that appear in a list template.
+class CPListSection {
+ /// Unique id of the object.
+ final String _elementId = const Uuid().v4();
+
+ /// Header text of the section.
+ final String? header;
+
+ /// A list of items as [[CPListItem]] to include in the section.
+ final List<CPListItem> items;
+
+ /// Creates [CPListSection] that contains zero or more list items. You can configure
+ /// a section to display a header, which CarPlay displays on the trailing edge of the screen.
+ CPListSection({this.header, required this.items});
+
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'header': header,
+ 'items': items.map((e) => e.toJson()).toList(),
+ };
+
+ String get uniqueId {
+ return _elementId;
+ }
+}
diff --git a/packages/flutter_carplay/lib/models/list/list_template.dart b/packages/flutter_carplay/lib/models/list/list_template.dart
new file mode 100644
index 00000000..d2d67073
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/list/list_template.dart
@@ -0,0 +1,108 @@
+import 'package:flutter_carplay/models/button/bar_button.dart';
+import 'package:flutter_carplay/models/list/list_section.dart';
+import 'package:uuid/uuid.dart';
+
+import '../template.dart';
+
+/// A template object that displays and manages a list of items.
+class CPListTemplate implements CPTemplate {
+ /// Unique id of the object.
+ final String _elementId = const Uuid().v4();
+
+ /// A title displayed in the navigation bar.
+ /// It will be displayed when only the list template is visible.
+ final String? title;
+
+ /// An array of list sections as [CPListSection], each can contain zero or more list items.
+ final List<CPListSection> sections;
+
+ /// An optional array of title variants for the template’s empty view.
+ /// Provide the strings as localized displayable content and order from most- to
+ /// least- preferred. When there are no items in the list, the template displays
+ /// an empty view with a title and a subtitle in place of the items. If you update
+ /// the list and provide items, the template automatically removes the empty view.
+ final List<String>? emptyViewTitleVariants;
+
+ /// An optional array of subtitle variants for the template’s empty view.
+ /// Provide the strings as localized displayable content and order from most- to
+ /// least- preferred. When there are no items in the list, the template displays
+ /// an empty view with a title and a subtitle in place of the items. If you update
+ /// the list and provide items, the template automatically removes the empty view.
+ final List<String>? emptyViewSubtitleVariants;
+
+ /// An indicator you use to call attention to the tab. When it is true, a small
+ /// red indicator will be displayed on the tab in order to show user that it requires
+ /// an action or you received an notification e.g.
+ ///
+ /// CarPlay only displays the red indicator when the template is a root-template
+ /// of a tab bar, otherwise setting this property has no effect.
+ final bool showsTabBadge;
+
+ /// A system icon which will be used in a image that represents the content of the tab.
+ ///
+ /// SF Symbols provides a set of over 3,100 consistent, highly configurable symbols you can
+ /// use in your app. Apple designed SF Symbols to integrate seamlessly with the San Francisco
+ /// system font, so the symbols automatically align with text in all weights and sizes.
+ ///
+ /// **See**:
+ /// - [SF Symbols Apple Website](https://developer.apple.com/sf-symbols/)
+ /// - [SF Symbols - Human Interface Guidelines](https://developer.apple.com/design/human-interface-guidelines/sf-symbols/overview/)
+ ///
+ /// **IMPORTANT:**
+ /// All SF Symbols shall be considered to be system-provided images as defined in the Xcode and Apple SDKs
+ /// license agreements and are subject to the terms and conditions set forth therein. You may not use SF
+ /// Symbols—or glyphs that are substantially or confusingly similar—in your app icons, logos, or any other
+ /// trademark-related use. Apple reserves the right to review and, in its sole discretion, require modification
+ /// or discontinuance of use of any Symbol used in violation of the foregoing restrictions, and you agree to
+ /// promptly comply with any such request.
+ final String systemIcon;
+
+ /// Back button object
+ final CPBarButton? backButton;
+
+ /// Whether to show the section index (alphabetical letters) in the scroll bar.
+ /// When true, the first letter of each section header appears on the right edge
+ /// for quick navigation. Section headers are always shown regardless of this setting.
+ /// Defaults to true.
+ final bool sectionIndexEnabled;
+
+ /// Creates [CPListTemplate] to display a list of items, grouped into one or more sections.
+ /// Each section contains an array of list items — objects that is [CPListItem]
+ ///
+ /// **Consider that some vehicles limit the number of items that [CPListTemplate] displays.**
+ CPListTemplate({
+ this.title,
+ required this.sections,
+ this.emptyViewTitleVariants,
+ this.emptyViewSubtitleVariants,
+ this.showsTabBadge = false,
+ required this.systemIcon,
+ this.backButton,
+ this.sectionIndexEnabled = true,
+ });
+
+ @override
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'title': title,
+ 'sections': sections.map((e) => e.toJson()).toList(),
+ 'emptyViewTitleVariants': emptyViewTitleVariants,
+ 'emptyViewSubtitleVariants': emptyViewSubtitleVariants,
+ 'showsTabBadge': showsTabBadge,
+ 'systemIcon': systemIcon,
+ 'backButton': backButton?.toJson(),
+ 'sectionIndexEnabled': sectionIndexEnabled,
+ };
+
+ @override
+ String get uniqueId {
+ return _elementId;
+ }
+
+ void updateSections(List<CPListSection> newSections) {
+ final copy = List<CPListSection>.from(newSections);
+ sections
+ ..clear()
+ ..addAll(copy);
+ }
+}
diff --git a/packages/flutter_carplay/lib/models/poi/poi.dart b/packages/flutter_carplay/lib/models/poi/poi.dart
new file mode 100644
index 00000000..7a03f178
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/poi/poi.dart
@@ -0,0 +1,63 @@
+import 'package:uuid/uuid.dart';
+import '../button/text_button.dart';
+
+/// A section object of list items that appear in a list template.
+class CPPointOfInterest {
+ /// Unique id of the object.
+ final String _elementId = const Uuid().v4();
+
+ /// Header text of the section.
+ double latitude = 0.0;
+ double longitude = 0.0;
+ String title = '';
+ String? subtitle;
+ String? summary;
+ String? detailTitle;
+ String? detailSubtitle;
+ String? detailSummary;
+
+ /// The image displayed for this point of interest.
+ ///
+ /// Supports three formats:
+ /// - **Asset path**: `images/marker.png` (from pubspec.yaml assets)
+ /// - **File path**: `file:///path/to/image.png` (local file on device)
+ /// - **Network URL**: `https://example.com/image.png` (remote image)
+ String? image;
+
+ final CPTextButton? primaryButton;
+ final CPTextButton? secondaryButton;
+
+ /// Creates [CPPointOfInterest]
+ CPPointOfInterest({
+ required this.latitude,
+ required this.longitude,
+ required this.title,
+ this.subtitle,
+ this.summary,
+ this.detailTitle,
+ this.detailSubtitle,
+ this.detailSummary,
+ this.image,
+ this.primaryButton,
+ this.secondaryButton,
+ });
+
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'latitude': latitude,
+ 'longitude': longitude,
+ 'title': title,
+ 'subtitle': subtitle,
+ 'summary': summary,
+ 'detailTitle': detailTitle,
+ 'detailSubtitle': detailSubtitle,
+ 'detailSummary': detailSummary,
+ 'image': image,
+ 'primaryButton': primaryButton?.toJson(),
+ 'secondaryButton': secondaryButton?.toJson(),
+ };
+
+ String get uniqueId {
+ return _elementId;
+ }
+}
diff --git a/packages/flutter_carplay/lib/models/poi/poi_template.dart b/packages/flutter_carplay/lib/models/poi/poi_template.dart
new file mode 100644
index 00000000..b7730ca6
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/poi/poi_template.dart
@@ -0,0 +1,29 @@
+import 'package:uuid/uuid.dart';
+
+import '../template.dart';
+import 'poi.dart';
+
+/// A template object that displays point of interest.
+class CPPointOfInterestTemplate implements CPTemplate {
+ /// Unique id of the object.
+ final String _elementId = const Uuid().v4();
+
+ /// A title will be shown in the navigation bar.
+ final String title;
+ final List<CPPointOfInterest> poi;
+
+ /// Creates [CPPointOfInterestTemplate]
+ CPPointOfInterestTemplate({required this.title, required this.poi});
+
+ @override
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'title': title,
+ 'poi': poi.map((e) => e.toJson()).toList(),
+ };
+
+ @override
+ String get uniqueId {
+ return _elementId;
+ }
+}
diff --git a/packages/flutter_carplay/lib/models/tabbar/tabbar_template.dart b/packages/flutter_carplay/lib/models/tabbar/tabbar_template.dart
new file mode 100644
index 00000000..bccb1bfe
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/tabbar/tabbar_template.dart
@@ -0,0 +1,74 @@
+import 'package:flutter_carplay/models/action_sheet/action_sheet_template.dart';
+import 'package:flutter_carplay/models/alert/alert_template.dart';
+import 'package:flutter_carplay/models/grid/grid_template.dart';
+import 'package:flutter_carplay/models/information/information_template.dart';
+import 'package:flutter_carplay/models/list/list_template.dart';
+import 'package:flutter_carplay/models/poi/poi_template.dart';
+import 'package:uuid/uuid.dart';
+
+import '../template.dart';
+
+/// A template object that contains a collection of [CPTemplate] templates,
+/// each of which occupies one tab in the tab bar.
+/// Supported template types: [CPListTemplate], [CPPointOfInterestTemplate],
+/// [CPGridTemplate], [CPInformationTemplate], [CPActionSheetTemplate], [CPAlertTemplate]
+class CPTabBarTemplate implements CPTemplate {
+ /// Unique id of the object.
+ final String _elementId = const Uuid().v4();
+
+ /// A title that describes the content of the tab.
+ ///
+ /// CarPlay only displays the title when the template is a root-template of a tab
+ /// bar, otherwise setting this property has no effect.
+ final String? title;
+
+ /// The templates to show as tabs.
+ /// Supported types: [CPListTemplate], [CPPointOfInterestTemplate],
+ /// [CPGridTemplate], [CPInformationTemplate]
+ final List<CPTemplate> templates;
+
+ /// When creating a [CPTabBarTemplate], provide an array of templates for the tab bar to display.
+ /// CarPlay treats the array’s templates as root templates, each with its own
+ /// navigation hierarchy. When a tab bar template is the rootTemplate of your
+ /// app’s interface controller and you use the controller to add and remove templates,
+ /// CarPlay applies those changes to the selected tab’s navigation hierarchy.
+ ///
+ /// [!] You can’t add a tab bar template to an existing navigation hierarchy,
+ /// or present one modally.
+ CPTabBarTemplate({this.title, required List<CPTemplate> templates})
+ : templates = List<CPTemplate>.from(templates);
+
+ @override
+ Map<String, dynamic> toJson() => {
+ '_elementId': _elementId,
+ 'title': title,
+ 'templates': templates.map((e) => _templateToJson(e)).toList(),
+ };
+
+ /// Converts a template to JSON with its runtime type identifier.
+ Map<String, dynamic> _templateToJson(CPTemplate template) {
+ final json = template.toJson();
+ if (template is CPListTemplate) {
+ json['runtimeType'] = 'FCPListTemplate';
+ } else if (template is CPPointOfInterestTemplate) {
+ json['runtimeType'] = 'FCPPointOfInterestTemplate';
+ } else if (template is CPGridTemplate) {
+ json['runtimeType'] = 'FCPGridTemplate';
+ } else if (template is CPInformationTemplate) {
+ json['runtimeType'] = 'FCPInformationTemplate';
+ }
+ return json;
+ }
+
+ @override
+ String get uniqueId {
+ return _elementId;
+ }
+
+ void updateTemplates(List<CPTemplate> newTemplates) {
+ final copy = List<CPTemplate>.from(newTemplates);
+ templates
+ ..clear()
+ ..addAll(copy);
+ }
+}
diff --git a/packages/flutter_carplay/lib/models/template.dart b/packages/flutter_carplay/lib/models/template.dart
new file mode 100644
index 00000000..15ec612a
--- /dev/null
+++ b/packages/flutter_carplay/lib/models/template.dart
@@ -0,0 +1,15 @@
+import 'alert/alert_action.dart';
+
+abstract interface class CPTemplate {
+ const CPTemplate();
+
+ String get uniqueId;
+
+ Map<String, dynamic> toJson();
+}
+
+abstract interface class CPActionsTemplate {
+ const CPActionsTemplate();
+
+ List<CPAlertAction> get actions;
+}
diff --git a/packages/flutter_carplay/previews/actionsheet_template.png b/packages/flutter_carplay/previews/actionsheet_template.png
new file mode 100644
index 00000000..0b888484
Binary files /dev/null and b/packages/flutter_carplay/previews/actionsheet_template.png differ
diff --git a/packages/flutter_carplay/previews/alert_template.png b/packages/flutter_carplay/previews/alert_template.png
new file mode 100644
index 00000000..12c414c2
Binary files /dev/null and b/packages/flutter_carplay/previews/alert_template.png differ
diff --git a/packages/flutter_carplay/previews/banner.png b/packages/flutter_carplay/previews/banner.png
new file mode 100644
index 00000000..29dd1894
Binary files /dev/null and b/packages/flutter_carplay/previews/banner.png differ
diff --git a/packages/flutter_carplay/previews/grid_template.png b/packages/flutter_carplay/previews/grid_template.png
new file mode 100644
index 00000000..40edc168
Binary files /dev/null and b/packages/flutter_carplay/previews/grid_template.png differ
diff --git a/packages/flutter_carplay/previews/information_template.png b/packages/flutter_carplay/previews/information_template.png
new file mode 100644
index 00000000..1527592c
Binary files /dev/null and b/packages/flutter_carplay/previews/information_template.png differ
diff --git a/packages/flutter_carplay/previews/list_template.png b/packages/flutter_carplay/previews/list_template.png
new file mode 100644
index 00000000..d38c9498
Binary files /dev/null and b/packages/flutter_carplay/previews/list_template.png differ
diff --git a/packages/flutter_carplay/previews/point_of_interest_template.png b/packages/flutter_carplay/previews/point_of_interest_template.png
new file mode 100644
index 00000000..f835cd7e
Binary files /dev/null and b/packages/flutter_carplay/previews/point_of_interest_template.png differ
diff --git a/packages/flutter_carplay/previews/step2.png b/packages/flutter_carplay/previews/step2.png
new file mode 100644
index 00000000..ca4aebda
Binary files /dev/null and b/packages/flutter_carplay/previews/step2.png differ
diff --git a/packages/flutter_carplay/previews/step3.png b/packages/flutter_carplay/previews/step3.png
new file mode 100644
index 00000000..50aa3485
Binary files /dev/null and b/packages/flutter_carplay/previews/step3.png differ
diff --git a/packages/flutter_carplay/previews/tabbar_template.png b/packages/flutter_carplay/previews/tabbar_template.png
new file mode 100644
index 00000000..76fe3e51
Binary files /dev/null and b/packages/flutter_carplay/previews/tabbar_template.png differ
diff --git a/packages/flutter_carplay/previews/templates.png b/packages/flutter_carplay/previews/templates.png
new file mode 100644
index 00000000..3fe00a0d
Binary files /dev/null and b/packages/flutter_carplay/previews/templates.png differ
diff --git a/packages/flutter_carplay/pubspec.yaml b/packages/flutter_carplay/pubspec.yaml
new file mode 100644
index 00000000..e524a695
--- /dev/null
+++ b/packages/flutter_carplay/pubspec.yaml
@@ -0,0 +1,29 @@
+name: flutter_carplay
+description: Flutter Apps are now on Apple CarPlay and Android Auto. This package aims to make it safe to use apps made with Flutter in the car by integrating with CarPlay or Android Auto.
+version: 1.2.11
+homepage: https://github.com/oguzhnatly/flutter_carplay#readme
+repository: https://github.com/oguzhnatly/flutter_carplay
+issue_tracker: https://github.com/oguzhnatly/flutter_carplay/issues
+
+environment:
+ sdk: ">=3.6.0 <4.0.0"
+ flutter: ">=1.10.0"
+
+dependencies:
+ flutter:
+ sdk: flutter
+ uuid: ^4.5.1
+
+dev_dependencies:
+ flutter_test:
+ sdk: flutter
+ flutter_lints: ^6.0.0
+
+flutter:
+ plugin:
+ platforms:
+ ios:
+ pluginClass: FlutterCarplayPlugin
+ android:
+ package: com.oguzhnatly.flutter_android_auto
+ pluginClass: FlutterAndroidAutoPlugin
diff --git a/packages/flutter_carplay/test/flutter_carplay_test.dart b/packages/flutter_carplay/test/flutter_carplay_test.dart
new file mode 100644
index 00000000..cfe7c283
--- /dev/null
+++ b/packages/flutter_carplay/test/flutter_carplay_test.dart
@@ -0,0 +1,15 @@
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ const MethodChannel channel = MethodChannel('flutter_carplay');
+
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ setUp(() {
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(channel, (MethodCall channel) async {
+ return '42';
+ });
+ });
+}
diff --git a/packages/flutter_carplay/test/helpers/carplay_helper_test.dart b/packages/flutter_carplay/test/helpers/carplay_helper_test.dart
new file mode 100644
index 00000000..a96d2e26
--- /dev/null
+++ b/packages/flutter_carplay/test/helpers/carplay_helper_test.dart
@@ -0,0 +1,53 @@
+import 'package:flutter_carplay/flutter_carplay.dart';
+import 'package:flutter_carplay/helpers/carplay_helper.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ group('FlutterCarplayHelper', () {
+ late FlutterCarplayHelper flutterCarplayHelper;
+
+ final cpListItem = CPListItem(text: '<CPListItem>');
+
+ final cpListTemplate = CPListTemplate(
+ title: '<CPListTemplate>',
+ sections: [
+ CPListSection(items: [cpListItem]),
+ ],
+ systemIcon: '<CarIcon>',
+ );
+
+ final templates = [
+ CPTabBarTemplate(
+ title: '<CPTabBarTemplate>',
+ templates: [cpListTemplate],
+ ),
+ cpListTemplate,
+ ];
+
+ setUp(() {
+ flutterCarplayHelper = FlutterCarplayHelper();
+ });
+
+ test('find CPListItem from dynamic list item and element id', () {
+ final CPListItem? item = flutterCarplayHelper.findCPListItem(
+ templates: templates,
+ elementId: cpListItem.uniqueId,
+ );
+
+ expect(item, cpListItem);
+
+ final CPListItem? nullableItem = flutterCarplayHelper.findCPListItem(
+ templates: templates,
+ elementId: '',
+ );
+
+ expect(nullableItem, null);
+ });
+
+ test('make FCP channel id', () {
+ final String channelId = flutterCarplayHelper.makeFCPChannelId(event: '/event');
+
+ expect(channelId, 'com.oguzhnatly.flutter_carplay/event');
+ });
+ });
+}
diff --git a/packages/flutter_carplay/test/helpers/enum_utils_test.dart b/packages/flutter_carplay/test/helpers/enum_utils_test.dart
new file mode 100644
index 00000000..7533163e
--- /dev/null
+++ b/packages/flutter_carplay/test/helpers/enum_utils_test.dart
@@ -0,0 +1,37 @@
+import 'package:flutter_carplay/flutter_carplay.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ group('EnumUtils', () {
+ test('convert string into any type of enum', () {
+ final cpListItemAccessoryType = EnumUtils.enumFromString(
+ CPListItemAccessoryTypes.values,
+ 'cloud',
+ );
+
+ expect(cpListItemAccessoryType, CPListItemAccessoryTypes.cloud);
+
+ final cpListItemPlayingIndicatorLocation = EnumUtils.enumFromString(
+ CPListItemPlayingIndicatorLocations.values,
+ 'trailing',
+ );
+
+ expect(
+ cpListItemPlayingIndicatorLocation,
+ CPListItemPlayingIndicatorLocations.trailing,
+ );
+ });
+
+ test('convert dynamic type into string after the `.`', () {
+ final cpAlertActionStylesString = EnumUtils.stringFromEnum(
+ CPAlertActionStyles.normal.toString(),
+ );
+
+ expect(cpAlertActionStylesString, 'normal');
+
+ final fcpChannelTypesString = EnumUtils.stringFromEnum('car.setAlert');
+
+ expect(fcpChannelTypesString, 'setAlert');
+ });
+ });
+}
diff --git a/pubspec.lock b/pubspec.lock
index 356e3b6e..4e478010 100644
--- a/pubspec.lock
+++ b/pubspec.lock
@@ -296,10 +296,9 @@ packages:
flutter_carplay:
dependency: "direct main"
description:
- name: flutter_carplay
- sha256: "134d5448a648573122af9d5a9e86c326f711150309eb518333a8bfad284604af"
- url: "https://pub.dev"
- source: hosted
+ path: "packages/flutter_carplay"
+ relative: true
+ source: path
version: "1.2.11"
flutter_chrome_cast:
dependency: "direct main"
diff --git a/pubspec.yaml b/pubspec.yaml
index cd428313..581f4fc7 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,7 +1,7 @@
name: absorb
description: An Audiobookshelf Client
publish_to: 'none'
-version: 1.8.97+167
+version: 1.8.97+168
environment:
sdk: '>=3.1.0 <4.0.0'
@@ -39,8 +39,10 @@ dependencies:
audio_service:
path: packages/audio_service
- # CarPlay
- flutter_carplay: ^1.2.11
+ # CarPlay - vendored copy of 1.2.11 with a patched image loader (downsampled +
+ # cached list thumbnails) so large browse lists don't run CarPlay out of memory.
+ flutter_carplay:
+ path: packages/flutter_carplay
# Permissions
permission_handler: ^12.0.1