id
stringlengths
14
17
text
stringlengths
23
1.11k
source
stringlengths
35
114
33cc08dd96bb-1
In Xcode, select File -> New -> Target from the menu bar. Select the app extension you intend to add. This selection generates extension-specific code within a new folder in your project. To learn more about the generated code and the SDKs for each extension point, check out the resources in Apple’s documentation. How do Flutter apps interact with App Extensions? Flutter apps interact with app extensions using the same techniques as UIKit or SwiftUI apps. The containing app and the app extension don’t communicate directly. The containing app might not be running while the device user interacts with the extension. The app and your extension can read and write to shared resources or use higher-level APIs to communicate with each other. Using higher-level APIs Some extensions have APIs. For example, the Core Spotlight framework indexes your app allowing users to search from Spotlight and Safari. The WidgetKit framework can trigger an update of your home screen widget.
https://docs.flutter.dev/development/platform-integration/ios/app-extensions/index.html
33cc08dd96bb-2
To simplify how your app communicates with extensions, Flutter plugins wrap these APIs. To find plugins that wrap extension APIs, check out Leveraging Apple’s System APIs and Frameworks or search pub.dev. Sharing resources To share resources between your Flutter app and your app extension, put the Runner app target and the extension target in the same App Group. Note: You must be signed in to your Apple Developer account. To add a target to an App Group: Open the target settings in Xcode. Navigate to the Signing & Capabilities tab. Select + Capability then App Groups. Choose which App Group you want to add the target from one of two options: Select an App Group from the list. Click + to add a new App Group.
https://docs.flutter.dev/development/platform-integration/ios/app-extensions/index.html
33cc08dd96bb-3
When two targets belong to the same App Group, they can read and write data to the same source. Choose one of the following sources for your data. Key/value: Use the shared_preference_app_group plugin to read or write to UserDefaults within the same App Group. File: Use the App Group container path from the path_provider plugin to read and write files. Database: Use the App Group container path from the path_provider plugin to create a database with the sqflite plugin. Background updates Background tasks provide a means to update your extension through code regardless of the status of your app. To schedule background work from your Flutter app, use the workmanager plugin. Deep linking You might want to direct users from an app extension to a specific page in your Flutter app. To have a URL open a specified route in your app, you can use Deep Linking. Creating app extension UIs with Flutter
https://docs.flutter.dev/development/platform-integration/ios/app-extensions/index.html
33cc08dd96bb-4
Creating app extension UIs with Flutter Some app extensions display a user interface. For example, iMessage extensions allow users to access your app’s content directly from the Messages app. Flutter does not support building Flutter UI for app extensions. To create the UI for an app extension using Flutter, you must compile a custom engine and embed the FlutterViewController as described in the following section. Note: Creating an app extension user interface with Flutter requires you to compile a custom build of the Flutter engine. The Flutter team cautions that only advanced users should try to create a custom build. To learn more, check out Compiling the engine. Create a custom build of the Flutter engine that removes uses of sharedApplication and corrects the path for the bundle. Check out an example from the community on GitHub. Open the Flutter app project settings in Xcode to share build configurations.
https://docs.flutter.dev/development/platform-integration/ios/app-extensions/index.html
33cc08dd96bb-5
Open the Flutter app project settings in Xcode to share build configurations. Navigate to the Info tab. Expand the Configurations group. Expand the Debug, Profile, and Release entries. For each of these configurations, make sure the value in the Based on configuration file drop-down menu for your extension matches the one selected for the normal app target. (Optional) Replace any storyboard files with an extension class if needed. In the Info.plist file, delete the NSExtensionMainStoryboard property. Add the NSExtensionPrincipalClass property. Set this value for this property to the name of your ViewController. For example, in an iMessage extension you would use MessageViewController. Embed the FlutterViewController as described in Adding a Flutter Screen. For example, you can display a specific route in your Flutter app within an iMessage extension.
https://docs.flutter.dev/development/platform-integration/ios/app-extensions/index.html
33cc08dd96bb-6
//This attribute tells the compiler that this piece of Swift code can be accessed from Objective-C. @objc(MessagesViewController) class MessagesViewController: MSMessagesAppViewController { override func viewDidLoad() { super.viewDidLoad() showFlutter() } @objc func showFlutter() { // Create a FlutterViewController with an implicit FlutterEngine let flutterViewController = FlutterViewController(project: nil, initialRoute: "/ext", nibName: nil, bundle: nil) present(flutterViewController, animated: true, completion: nil) } Important: Commenting out sharedApplication disables many features in the Flutter framework. This hasn’t been tested in App Store submissions and might not work for some app extensions. For example, home screen Widgets and Live Activities can’t use some lower-level APIs needed to draw Flutter UI.
https://docs.flutter.dev/development/platform-integration/ios/app-extensions/index.html
e4531768dcc1-0
Leveraging Apple's System APIs and Frameworks Platform integration iOS Leveraging Apple's System APIs and Frameworks Introducing Flutter plugins Adding a plugin to your project Flutter Plugins and Apple Frameworks When you come from iOS development, you might need to find Flutter plugins that offer the same abilities as Apple’s system libraries. This might include accessing device hardware or interacting with specific frameworks like HealthKit or MapKit. For an overview of how the SwiftUI framework compares to Flutter, see Flutter for SwiftUI developers. Introducing Flutter plugins Dart calls libraries that contain platform-specific code plugins. When developing an app with Flutter, you use plugins to interact with system libraries.
https://docs.flutter.dev/development/platform-integration/ios/apple-frameworks/index.html
e4531768dcc1-1
In your Dart code, you use the plugin’s Dart API to call the native code from the system library being used. This means that you can write the code to call the Dart API. The API then makes it work for all platforms that the plugin supports. To learn more about plugins, see Using packages. Though this page links to some popular plugins, you can find thousands more, along with examples, on pub.dev. The following table does not endorse any particular plugin. If you can’t find a package that meets your need, you can create your own or use platform channels directly in your project. To learn more, see Writing platform-specific code. Adding a plugin to your project To use an Apple framework within your native project, import it into your Swift or Objective-C file.
https://docs.flutter.dev/development/platform-integration/ios/apple-frameworks/index.html
e4531768dcc1-2
To add a Flutter plugin, run flutter pub add package_name from the root of your project. This adds the dependency to your pubspec.yaml file. After you add the dependency, add an import statement for the package in your Dart file. You might need to change app settings or initialization logic. If that’s needed, the package’s “Readme” page on pub.dev should provide details. Flutter Plugins and Apple Frameworks Access the photo library PhotoKitusing the Photos and PhotosUI frameworks UIImagePickerController image_picker Access the camera UIImagePickerControllerusing the .camera sourceType image_picker Use advanced camera features AVFoundation camera Offer In-app purchases StoreKit in_app_purchase1 Process payments
https://docs.flutter.dev/development/platform-integration/ios/apple-frameworks/index.html
e4531768dcc1-3
in_app_purchase1 Process payments PassKit pay2 Send push notifications UserNotifications firebase_messaging3 Access GPS coordinates CoreLocation geolocator Access sensor data4 CoreMotion sensors_plus Embed maps MapKit google_maps_flutter Make network requests URLSession http Store key-values @AppStorage property wrapper NSUserDefaults shared_preferences Persist to a database CoreData or SQLite sqflite Access health data HealthKit health Use machine learning CoreML
https://docs.flutter.dev/development/platform-integration/ios/apple-frameworks/index.html
e4531768dcc1-4
health Use machine learning CoreML google_ml_kit5 Recognize text VisionKit google_ml_kit5 Recognize speech Speech speech_to_text Use augmented reality ARKit ar_flutter_plugin Access weather data WeatherKit weather6 Access and manage contacts Contacts contacts_service Expose quick actions on the home screen UIApplicationShortcutItem quick_actions Index items in Spotlight search CoreSpotlight flutter_core_spotlight Configure, update and communicate with Widgets WidgetKit home_widget
https://docs.flutter.dev/development/platform-integration/ios/apple-frameworks/index.html
e4531768dcc1-5
WidgetKit home_widget Supports both Google Play Store on Android and Apple App Store on iOS. ↩ Adds Google Pay payments on Android and Apple Pay payments on iOS. ↩ Uses Firebase Cloud Messaging and integrates with APNs. ↩ Includes sensors like accelerometer, gyroscope, etc. ↩ Uses Google’s ML Kit and supports various features like text recognition, face detection, image labeling, landmark recognition, and barcode scanning. You can also create a custom model with Firebase. To learn more, see Use a custom TensorFlow Lite model with Flutter. ↩ ↩2 Uses the OpenWeatherMap API. Other packages exist that can pull from different weather APIs. ↩
https://docs.flutter.dev/development/platform-integration/ios/apple-frameworks/index.html
93112a7869ac-0
Binding to native iOS code using dart:ffi Platform integration iOS Binding to native iOS code using dart:ffi Dynamic vs static linking Step 1: Create a plugin Step 2: Add C/C++ sources Step 3: Load the code using the FFI library Other use cases iOS and macOS Platform library First-party library Source code Compiled (dynamic) library Open-source third-party library Closed-source third-party library Stripping iOS symbols Flutter mobile and desktop apps can use the dart:ffi library to call native C APIs. FFI stands for foreign function interface. Other terms for similar functionality include native interface and language bindings.
https://docs.flutter.dev/development/platform-integration/ios/c-interop/index.html
93112a7869ac-1
Note: This page describes using the dart:ffi library in iOS apps. For information on Android, see Binding to native Android code using dart:ffi. For information in macOS, see Binding to native macOS code using dart:ffi. This feature is not yet supported for web plugins. Before your library or program can use the FFI library to bind to native code, you must ensure that the native code is loaded and its symbols are visible to Dart. This page focuses on compiling, packaging, and loading iOS native code within a Flutter plugin or app. This tutorial demonstrates how to bundle C/C++ sources in a Flutter plugin and bind to them using the Dart FFI library on iOS. In this walkthrough, you’ll create a C function that implements 32-bit addition and then exposes it through a Dart plugin named “native_add”. Dynamic vs static linking
https://docs.flutter.dev/development/platform-integration/ios/c-interop/index.html
93112a7869ac-2
Dynamic vs static linking A native library can be linked into an app either dynamically or statically. A statically linked library is embedded into the app’s executable image, and is loaded when the app starts. Symbols from a statically linked library can be loaded using DynamicLibrary.executable or DynamicLibrary.process. A dynamically linked library, by contrast, is distributed in a separate file or folder within the app, and loaded on-demand. On iOS, the dynamically linked library is distributed as a .framework folder. A dynamically linked library can be loaded into Dart using DynamicLibrary.open. API documentation is available from the Dart dev channel: Dart API reference documentation. Step 1: Create a plugin If you already have a plugin, skip this step. To create a plugin called “native_add”, do the following: flutter create -platforms =android,ios
https://docs.flutter.dev/development/platform-integration/ios/c-interop/index.html
93112a7869ac-3
flutter create -platforms =android,ios -template =plugin native_add cd native_add Note: You can exclude platforms from --platforms that you don’t want to build to. However, you need to include the platform of the device you are testing on. Step 2: Add C/C++ sources You need to inform the iOS build system about the native code so the code can be compiled and linked appropriately into the final application. Add the sources to the ios folder, because CocoaPods doesn’t allow including sources above the podspec file. The FFI library can only bind against C symbols, so in C++ these symbols must be marked extern C. You should also add attributes to indicate that the symbols are referenced from Dart, to prevent the linker from discarding the symbols during link-time optimization.
https://docs.flutter.dev/development/platform-integration/ios/c-interop/index.html
93112a7869ac-4
For example, to create a C++ file named ios/Classes/native_add.cpp, use the following instructions. (Note that the template has already created this file for you.) Start from the root directory of your project: cat > ios/Classes/native_add.cpp << EOF #include <stdint.h> extern "C" __attribute__((visibility("default"))) __attribute__((used)) int32_t native_add(int32_t x, int32_t y) { return x + y; } EOF On iOS, you need to tell Xcode to statically link the file: In Xcode, open Runner.xcworkspace. Add the C/C++/Objective-C/Swift source files to the Xcode project. Step 3: Load the code using the FFI library
https://docs.flutter.dev/development/platform-integration/ios/c-interop/index.html
93112a7869ac-5
Step 3: Load the code using the FFI library In this example, you can add the following code to lib/native_add.dart. However the location of the Dart binding code isn’t important. First, you must create a DynamicLibrary handle to the native code. The following example shows how to create a handle for an iOS app OR an Android app: Note that on Android the native library is named in CMakeLists.txt, but on iOS it takes the plugin’s name. With a handle to the enclosing library, you can resolve the native_add symbol: Finally, you can call it. To demonstrate this within the auto-generated “example” app (example/lib/main.dart): Other use cases iOS and macOS
https://docs.flutter.dev/development/platform-integration/ios/c-interop/index.html
93112a7869ac-6
Other use cases iOS and macOS Dynamically linked libraries are automatically loaded by the dynamic linker when the app starts. Their constituent symbols can be resolved using DynamicLibrary.process. You can also get a handle to the library with DynamicLibrary.open to restrict the scope of symbol resolution, but it’s unclear how Apple’s review process handles this. Symbols statically linked into the application binary can be resolved using DynamicLibrary.executable or DynamicLibrary.process. Platform library To link against a platform library, use the following instructions: In Xcode, open Runner.xcworkspace. Select the target platform. Click + in the Linked Frameworks and Libraries section. Select the system library to link against. First-party library
https://docs.flutter.dev/development/platform-integration/ios/c-interop/index.html
93112a7869ac-7
Select the system library to link against. First-party library A first-party native library can be included either as source or as a (signed) .framework file. It’s probably possible to include statically linked archives as well, but it requires testing. Source code To link directly to source code, use the following instructions: In Xcode, open Runner.xcworkspace. Add the C/C++/Objective-C/Swift source files to the Xcode project. Add the following prefix to the exported symbol declarations to ensure they are visible to Dart: C/C++/Objective-C extern "C" /* <= C++ only */ __attribute__((visibility("default"))) __attribute__((used)) Swift @_cdecl("myFunctionName") Compiled (dynamic) library
https://docs.flutter.dev/development/platform-integration/ios/c-interop/index.html
93112a7869ac-8
Compiled (dynamic) library To link to a compiled dynamic library, use the following instructions: If a properly signed Framework file is present, open Runner.xcworkspace. Add the framework file to the Embedded Binaries section. Also add it to the Linked Frameworks & Libraries section of the target in Xcode. Open-source third-party library To create a Flutter plugin that includes both C/C++/Objective-C and Dart code, use the following instructions: In your plugin project, open ios/<myproject>.podspec. Add the native code to the source_files field. The native code is then statically linked into the application binary of any app that uses this plugin. Closed-source third-party library
https://docs.flutter.dev/development/platform-integration/ios/c-interop/index.html
93112a7869ac-9
Closed-source third-party library To create a Flutter plugin that includes Dart source code, but distribute the C/C++ library in binary form, use the following instructions: In your plugin project, open ios/<myproject>.podspec. Add a vendored_frameworks field. See the CocoaPods example. Warning: Do not upload this plugin (or any plugin containing binary code) to pub.dev. Instead, this plugin should be downloaded from a trusted third-party, as shown in the CocoaPods example. Stripping iOS symbols When creating a release archive (IPA), the symbols are stripped by Xcode. In Xcode, go to Target Runner > Build Settings > Strip Style. Change from All Symbols to Non-Global Symbols.
https://docs.flutter.dev/development/platform-integration/ios/c-interop/index.html
f101dae66193-0
iOS Platform integration iOS Topics: Leveraging Apple’s system libraries Adding a splash screen Adding iOS App Clip support Adding iOS app extensions C interop Hosting native iOS views iOS debugging
https://docs.flutter.dev/development/platform-integration/ios/index.html
65be8373a65e-0
Adding an iOS App Clip target Platform integration iOS Adding an iOS App Clip target Step 1 - Open project Step 2 - Add an App Clip target Step 3 - Remove unneeded files Step 4 - Share build configurations Step 5 - Share code and assets Option 1 - Share everything Option 2 - Customize Flutter launch for App Clip Step 6 - Add App Clip associated domains Step 7 - Integrate Flutter Step 8 - Integrate plugins Run Debugging, hot reload Important: This experimental preview currently exceeds the 10MB uncompressed IPA payload size limit and cannot be used in production (#71098).
https://docs.flutter.dev/development/platform-integration/ios/ios-app-clip/index.html
65be8373a65e-1
This guide describes how to manually add another Flutter-rendering iOS App Clip target to your existing Flutter project or add-to-app project. Warning: This is an advanced guide and is best intended for audience with a working knowledge of iOS development. To see a working sample, see the App Clip sample on GitHub. Step 1 - Open project Open your iOS Xcode project, such as ios/Runner.xcworkspace for full-Flutter apps. Step 2 - Add an App Clip target 2.1 Click on your project in the Project Navigator to show the project settings. Press + at the bottom of the target list to add a new target. 2.2 Select the App Clip type for your new target. 2.3 Enter your new target detail in the dialog. Select Storyboard for Interface.
https://docs.flutter.dev/development/platform-integration/ios/ios-app-clip/index.html
65be8373a65e-2
Select Storyboard for Interface. Select UIKit App Delegate for Life Cycle. Select the same language as your original target for Language. (In other words, to simplify the setup, don’t create a Swift App Clip target for an Objective-C main target, and vice versa.) 2.4 In the following dialog, activate the new scheme for the new target. Step 3 - Remove unneeded files 3.1 In the Project Navigator, in the newly created App Clip group, delete everything except Info.plist and <app clip target>.entitlements. Tip: For add-to-app users, it’s up to the reader to decide how much of this template to keep to invoke FlutterViewController or FlutterEngine APIs from this code later. Move files to trash. 3.2
https://docs.flutter.dev/development/platform-integration/ios/ios-app-clip/index.html
65be8373a65e-3
Move files to trash. 3.2 If you don’t use the SceneDelegate.swift file, remove the reference to it in the Info.plist. Open the Info.plist file in the App Clip group. Delete the entire dictionary entry for Application Scene Manifest. Step 4 - Share build configurations This step isn’t necessary for add-to-app projects since add-to-app projects have their custom build configurations and versions. 4.1 Back in the project settings, select the project entry now rather than any targets. In the Info tab, under the Configurations expandable group, expand the Debug, Profile, and Release entries. For each, select the same value from the drop-down menu for the App Clip target as the entry selected for the normal app target.
https://docs.flutter.dev/development/platform-integration/ios/ios-app-clip/index.html
65be8373a65e-4
This gives your App Clip target access to Flutter’s required build settings. 4.2 In the App Clip group’s Info.plist file, set: Build version string (short) to $(FLUTTER_BUILD_NAME) Bundle version to $(FLUTTER_BUILD_NUMBER) Step 5 - Share code and assets Option 1 - Share everything Assuming the intent is to show the same Flutter UI in the standard app as in the App Clip, share the same code and assets. Option 2 - Customize Flutter launch for App Clip In this case, do not delete everything listed in Step 3. Instead, use the scaffolding and the iOS add-to-app APIs to perform a custom launch of Flutter. For example to show a custom Flutter route. Step 6 - Add App Clip associated domains
https://docs.flutter.dev/development/platform-integration/ios/ios-app-clip/index.html
65be8373a65e-5
Step 6 - Add App Clip associated domains This is a standard step for App Clip development. See the official Apple documentation. 6.1 Open the <app clip target>.entitlements file. Add an Associated Domains Array type. Add a row to the array with appclips:<your bundle id>. 6.2 The same associated domains entitlement needs to be added to your main app, as well. Copy the <app clip target>.entitlements file from your App Clip group to your main app group and rename it to the same name as your main target such as Runner.entitlements. Open the file and delete the Parent Application Identifiers entry for the main app’s entitlement file (leave that entry for the App Clip’s entitlement file). 6.3
https://docs.flutter.dev/development/platform-integration/ios/ios-app-clip/index.html
65be8373a65e-6
6.3 Back in the project settings, select the main app’s target, open the Build Settings tab. Set the Code Signing Entitlements setting to the relative path of the second entitlements file created for the main app. Step 7 - Integrate Flutter These steps are not necessary for add-to-app. 7.1 In your App Clip’s target’s project settings, open the Build Settings tab. For setting Framework Search Paths, add 2 entries: $(inherited) $(PROJECT_DIR)/Flutter In other words, the same as the main app target’s build settings. 7.2 For the Swift target, set the Objective-C Bridging Header build setting to Runner/Runner-Bridging-Header.h
https://docs.flutter.dev/development/platform-integration/ios/ios-app-clip/index.html
65be8373a65e-7
In other words, the same as the main app target’s build settings. 7.3 Now open the Build Phases tab. Press the + sign and select New Run Script Phase. Drag that new phase to below the Dependencies phase. Expand the new phase and add this line to the script content: $FLUTTER_ROOT /packages/flutter_tools/bin/xcode_backend.sh" build In other words, the same as the main app target’s build phases. This ensures that your Flutter Dart code is compiled when running the App Clip target. 7.4 Press the + sign and select New Run Script Phase again. Leave it as the last phase. This time, add: $FLUTTER_ROOT
https://docs.flutter.dev/development/platform-integration/ios/ios-app-clip/index.html
65be8373a65e-8
This time, add: $FLUTTER_ROOT /packages/flutter_tools/bin/xcode_backend.sh" embed_and_thin In other words, the same as the main app target’s build phases. This ensures that your Flutter app and engine are embedded into the App Clip bundle. Step 8 - Integrate plugins Warning: CocoaPods version 1.10.0.beta.1 or higher is required to run Flutter apps with plugins. 8.1 Open the Podfile for your Flutter project or add-to-app host project. For full-Flutter apps, replace the following section: target 'Runner' do use_frameworks! use_modular_headers! flutter_install_all_ios_pods
https://docs.flutter.dev/development/platform-integration/ios/ios-app-clip/index.html
65be8373a65e-9
flutter_install_all_ios_pods File dirname File realpath __FILE__ )) end with: use_frameworks! use_modular_headers! flutter_install_all_ios_pods File dirname File realpath __FILE__ )) target 'Runner' target '<name of your App Clip target>' At the top of the file, also uncomment platform :ios, '11.0' and set the version to the lowest of the two target’s iOS Deployment Target. For add-to-app, add to: target
https://docs.flutter.dev/development/platform-integration/ios/ios-app-clip/index.html
65be8373a65e-10
For add-to-app, add to: target 'MyApp' do install_all_flutter_pods flutter_application_path end with: target 'MyApp' do install_all_flutter_pods flutter_application_path end target '<name of your App Clip target>' install_all_flutter_pods flutter_application_path end 8.2 From the command line, enter your Flutter project directory and then install the pod: cd ios pod install Run
https://docs.flutter.dev/development/platform-integration/ios/ios-app-clip/index.html
65be8373a65e-11
cd ios pod install Run You can now run your App Clip target from Xcode by selecting your App Clip target from the scheme drop-down, selecting an iOS 14 device and pressing run. To test launching an App Clip from the beginning, also consult Apple’s doc on Testing Your App Clip’s Launch Experience. Debugging, hot reload Unfortunately flutter attach cannot auto-discover the Flutter session in an App Clip due to networking permission restrictions. In order to debug your App Clip and use functionalities like hot reload, you must look for the Observatory URI from the console output in Xcode after running. [PENDING: Is this still true?] You must then copy paste it back into the flutter attach command to connect. For example: flutter attach --debug-uri <copied URI>
https://docs.flutter.dev/development/platform-integration/ios/ios-app-clip/index.html
f3be2054f0ca-0
iOS debugging Platform integration iOS iOS debugging Due to security around local network permissions in iOS 14 or later, you must accept a permission dialog box to enable Flutter debugging functionalities such as hot-reload and DevTools. This affects debug and profile builds only and won’t appear in release builds. You can also allow this permission by enabling Settings > Privacy > Local Network > Your App.
https://docs.flutter.dev/development/platform-integration/ios/ios-debugging/index.html
fe444cf9bb3b-0
Hosting native iOS views in your Flutter app with Platform Views Platform integration iOS iOS platform-views On the Dart side On the platform side Putting it together Performance Platform views allow you to embed native views in a Flutter app, so you can apply transforms, clips, and opacity to the native view from Dart. This allows you, for example, to use the native Google Maps from the Android and iOS SDKs directly inside your Flutter app. Note: This page discusses how to host your own native views within a Flutter app. If you’d like to embed native Android views in your Flutter app, see Hosting native Android views. iOS only uses Hybrid composition, which means that the native UIView is appended to the view hierarchy.
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-1
To create a platform view on iOS, use the following instructions: On the Dart side On the Dart side, create a Widget and add the following build implementation, as shown in the following steps. In your Dart file, for example do the following in native_view_example.dart: Add the following imports: import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; Implement a build() method: Widget build(BuildContext context) { // This is used in the platform side to register the view. const String viewType = '<platform-view-type>'; // Pass parameters to the platform side. final Map<String, dynamic> creationParams = <String, dynamic>{};
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-2
return UiKitView( viewType: viewType, layoutDirection: TextDirection.ltr, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), ); } For more information, see the API docs for: UIKitView. On the platform side On the platform side, you use the either Swift or Objective-C: Swift Objective-C Implement the factory and the platform view. The FLNativeViewFactory creates the platform view, and the platform view provides a reference to the UIView. For example, FLNativeView.swift: import Flutter import UIKit class FLNativeViewFactory NSObject FlutterPlatformViewFactory private var messenger
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-3
private var messenger FlutterBinaryMessenger init messenger FlutterBinaryMessenger self messenger messenger super init () func create withFrame frame CGRect viewIdentifier viewId Int64 arguments args Any > FlutterPlatformView return FLNativeView frame frame viewIdentifier viewId arguments args binaryMessenger messenger class
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-4
binaryMessenger messenger class FLNativeView NSObject FlutterPlatformView private var _view UIView init frame CGRect viewIdentifier viewId Int64 arguments args Any ?, binaryMessenger messenger FlutterBinaryMessenger _view UIView () super init () // iOS views can be created here createNativeView view _view func view ()
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-5
func view () > UIView return _view func createNativeView view _view UIView ){ _view backgroundColor UIColor blue let nativeLabel UILabel () nativeLabel text "Native text from iOS" nativeLabel textColor UIColor white nativeLabel textAlignment center nativeLabel frame CGRect width 180 height
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-6
width 180 height 48.0 _view addSubview nativeLabel Finally, register the platform view. This can be done in an app or a plugin. For app registration, modify the App’s AppDelegate.swift: import Flutter import UIKit @UIApplicationMain @objc class AppDelegate FlutterAppDelegate override func application application UIApplication didFinishLaunchingWithOptions launchOptions UIApplication LaunchOptionsKey Any ]? > Bool
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-7
]? > Bool GeneratedPluginRegistrant register with self weak var registrar self registrar forPlugin "plugin-name" let factory FLNativeViewFactory messenger registrar !. messenger ()) self registrar forPlugin "<plugin-name>" !. register factory withId "<platform-view-type>" return super application application
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-8
return super application application didFinishLaunchingWithOptions launchOptions For plugin registration, modify the plugin’s main file (for example, FLPlugin.swift): import Flutter import UIKit class FLPlugin NSObject FlutterPlugin public static func register with registrar FlutterPluginRegistrar let factory FLNativeViewFactory messenger registrar messenger registrar register factory withId
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-9
register factory withId "<platform-view-type>" Add the headers for the factory and the platform view. For example, FLNativeView.h: #import <Flutter/Flutter.h> @interface FLNativeViewFactory NSObject FlutterPlatformViewFactory instancetype initWithMessenger :( NSObject FlutterBinaryMessenger >* messenger @end @interface FLNativeView NSObject FlutterPlatformView instancetype initWithFrame :( CGRect frame viewIdentifier :(
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-10
frame viewIdentifier :( int64_t viewId arguments :( id _Nullable args binaryMessenger :( NSObject FlutterBinaryMessenger >* messenger UIView view @end Implement the factory and the platform view. The FLNativeViewFactory creates the platform view, and the platform view provides a reference to the UIView. For example, FLNativeView.m: #import "FLNativeView.h" @implementation FLNativeViewFactory NSObject FlutterBinaryMessenger >* _messenger
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-11
>* _messenger instancetype initWithMessenger :( NSObject FlutterBinaryMessenger >* messenger self super init ]; if self _messenger messenger return self NSObject FlutterPlatformView >* createWithFrame :( CGRect frame viewIdentifier :( int64_t viewId arguments :( id _Nullable args return
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-12
_Nullable args return [[ FLNativeView alloc initWithFrame frame viewIdentifier: viewId arguments: args binaryMessenger: _messenger ]; @end @implementation FLNativeView UIView _view instancetype initWithFrame :( CGRect frame viewIdentifier :( int64_t viewId arguments :( id _Nullable args binaryMessenger :(
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-13
args binaryMessenger :( NSObject FlutterBinaryMessenger >* messenger if self super init ]) _view [[ UIView alloc init ]; return self UIView view return _view @end Finally, register the platform view. This can be done in an app or a plugin. For app registration, modify the App’s AppDelegate.m: #import "AppDelegate.h" #import "FLNativeView.h" #import "GeneratedPluginRegistrant.h" @implementation
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-14
@implementation AppDelegate BOOL application :( UIApplication application didFinishLaunchingWithOptions :( NSDictionary launchOptions GeneratedPluginRegistrant registerWithRegistry self ]; NSObject FlutterPluginRegistrar >* registrar self registrarForPlugin @"plugin-name" ]; FLNativeViewFactory factory [[ FLNativeViewFactory alloc initWithMessenger registrar messenger ]; [[ self
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-15
]; [[ self registrarForPlugin @"<plugin-name>" registerViewFactory factory withId: @"<platform-view-type>" ]; return super application application didFinishLaunchingWithOptions launchOptions ]; @end For plugin registration, modify the main plugin file (for example, FLPlugin.m): #import <Flutter/Flutter.h> #import "FLNativeView.h" @interface FLPlugin NSObject FlutterPlugin @end @implementation FLPlugin void
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-16
@implementation FLPlugin void registerWithRegistrar :( NSObject FlutterPluginRegistrar >* registrar FLNativeViewFactory factory [[ FLNativeViewFactory alloc initWithMessenger registrar messenger ]; registrar registerViewFactory factory withId @"<platform-view-type>" ]; @end For more information, see the API docs for: FlutterPlatformViewFactory FlutterPlatformView PlatformView Putting it together
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-17
PlatformView Putting it together When implementing the build() method in Dart, you can use defaultTargetPlatform to detect the platform, and decide what widget to use: Performance Platform views in Flutter come with performance trade-offs. For example, in a typical Flutter app, the Flutter UI is composed on a dedicated raster thread. This allows Flutter apps to be fast, as the main platform thread is rarely blocked. While a platform view is rendered with hybrid composition, the Flutter UI is composed from the platform thread, which competes with other tasks like handling OS or plugin messages. Prior to Android 10, hybrid composition copied each Flutter frame out of the graphic memory into main memory, and then copied it back to a GPU texture. As this copy happens per frame, the performance of the entire Flutter UI might be impacted. In Android 10 or above, the graphics memory is copied only once.
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
fe444cf9bb3b-18
Virtual display, on the other hand, makes each pixel of the native view flow through additional intermediate graphic buffers, which cost graphic memory and drawing performance. For complex cases, there are some techniques that can be used to mitigate these issues. For example, you could use a placeholder texture while an animation is happening in Dart. In other words, if an animation is slow while a platform view is rendered, then consider taking a screenshot of the native view and rendering it as a texture. For more information, see: TextureLayer TextureRegistry FlutterTextureRegistry FlutterImageView
https://docs.flutter.dev/development/platform-integration/ios/platform-views/index.html
0b3eb25415ca-0
Adding a splash screen to your iOS app Platform integration iOS Splash screen Splash screens (also known as launch screens) provide a simple initial experience while your iOS app loads. They set the stage for your application, while allowing time for the app engine to load and your app to initialize. All apps submitted to the Apple App Store must provide a launch screen with an Xcode storyboard. Customize the launch screen The default Flutter template includes an Xcode storyboard named LaunchScreen.storyboard that can be customized your own assets. By default, the storyboard displays a blank image, but you can change this. To do so, open the Flutter app’s Xcode project by typing open ios/Runner.xcworkspace from the root of your app directory. Then select Runner/Assets.xcassets from the Project Navigator and drop in the desired images to the LaunchImage image set.
https://docs.flutter.dev/development/platform-integration/ios/splash-screen/index.html
0b3eb25415ca-1
Apple provides detailed guidance for launch screens as part of the Human Interface Guidelines.
https://docs.flutter.dev/development/platform-integration/ios/splash-screen/index.html
fd713daad317-0
Building Linux apps with Flutter Platform integration Linux Linux development Integrating with Linux Preparing Linux apps for distribution This page discusses considerations unique to building Linux apps with Flutter, including shell integration and preparation of apps for distribution. Integrating with Linux The Linux programming interface, comprising library functions and system calls, is designed around the C language and ABI. Fortunately, Dart provides dart:ffi, which is designed to enable Dart programs to efficiently call into C libraries. FFI provides Flutter apps with the ability to allocate native memory with malloc or calloc, support for pointers, structs and callbacks, and ABI types like long and size_t. For more information about calling C libraries from Flutter, see C interop using dart:ffi.
https://docs.flutter.dev/development/platform-integration/linux/building/index.html
fd713daad317-1
Many apps will benefit from using a package that wraps the underlying library calls in a more convenient, idiomatic Dart API. Canonical has built a series of packages with a focus on enabling Dart and Flutter on Linux, including support for desktop notifications, dbus, network management, and Bluetooth. More generally, many other packages support Linux, including common packages such as url_launcher, shared_preferences, file_selector, and path_provider. Preparing Linux apps for distribution The executable binary can be found in your project under build/linux/<build mode>/bundle/. Alongside your executable binary in the bundle directory there are two directories: lib contains the required .so library files data contains the application’s data assets, such as fonts or images
https://docs.flutter.dev/development/platform-integration/linux/building/index.html
fd713daad317-2
data contains the application’s data assets, such as fonts or images In addition to these files, your application also relies on various operating system libraries that it’s been compiled against. You can see the full list by running ldd against your application. For example, assuming you have a Flutter desktop application called linux_desktop_test, you could inspect the system libraries it depends upon as follows: flutter build linux -release ldd build/linux/release/bundle/linux_desktop_test To wrap up this application for distribution you need to include everything in the bundle directory, and make sure the Linux system you are installing it on has all of the system libraries required. This may be as simple as: sudo apt-get install libgtk-3-0 libblkid1 liblzma5
https://docs.flutter.dev/development/platform-integration/linux/building/index.html
fd713daad317-3
install libgtk-3-0 libblkid1 liblzma5 For information on publishing a Linux application to the Snap Store, see Build and release a Linux application to the Snap Store.
https://docs.flutter.dev/development/platform-integration/linux/building/index.html
7bb9f5c56e33-0
Linux Platform integration Linux Topics: Building Linux apps
https://docs.flutter.dev/development/platform-integration/linux/index.html
f68346b87a9e-0
Building macOS apps with Flutter Platform integration macOS macOS development Integrating with macOS look and feel Building macOS apps Entitlements and the App Sandbox Setting up entitlements Hardened Runtime This page discusses considerations unique to building macOS apps with Flutter, including shell integration and distribution of macOS apps through the Apple Store. Integrating with macOS look and feel While you can use any visual style or theme you choose to build a macOS app, you might want to adapt your app to more fully align with the macOS look and feel. Flutter includes the Cupertino widget set, which provides a set of widgets for the current iOS design language. Many of these widgets, including sliders, switches and segmented controls, are also appropriate for use on macOS.
https://docs.flutter.dev/development/platform-integration/macos/building/index.html
f68346b87a9e-1
Alternatively, you might find the macos_ui package a good fit for your needs. This package provides widgets and themes that implement the macOS design language, including a MacosWindow frame and scaffold, toolbars, pulldown and pop-up buttons, and modal dialogs. Building macOS apps To distribute your macOS application, you can either distribute it through the macOS App Store, or you can distribute the .app itself, perhaps from your own website. As of macOS 10.14.5, you need to notarize your macOS application before distributing it outside of the macOS App Store. The first step in both of the above processes involves working with your application inside of Xcode. To be able to compile your application from inside of Xcode you first need to build the application for release using the flutter build command, then open the Flutter macOS Runner application.
https://docs.flutter.dev/development/platform-integration/macos/building/index.html
f68346b87a9e-2
Once inside of Xcode, follow either Apple’s documentation on notarizing macOS Applications, or on distributing an application through the App Store. You should also read through the macOS-specific support section below to understand how entitlements, the App Sandbox, and the Hardened Runtime impact your distributable application. Build and release a macOS app provides a more detailed step-by-step walkthrough of releasing a Flutter app to the App Store. Entitlements and the App Sandbox macOS builds are configured by default to be signed, and sandboxed with App Sandbox. This means that if you want to confer specific capabilities or services on your macOS app, such as the following: Accessing the internet Capturing movies and images from the built-in camera Accessing files Then you must set up specific entitlements in Xcode. The following section tells you how to do this.
https://docs.flutter.dev/development/platform-integration/macos/building/index.html
f68346b87a9e-3
Setting up entitlements Managing sandbox settings is done in the macos/Runner/*.entitlements files. When editing these files, you shouldn’t remove the original Runner-DebugProfile.entitlements exceptions (that support incoming network connections and JIT), as they’re necessary for the debug and profile modes to function correctly. If you’re used to managing entitlement files through the Xcode capabilities UI, be aware that the capabilities editor updates only one of the two files or, in some cases, it creates a whole new entitlements file and switches the project to use it for all configurations. Either scenario causes issues. We recommend that you edit the files directly. Unless you have a very specific reason, you should always make identical changes to both files.
https://docs.flutter.dev/development/platform-integration/macos/building/index.html
f68346b87a9e-4
If you keep the App Sandbox enabled (which is required if you plan to distribute your application in the App Store), you need to manage entitlements for your application when you add certain plugins or other native functionality. For instance, using the file_chooser plugin requires adding either the com.apple.security.files.user-selected.read-only or com.apple.security.files.user-selected.read-write entitlement. Another common entitlement is com.apple.security.network.client, which you must add if you make any network requests. Without the com.apple.security.network.client entitlement, for example, network requests fail with a message such as: flutter: SocketException: Connection failed (OS Error: Operation not permitted, errno = 1), address = example.com, port = 443 For more information on these topics, see App Sandbox and Entitlements on the Apple Developer site. Hardened Runtime
https://docs.flutter.dev/development/platform-integration/macos/building/index.html
f68346b87a9e-5
Hardened Runtime If you choose to distribute your application outside of the App Store, you need to notarize your application for compatibility with macOS 10.15+. This requires enabling the Hardened Runtime option. Once you have enabled it, you need a valid signing certificate in order to build. By default, the entitlements file allows JIT for debug builds but, as with App Sandbox, you might need to manage other entitlements. If you have both App Sandbox and Hardened Runtime enabled, you might need to add multiple entitlements for the same resource. For instance, microphone access would require both com.apple.security.device.audio-input (for Hardened Runtime) and com.apple.security.device.microphone (for App Sandbox). For more information on this topic, see Hardened Runtime on the Apple Developer site.
https://docs.flutter.dev/development/platform-integration/macos/building/index.html
5c3fda7a6c0c-0
Binding to native macOS code using dart:ffi Platform integration macOS Binding to native macOS code using dart:ffi Dynamic vs static linking Step 1: Create a plugin Step 2: Add C/C++ sources Step 3: Load the code using the FFI library Other use cases iOS and macOS Platform library First-party library Source code Compiled (dynamic) library Compiled (dynamic) library (macOS) Flutter mobile and desktop apps can use the dart:ffi library to call native C APIs. FFI stands for foreign function interface. Other terms for similar functionality include native interface and language bindings.
https://docs.flutter.dev/development/platform-integration/macos/c-interop/index.html
5c3fda7a6c0c-1
Note: This page describes using the dart:ffi library in macOS desktop apps. For information on Android, see Binding to native Android code using dart:ffi. For information on iOS, see Binding to native iOS code using dart:ffi. This feature is not yet supported for web plugins. Before your library or program can use the FFI library to bind to native code, you must ensure that the native code is loaded and its symbols are visible to Dart. This page focuses on compiling, packaging, and loading macOS native code within a Flutter plugin or app. This tutorial demonstrates how to bundle C/C++ sources in a Flutter plugin and bind to them using the Dart FFI library on macOS. In this walkthrough, you’ll create a C function that implements 32-bit addition and then exposes it through a Dart plugin named “native_add”. Dynamic vs static linking
https://docs.flutter.dev/development/platform-integration/macos/c-interop/index.html
5c3fda7a6c0c-2
Dynamic vs static linking A native library can be linked into an app either dynamically or statically. A statically linked library is embedded into the app’s executable image, and is loaded when the app starts. Symbols from a statically linked library can be loaded using DynamicLibrary.executable or DynamicLibrary.process. A dynamically linked library, by contrast, is distributed in a separate file or folder within the app, and loaded on-demand. On macOS, the dynamically linked library is distributed as a .framework folder. A dynamically linked library can be loaded into Dart using DynamicLibrary.open. API documentation is available from the Dart dev channel: Dart API reference documentation. Step 1: Create a plugin If you already have a plugin, skip this step. To create a plugin called “native_add”, do the following: flutter create -platforms =macos
https://docs.flutter.dev/development/platform-integration/macos/c-interop/index.html
5c3fda7a6c0c-3
flutter create -platforms =macos -template =plugin native_add cd native_add Note: You can exclude platforms from --platforms that you don’t want to build to. However, you need to include the platform of the device you are testing on. Step 2: Add C/C++ sources You need to inform the macOS build system about the native code so the code can be compiled and linked appropriately into the final application. Add the sources to the macos folder, because CocoaPods doesn’t allow including sources above the podspec file. The FFI library can only bind against C symbols, so in C++ these symbols must be marked extern C. You should also add attributes to indicate that the symbols are referenced from Dart, to prevent the linker from discarding the symbols during link-time optimization.
https://docs.flutter.dev/development/platform-integration/macos/c-interop/index.html
5c3fda7a6c0c-4
For example, to create a C++ file named macos/Classes/native_add.cpp, use the following instructions. (Note that the template has already created this file for you.) Start from the root directory of your project: cat > macos/Classes/native_add.cpp << EOF #include <stdint.h> extern "C" __attribute__((visibility("default"))) __attribute__((used)) int32_t native_add(int32_t x, int32_t y) { return x + y; } EOF On macOS, you need to tell Xcode to statically link the file: In Xcode, open Runner.xcworkspace. Add the C/C++/Objective-C/Swift source files to the Xcode project. Step 3: Load the code using the FFI library
https://docs.flutter.dev/development/platform-integration/macos/c-interop/index.html
5c3fda7a6c0c-5
Step 3: Load the code using the FFI library In this example, you can add the following code to lib/native_add.dart. However the location of the Dart binding code isn’t important. First, you must create a DynamicLibrary handle to the native code. import 'dart:ffi' // For FFI final DynamicLibrary nativeAddLib DynamicLibrary process (); With a handle to the enclosing library, you can resolve the native_add symbol: Finally, you can call it. To demonstrate this within the auto-generated “example” app (example/lib/main.dart): Other use cases iOS and macOS
https://docs.flutter.dev/development/platform-integration/macos/c-interop/index.html
5c3fda7a6c0c-6
Other use cases iOS and macOS Dynamically linked libraries are automatically loaded by the dynamic linker when the app starts. Their constituent symbols can be resolved using DynamicLibrary.process. You can also get a handle to the library with DynamicLibrary.open to restrict the scope of symbol resolution, but it’s unclear how Apple’s review process handles this. Symbols statically linked into the application binary can be resolved using DynamicLibrary.executable or DynamicLibrary.process. Platform library To link against a platform library, use the following instructions: In Xcode, open Runner.xcworkspace. Select the target platform. Click + in the Linked Frameworks and Libraries section. Select the system library to link against. First-party library
https://docs.flutter.dev/development/platform-integration/macos/c-interop/index.html
5c3fda7a6c0c-7
Select the system library to link against. First-party library A first-party native library can be included either as source or as a (signed) .framework file. It’s probably possible to include statically linked archives as well, but it requires testing. Source code To link directly to source code, use the following instructions: In Xcode, open Runner.xcworkspace. Add the C/C++/Objective-C/Swift source files to the Xcode project. Add the following prefix to the exported symbol declarations to ensure they are visible to Dart: C/C++/Objective-C extern "C" /* <= C++ only */ __attribute__((visibility("default"))) __attribute__((used)) Swift @_cdecl("myFunctionName") Compiled (dynamic) library
https://docs.flutter.dev/development/platform-integration/macos/c-interop/index.html
5c3fda7a6c0c-8
Compiled (dynamic) library To link to a compiled dynamic library, use the following instructions: If a properly signed Framework file is present, open Runner.xcworkspace. Add the framework file to the Embedded Binaries section. Also add it to the Linked Frameworks & Libraries section of the target in Xcode. Compiled (dynamic) library (macOS) To add a closed source library to a Flutter macOS Desktop app, use the following instructions: Follow the instructions for Flutter desktop to create a Flutter desktop app.
https://docs.flutter.dev/development/platform-integration/macos/c-interop/index.html
5c3fda7a6c0c-9
Follow the instructions for Flutter desktop to create a Flutter desktop app. Open the yourapp/macos/Runner.xcworkspace in Xcode. Drag your precompiled library (libyourlibrary.dylib) into Runner/Frameworks. Click Runner and go to the Build Phases tab. Drag libyourlibrary.dylib into the Copy Bundle Resources list. Under Embed Libraries, check Code Sign on Copy. Under Link Binary With Libraries, set status to Optional. (We use dynamic linking, no need to statically link.) Click Runner and go to the General tab. Drag libyourlibrary.dylib into the Frameworks, Libraries and Embedded Content list. Select Embed & Sign. Click Runner and go to the Build Settings tab. In the Search Paths section configure the Library Search Paths to include the path where libyourlibrary.dylib is located.
https://docs.flutter.dev/development/platform-integration/macos/c-interop/index.html
5c3fda7a6c0c-10
Edit lib/main.dart. Use DynamicLibrary.open('libyourlibrary.dylib') to dynamically link to the symbols. Call your native function somewhere in a widget. Run flutter run and check that your native function gets called. Run flutter build macos to build a self-contained release version of your app.
https://docs.flutter.dev/development/platform-integration/macos/c-interop/index.html
d4645e73d297-0
macOS Platform integration macOS Topics: Building macOS apps C interop
https://docs.flutter.dev/development/platform-integration/macos/index.html
8ebcffba73da-0
Writing custom platform-specific code Platform integration Platform-specific code Architectural overview: platform channels Platform channel data types support and codecs Example: Calling platform-specific code using platform channels Step 1: Create a new app project Step 2: Create the Flutter platform client Step 3: Add an Android platform-specific implementation Step 4: Add an iOS platform-specific implementation Step 5: Add a Windows platform-specific implementation Step 6: Add a Linux platform-specific implementation Typesafe platform channels using Pigeon Pigeon example Separate platform-specific code from UI code Publish platform-specific code as a package Custom channels and codecs Channels and platform threading
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-1
Custom channels and codecs Channels and platform threading Using plugins and channels from background isolates Executing channel handlers on background threads Jumping to the UI thread in Android Jumping to the main thread in iOS This guide describes how to write custom platform-specific code. Some platform-specific functionality is available through existing packages; see using packages. Note: The information in this page is valid for most platforms, but platform-specific code for the web generally uses JS interoperability or the dart:html library instead. Flutter uses a flexible system that allows you to call platform-specific APIs in a language that works directly with those APIs: Kotlin or Java on Android Swift or Objective-C on iOS C++ on Windows Objective-C on macOS C on Linux
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-2
Objective-C on macOS C on Linux Flutter’s builtin platform-specific API support doesn’t rely on code generation, but rather on a flexible message passing style. Alternatively, you can use the Pigeon package for sending structured typesafe messages with code generation: The Flutter portion of the app sends messages to its host, the non-Dart portion of the app, over a platform channel. The host listens on the platform channel, and receives the message. It then calls into any number of platform-specific APIs—using the native programming language—and sends a response back to the client, the Flutter portion of the app.
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-3
Note: This guide addresses using the platform channel mechanism if you need to use the platform’s APIs in a non-Dart language. But you can also write platform-specific Dart code in your Flutter app by inspecting the defaultTargetPlatform property. Platform adaptations lists some platform-specific adaptations that Flutter automatically performs for you in the framework. Architectural overview: platform channels Messages are passed between the client (UI) and host (platform) using platform channels as illustrated in this diagram: Messages and responses are passed asynchronously, to ensure the user interface remains responsive. Note: Even though Flutter sends messages to and from Dart asynchronously, whenever you invoke a channel method, you must invoke that method on the platform’s main thread. See the section on threading for more information.
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-4
On the client side, MethodChannel enables sending messages that correspond to method calls. On the platform side, MethodChannel on Android (MethodChannelAndroid) and FlutterMethodChannel on iOS (MethodChanneliOS) enable receiving method calls and sending back a result. These classes allow you to develop a platform plugin with very little ‘boilerplate’ code. Note: If desired, method calls can also be sent in the reverse direction, with the platform acting as client to methods implemented in Dart. For a concrete example, check out the quick_actions plugin. Platform channel data types support and codecs The standard platform channels use a standard message codec that supports efficient binary serialization of simple JSON-like values, such as booleans, numbers, Strings, byte buffers, and Lists and Maps of these (see StandardMessageCodec for details). The serialization and deserialization of these values to and from messages happens automatically when you send and receive values.
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-5
The following table shows how Dart values are received on the platform side and vice versa: Java Kotlin Obj-C Swift C++ C null null bool java.lang.Boolean int java.lang.Integer int, if 32 bits not enough java.lang.Long double java.lang.Double String java.lang.String Uint8List byte[] Int32List int[] Int64List long[] Float32List float[] Float64List double[] List
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-6
Float64List double[] List java.util.ArrayList Map java.util.HashMap null null bool Boolean int Int int, if 32 bits not enough Long double Double String String Uint8List ByteArray Int32List IntArray Int64List LongArray Float32List FloatArray Float64List DoubleArray List List Map HashMap null nil (NSNull when nested)
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-7
HashMap null nil (NSNull when nested) bool NSNumber numberWithBool: int NSNumber numberWithInt: int, if 32 bits not enough NSNumber numberWithLong: double NSNumber numberWithDouble: String NSString Uint8List FlutterStandardTypedData typedDataWithBytes: Int32List FlutterStandardTypedData typedDataWithInt32: Int64List FlutterStandardTypedData typedDataWithInt64: Float32List FlutterStandardTypedData typedDataWithFloat32: Float64List FlutterStandardTypedData typedDataWithFloat64: List
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-8
FlutterStandardTypedData typedDataWithFloat64: List NSArray Map NSDictionary null nil bool NSNumber(value: Bool) int NSNumber(value: Int32) int, if 32 bits not enough NSNumber(value: Int) double NSNumber(value: Double) String String Uint8List FlutterStandardTypedData(bytes: Data) Int32List FlutterStandardTypedData(int32: Data) Int64List FlutterStandardTypedData(int64: Data) Float32List
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-9
Float32List FlutterStandardTypedData(float32: Data) Float64List FlutterStandardTypedData(float64: Data) List Array Map Dictionary null EncodableValue() bool EncodableValue(bool) int EncodableValue(int32_t) int, if 32 bits not enough EncodableValue(int64_t) double EncodableValue(double) String EncodableValue(std::string) Uint8List EncodableValue(std::vector) Int32List EncodableValue(std::vector)
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-10
Int32List EncodableValue(std::vector) Int64List EncodableValue(std::vector) Float32List EncodableValue(std::vector) Float64List EncodableValue(std::vector) List EncodableValue(std::vector) Map EncodableValue(std::map<EncodableValue, EncodableValue>) null FlValue() bool FlValue(bool) int FlValue(int64_t) double FlValue(double) String FlValue(gchar*) Uint8List FlValue(uint8_t*)
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-11
Uint8List FlValue(uint8_t*) Int32List FlValue(int32_t*) Int64List FlValue(int64_t*) Float32List FlValue(float*) Float64List FlValue(double*) List FlValue(FlValue) Map FlValue(FlValue, FlValue) Example: Calling platform-specific code using platform channels The following code demonstrates how to call a platform-specific API to retrieve and display the current battery level. It uses the Android BatteryManager API, the iOS device.batteryLevel API, the Windows GetSystemPowerStatus API, and the Linux UPower API with a single platform message, getBatteryLevel().
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-12
The example adds the platform-specific code inside the main app itself. If you want to reuse the platform-specific code for multiple apps, the project creation step is slightly different (see developing packages), but the platform channel code is still written in the same way. Note: The full, runnable source-code for this example is available in /examples/platform_channel/ for Android with Java, iOS with Objective-C, Windows with C++, and Linux with C. For iOS with Swift, see /examples/platform_channel_swift/. Step 1: Create a new app project Start by creating a new app: In a terminal run: flutter create batterylevel By default, our template supports writing Android code using Kotlin, or iOS code using Swift. To use Java or Objective-C, use the -i and/or -a flags: In a terminal run: flutter create -i objc -a java batterylevel
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-13
In a terminal run: flutter create -i objc -a java batterylevel Step 2: Create the Flutter platform client The app’s State class holds the current app state. Extend that to hold the current battery state. First, construct the channel. Use a MethodChannel with a single platform method that returns the battery level. The client and host sides of a channel are connected through a channel name passed in the channel constructor. All channel names used in a single app must be unique; prefix the channel name with a unique ‘domain prefix’, for example: samples.flutter.dev/battery. Next, invoke a method on the method channel, specifying the concrete method to call using the String identifier getBatteryLevel. The call might fail—for example, if the platform doesn’t support the platform API (such as when running in a simulator), so wrap the invokeMethod call in a try-catch statement.
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-14
Use the returned result to update the user interface state in _batteryLevel inside setState. Finally, replace the build method from the template to contain a small user interface that displays the battery state in a string, and a button for refreshing the value. Step 3: Add an Android platform-specific implementation Kotlin Java Start by opening the Android host portion of your Flutter app in Android Studio: Start Android Studio Select the menu item File > Open… Navigate to the directory holding your Flutter app, and select the android folder inside it. Click OK. Open the file MainActivity.kt located in the kotlin folder in the Project view. Inside the configureFlutterEngine() method, create a MethodChannel and call setMethodCallHandler(). Make sure to use the same channel name as was used on the Flutter client side. import
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-15
import androidx.annotation.NonNull import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel class MainActivity FlutterActivity () private val CHANNEL "samples.flutter.dev/battery" override fun configureFlutterEngine @NonNull flutterEngine FlutterEngine super configureFlutterEngine flutterEngine MethodChannel flutterEngine dartExecutor binaryMessenger CHANNEL
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-16
binaryMessenger CHANNEL ). setMethodCallHandler call result > // This method is invoked on the main thread. // TODO Add the Android Kotlin code that uses the Android battery APIs to retrieve the battery level. This code is exactly the same as you would write in a native Android app. First, add the needed imports at the top of the file: import android.content.Context import android.content.ContextWrapper import android.content.Intent import android.content.IntentFilter import android.os.BatteryManager import android.os.Build.VERSION import
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-17
import android.os.Build.VERSION import android.os.Build.VERSION_CODES Next, add the following method in the MainActivity class, below the configureFlutterEngine() method: private fun getBatteryLevel (): Int val batteryLevel Int if VERSION SDK_INT >= VERSION_CODES LOLLIPOP val batteryManager getSystemService Context BATTERY_SERVICE as BatteryManager batteryLevel batteryManager getIntProperty BatteryManager
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-18
batteryManager getIntProperty BatteryManager BATTERY_PROPERTY_CAPACITY else val intent ContextWrapper applicationContext ). registerReceiver null IntentFilter Intent ACTION_BATTERY_CHANGED )) batteryLevel intent !! getIntExtra BatteryManager EXTRA_LEVEL 100 intent getIntExtra BatteryManager EXTRA_SCALE return batteryLevel
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html
8ebcffba73da-19
return batteryLevel Finally, complete the setMethodCallHandler() method added earlier. You need to handle a single platform method, getBatteryLevel(), so test for that in the call argument. The implementation of this platform method calls the Android code written in the previous step, and returns a response for both the success and error cases using the result argument. If an unknown method is called, report that instead. Remove the following code: MethodChannel flutterEngine dartExecutor binaryMessenger CHANNEL ). setMethodCallHandler call result > // This method is invoked on the main thread. // TODO And replace with the following: MethodChannel flutterEngine dartExecutor binaryMessenger
https://docs.flutter.dev/development/platform-integration/platform-channels/index.html