id
stringlengths
14
17
text
stringlengths
23
1.11k
source
stringlengths
35
114
c59ce75ad41c-2
Geolocation Determine a user's location for enhanced app functionality. Immutable data Handle immutable data structures. Structured local storage Maintain and preserve data. Web sockets Handle client and server connections.
https://docs.flutter.dev/development/packages-and-plugins/happy-paths/index.html
b0b4e36649ae-0
Happy paths recommendations Packages & plugins Happy paths project Happy paths recommendations Ads Background processing Geolocation Immutable data Structured local storage Web sockets Ads Are you looking to monetize your mobile app? You can do that by adding in-app ads using the google_mobile_ads package. You’ll need to register a free account with AdMob and you can then leverage one or more AdMob features, including the following: Several ad formats: Banner, full-screen, native, and rewarded. Control over when ads display. For example, in between levels of a game, after completing a task, or before starting a new game Monetization reports to help you make decisions about your app. Useful links
https://docs.flutter.dev/development/packages-and-plugins/happy-paths/recommended/index.html
b0b4e36649ae-1
Useful links Get started with the AdMob guide Create an AdMob account tutorial google_mobile_ads package on pub.dev Background processing The background processing path shows you how to run a Dart function in the background on mobile devices. With background processing, you can perform tasks like making an HTTP request, running an expensive calculation, or displaying a notification in another isolate (similar to a lightweight thread). There are a of couple ways to incorporate background processing into your mobile app. One way is through a Dart isolate. With a Dart isolate, you can create a separate thread to run tasks concurrently in the background. Another way to incorporate background processing is through the WorkManager plugin. With this plugin, you can enable persistent headless execution of Dart code. Your tasks remain scheduled through app restarts and system reboots.
https://docs.flutter.dev/development/packages-and-plugins/happy-paths/recommended/index.html
b0b4e36649ae-2
Is there a difference between a package and a plugin? Yes, there is! Both are packages, but a plugin is a type of package that contains platform-specific code (such as Kotlin, Java, Swift, Objective C) that communicates with the underlying platform. For more information, see Using packages. Some features of WorkManager include: Persistent work handling Flexible scheduling Ability to apply constraints on jobs like checking for a network connection, only running when the device is charging, or only running when a device is idle (Android only) Useful links Android setup iOS setup Dart concurrency Geolocation
https://docs.flutter.dev/development/packages-and-plugins/happy-paths/recommended/index.html
b0b4e36649ae-3
iOS setup Dart concurrency Geolocation Geolocation, the ability to determine where in the world a user is located, is critical functionality for many applications; for example, shopping apps need to calculate shipping, fitness apps need to track distance traveled, and so on. The plugins in Flutter’s ecosystem offer a number of features to help build these experiences. A plugin that provides this functionality is the geolocator plugin, rated as a Flutter favorite. With this plugin, you can check and request permission, fetch a one-time location, and even provide a stream of constantly updated values as a user moves about. Features include: Ability to get a device’s current location Receive location updates Ability to determine whether a devices’s location services are enabled Useful links
https://docs.flutter.dev/development/packages-and-plugins/happy-paths/recommended/index.html
b0b4e36649ae-4
Useful links How to get a user’s location with the geolocator plugin tutorial geolocator plugin Immutable data For an easy way to represent immutable application data, check out two plugins that provide ways to handle and manipulate immutable data: freezed and json_serializable, both rated as Flutter favorites. These plugins can be used independently, but are also great when used together. The freezed package handles in-memory objects and json_serializable maps those immutable objects to and from the JSON format. Useful links Freezed freezed package video freezed package json_serializable Serializing JSON using json_serializable json_serializable example on GitHub json_serializable package Structured local storage
https://docs.flutter.dev/development/packages-and-plugins/happy-paths/recommended/index.html
b0b4e36649ae-5
Structured local storage Structured local storage increases app performance and improves the user experience by selectively saving expensive or slow data on a user’s device. This path suggests two plugins for local persistence: drift and hive. Which plugin you choose depends on your needs. Drift, rated a Flutter favorite, offers a fully-typed object relational mapping (ORM) around SQLite, with support on all Flutter platforms. Developers who require a fully relational database on their users’ device will benefit most from this package. Hive offers a fully-typed object document mapping (ODM) around a custom storage solution, with support on all Flutter platforms. Developers who do not require a fully relational database, especially if they use document-based storage on their server (like Cloud Firestore) will benefit most from this package. Useful links
https://docs.flutter.dev/development/packages-and-plugins/happy-paths/recommended/index.html
b0b4e36649ae-6
Useful links Drift: The boring flutter development show using Drift video Fluent sqlite database video that references Drift’s previous name, Moor drift package Hive: Hive NoSQL Database IN 16 Minutes video hive package Web sockets Web sockets enable communication between Flutter clients and servers. This path suggests two packages to use when installing and using web sockets. Use the web_socket_channel package for client-side web socket connections, and the web_socket_connections package for server-side Dart web sockets. Useful links web_socket_channel: Work with WebSockets cookbook recipe web_socket_channel package shelf_web_socket shelf_web_socket example shelf_web_socket package
https://docs.flutter.dev/development/packages-and-plugins/happy-paths/recommended/index.html
bf90ee36c503-0
Packages & plugins Packages & plugins Topics: Background processes Developing packages & plugins Flutter Favorites program Happy paths project Happy paths recommendations Plugins in Flutter tests Using packages Package site
https://docs.flutter.dev/development/packages-and-plugins/index.html
e8880d00d32d-0
Plugins in Flutter tests Packages & plugins Plugin tests Wrap the plugin Mock the plugin’s public API Mock the plugin’s platform interface Mock the platform channel Note: To learn how to avoid crashes from a plugin when testing your Flutter app, read on. To learn how to test your plugin code, check out Testing plugins. Almost all Flutter plugins have two parts: Dart code, which provides the API your code calls. Code written in a platform-specific (or “host”) language, such as Kotlin or Swift, which implements those APIs. In fact, the native (or host) language code distinguishes a plugin package from a standard package.
https://docs.flutter.dev/development/packages-and-plugins/plugins-in-tests/index.html
e8880d00d32d-1
Building and registering the host portion of a plugin is part of the Flutter application build process, so plugins only work when your code is running in your application, such as with flutter run or when running integration tests. When running Dart unit tests or widget tests, the host code isn’t available. If the code you are testing calls any plugins, this often results in errors like the following: MissingPluginException(No implementation found for method someMethodName on channel some_channel_name) Note: Plugin implementations that only use Dart will work in unit tests. This is an implementation detail of the plugin, however, so tests shouldn’t rely on it. When unit testing code that uses plugins, there are several options to avoid this exception. The following solutions are listed in order of preference. Wrap the plugin In most cases, the best approach is to wrap plugin calls in your own API, and provide a way of mocking your own API in tests.
https://docs.flutter.dev/development/packages-and-plugins/plugins-in-tests/index.html
e8880d00d32d-2
This has several advantages: If the plugin API changes, you won’t need to update your tests. You are only testing your own code, so your tests can’t fail due to behavior of a plugin you’re using. You can use the same approach regardless of how the plugin is implemented, or even for non-plugin package dependencies. Mock the plugin’s public API If the plugin’s API is already based on class instances, you can mock it directly, with the following caveats: This won’t work if the plugin uses non-class functions or static methods. Tests will need to be updated when the plugin API changes. Mock the plugin’s platform interface If the plugin is a federated plugin, it will include a platform interface that allows registering implementations of its internal logic. You can register a mock of that platform interface implementation instead of the public API with the following caveats:
https://docs.flutter.dev/development/packages-and-plugins/plugins-in-tests/index.html
e8880d00d32d-3
This won’t work if the plugin isn’t federated. Your tests will include part of the plugin’s code, so plugin behavior could cause problems for your tests. For instance, if a plugin writes files as part of an internal cache, your test behavior might change based on whether you had run the test previously. Tests might need to be updated when the platform interface changes. An example of when this might be necessary is mocking the implementation of a plugin used by a package that you rely on, rather than your own code, so you can’t change how it’s called. However, if possible, you should mock the dependency that uses the plugin instead. Mock the platform channel If the plugin uses platform channels, you can mock the platform channels using TestDefaultBinaryMessenger. This should only be used if, for some reason, none of the methods above are available, as it has several drawbacks:
https://docs.flutter.dev/development/packages-and-plugins/plugins-in-tests/index.html
e8880d00d32d-4
Only implementations that use platform channels can be mocked. This means that if some implementations don’t use platform channels, your tests will unexpectedly use real implementations when run on some platforms. Platform channels are usually internal implementation details of plugins. They might change substantially even in a bugfix update to a plugin, breaking your tests unexpectedly. Platform channels might differ in each implementation of a federated plugin. For instance, you might set up mock platform channels to make tests pass on a Windows machine, then find that they fail if run on macOS or Linux. Platform channels aren’t strongly typed. For example, method channels often use dictionaries and you have to read the plugin’s implementation to know what the key strings and value types are. Because of these limitations, TestDefaultBinaryMessenger is mainly useful in the internal tests of plugin implementations, rather than tests of code using plugins. You might also want to check out Testing plugins.
https://docs.flutter.dev/development/packages-and-plugins/plugins-in-tests/index.html
8860b73b8ec4-0
Using packages Packages & plugins Using packages Using packages Searching for packages Adding a package dependency to an app Adding a package dependency to an app using flutter pub add Removing a package dependency to an app using flutter pub remove Conflict resolution Developing new packages Managing package dependencies and versions Package versions Updating package dependencies Dependencies on unpublished packages Examples Example: Using the css_colors package Example: Using the url_launcher package to launch the browser Flutter supports using shared packages contributed by other developers to the Flutter and Dart ecosystems. This allows quickly building an app without having to develop everything from scratch. What is the difference between a package and a plugin? A plugin is a type of package—the full designation is plugin package, which is generally shortened to plugin.
https://docs.flutter.dev/development/packages-and-plugins/using-packages/index.html
8860b73b8ec4-1
At a minimum, a Dart package is a directory containing a pubspec.yaml file. Additionally, a package can contain dependencies (listed in the pubspec), Dart libraries, apps, resources, tests, images, fonts, and examples. The pub.dev site lists many packages—developed by Google engineers and generous members of the Flutter and Dart community— that you can use in your app. A plugin package is a special kind of package that makes platform functionality available to the app. Plugin packages can be written for Android (using Kotlin or Java), iOS (using Swift or Objective-C), web, macOS, Windows, Linux, or any combination thereof. For example, a plugin might provide Flutter apps with the ability to use a device’s camera.
https://docs.flutter.dev/development/packages-and-plugins/using-packages/index.html
8860b73b8ec4-2
Existing packages enable many use cases—for example, making network requests (http), navigation/route handling (go_router), integration with device APIs (url_launcher and battery_plus), and using third-party platform SDKs like Firebase (FlutterFire). To write a new package, see developing packages. To add assets, images, or fonts, whether stored in files or packages, see Adding assets and images. Using packages The following section describes how to use existing published packages. Searching for packages Packages are published to pub.dev. The Flutter landing page on pub.dev displays top packages that are compatible with Flutter (those that declare dependencies generally compatible with Flutter), and supports searching among all published packages.
https://docs.flutter.dev/development/packages-and-plugins/using-packages/index.html
8860b73b8ec4-3
The Flutter Favorites page on pub.dev lists the plugins and packages that have been identified as packages you should first consider using when writing your app. For more information on what it means to be a Flutter Favorite, see the Flutter Favorites program. Android, iOS, web, Linux, Windows, macOS, or any combination thereof. Adding a package dependency to an app To add the package, css_colors, to an app: Depend on it Open the pubspec.yaml file located inside the app folder, and add css_colors: under dependencies. Install it From the terminal: Run flutter pub get. OR
https://docs.flutter.dev/development/packages-and-plugins/using-packages/index.html
8860b73b8ec4-4
Install it From the terminal: Run flutter pub get. OR From VS Code: Click Get Packages located in right side of the action ribbon at the top of pubspec.yaml indicated by the Download icon. From Android Studio/IntelliJ: Click Pub get in the action ribbon at the top of pubspec.yaml. Import it Add a corresponding import statement in the Dart code. Stop and restart the app, if necessary If the package brings platform-specific code (Kotlin/Java for Android, Swift/Objective-C for iOS), that code must be built into your app. Hot reload and hot restart only update the Dart code, so a full restart of the app might be required to avoid errors like MissingPluginException when using the package. Adding a package dependency to an app using flutter pub add To add the package, css_colors, to an app:
https://docs.flutter.dev/development/packages-and-plugins/using-packages/index.html
8860b73b8ec4-5
To add the package, css_colors, to an app: Issue the command while being inside the project directory flutter pub add css_colors Import it Add a corresponding import statement in the Dart code. Stop and restart the app, if necessary If the package brings platform-specific code (Kotlin/Java for Android, Swift/Objective-C for iOS), that code must be built into your app. Hot reload and hot restart only update the Dart code, so a full restart of the app might be required to avoid errors like MissingPluginException when using the package. Removing a package dependency to an app using flutter pub remove To remove the package, css_colors, to an app: Issue the command while being inside the project directory flutter pub remove css_colors The Installing tab, available on any package page on pub.dev, is a handy reference for these steps.
https://docs.flutter.dev/development/packages-and-plugins/using-packages/index.html
8860b73b8ec4-6
For a complete example, see the css_colors example below. Conflict resolution Suppose you want to use some_package and another_package in an app, and both of these depend on url_launcher, but in different versions. That causes a potential conflict. The best way to avoid this is for package authors to use version ranges rather than specific versions when specifying dependencies. dependencies url_launcher ^5.4.0 # Good, any version >= 5.4.0 but < 6.0.0 image_picker 5.4.3' # Not so good, only version 5.4.3 works. Gradle modules and/or CocoaPods are solved in a similar way.
https://docs.flutter.dev/development/packages-and-plugins/using-packages/index.html
8860b73b8ec4-7
CocoaPods are solved in a similar way. Even if some_package and another_package declare incompatible versions for url_launcher, they might actually use url_launcher in compatible ways. In this situation, the conflict can be resolved by adding a dependency override declaration to the app’s pubspec.yaml file, forcing the use of a particular version. For example, to force the use of url_launcher version 5.4.0, make the following changes to the app’s pubspec.yaml file: dependencies some_package another_package dependency_overrides url_launcher 5.4.0' If the conflicting dependency is not itself a package, but an Android-specific library like guava, the dependency override declaration must be added to Gradle build logic instead.
https://docs.flutter.dev/development/packages-and-plugins/using-packages/index.html
8860b73b8ec4-8
To force the use of guava version 28.0, make the following changes to the app’s android/build.gradle file: configurations all resolutionStrategy force 'com.google.guava:guava:28.0-android' CocoaPods doesn’t currently offer dependency override functionality. Developing new packages If no package exists for your specific use case, you can write a custom package. Managing package dependencies and versions To minimize the risk of version collisions, specify a version range in the pubspec.yaml file. Package versions All packages have a version number, specified in the package’s pubspec.yaml file. The current version of a package is displayed next to its name (for example, see the url_launcher package), as well as a list of all prior versions (see url_launcher versions).
https://docs.flutter.dev/development/packages-and-plugins/using-packages/index.html
8860b73b8ec4-9
To ensure that the app doesn’t break when a package is updated, specify a version range using one of the following formats: Range constraints: Specify a minimum and maximum version. For example: dependencies: url_launcher: '>=5.4.0 <6.0.0' Range constraints with caret syntax are similar to regular range constraints: dependencies: collection: '^5.4.0' For additional details, see the package versioning guide. Updating package dependencies When running flutter pub get for the first time after adding a package, Flutter saves the concrete package version found in the pubspec.lock lockfile. This ensures that you get the same version again if you, or another developer on your team, run flutter pub get.
https://docs.flutter.dev/development/packages-and-plugins/using-packages/index.html
8860b73b8ec4-10
To upgrade to a new version of the package, for example to use new features in that package, run flutter pub upgrade to retrieve the highest available version of the package that is allowed by the version constraint specified in pubspec.yaml. Note that this is a different command from flutter upgrade or flutter update-packages, which both update Flutter itself. Dependencies on unpublished packages Packages can be used even when not published on pub.dev. For private packages, or for packages not ready for publishing, additional dependency options are available: A Flutter app can depend on a package using a file system path: dependency. The path can be either relative or absolute. Relative paths are evaluated relative to the directory containing pubspec.yaml. For example, to depend on a package, packageA, located in a directory next to the app, use the following syntax: dependencies: packageA: path: ../packageA/
https://docs.flutter.dev/development/packages-and-plugins/using-packages/index.html
8860b73b8ec4-11
dependencies: packageA: path: ../packageA/ You can also depend on a package stored in a Git repository. If the package is located at the root of the repo, use the following syntax: dependencies: packageA: git: url: https://github.com/flutter/packageA.git If the repository is private and you can connect to it using SSH, depend on the package by using the repo’s SSH url: dependencies: packageA: git: url: [email protected]:flutter/packageA.git Pub assumes the package is located in the root of the Git repository. If that isn’t the case, specify the location with the path argument. For example: dependencies: packageA: git: url: https://github.com/flutter/packages.git path: packages/packageA
https://docs.flutter.dev/development/packages-and-plugins/using-packages/index.html
8860b73b8ec4-12
Finally, use the ref argument to pin the dependency to a specific git commit, branch, or tag. For more details, see Package dependencies. Examples The following examples walk through the necessary steps for using packages. Example: Using the css_colors package The css_colors package defines color constants for CSS colors, so use the constants wherever the Flutter framework expects the Color type. To use this package: Create a new project called cssdemo. Open pubspec.yaml, and add the css-colors dependency: dependencies: flutter: sdk: flutter css_colors: ^1.0.0 Run flutter pub get in the terminal, or click Get Packages in VS Code. Open lib/main.dart and replace its full contents with:
https://docs.flutter.dev/development/packages-and-plugins/using-packages/index.html
8860b73b8ec4-13
Open lib/main.dart and replace its full contents with: import 'package:css_colors/css_colors.dart'; import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: DemoPage(), ); } } class DemoPage extends StatelessWidget { const DemoPage({super.key}); @override Widget build(BuildContext context) { return Scaffold(body: Container(color: CSSColors.orange)); } } Run the app. The app’s background should now be orange. Example: Using the url_launcher package to launch the browser
https://docs.flutter.dev/development/packages-and-plugins/using-packages/index.html
8860b73b8ec4-14
Example: Using the url_launcher package to launch the browser The url_launcher plugin package enables opening the default browser on the mobile platform to display a given URL, and is supported on Android, iOS, web, Windows, Linux, and macos. This package is a special Dart package called a plugin package (or plugin), which includes platform-specific code. To use this plugin: Create a new project called launchdemo. Open pubspec.yaml, and add the url_launcher dependency: dependencies: flutter: sdk: flutter url_launcher: ^5.4.0 Run flutter pub get in the terminal, or click Get Packages get in VS Code. Open lib/main.dart and replace its full contents with the following:
https://docs.flutter.dev/development/packages-and-plugins/using-packages/index.html
8860b73b8ec4-15
Open lib/main.dart and replace its full contents with the following: import 'package:flutter/material.dart'; import 'package:path/path.dart' as p; import 'package:url_launcher/url_launcher.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: DemoPage(), ); } } class DemoPage extends StatelessWidget { const DemoPage({super.key}); launchURL() { launchUrl(p.toUri('https://flutter.dev')); }
https://docs.flutter.dev/development/packages-and-plugins/using-packages/index.html
8860b73b8ec4-16
@override Widget build(BuildContext context) { return Scaffold( body: Center( child: ElevatedButton( onPressed: launchURL, child: const Text('Show Flutter homepage'), ), ), ); } } Run the app (or stop and restart it, if it was already running before adding the plugin). Click Show Flutter homepage. You should see the default browser open on the device, displaying the homepage for flutter.dev.
https://docs.flutter.dev/development/packages-and-plugins/using-packages/index.html
f102d2552c53-0
AndroidX migration Platform integration Android AndroidX migration Common Questions How do I migrate my existing app, plugin or host-editable module project to AndroidX? What if I can’t use Android Studio? Add to app How do I know if my project is using AndroidX? What if I don’t migrate my app or module to AndroidX? What if my app is migrated to AndroidX, but not all of the plugins I use? I’m having issues migrating to AndroidX Note: You might be directed to this page if Flutter detects that your project doesn’t use AndroidX. AndroidX is a major improvement to the original Android Support Library. It provides the androidx.* package libraries, unbundled from the platform API. This means that it offers backward compatibility and is updated more frequently than the Android platform. Common Questions
https://docs.flutter.dev/development/platform-integration/android/androidx-migration/index.html
f102d2552c53-1
Common Questions How do I migrate my existing app, plugin or host-editable module project to AndroidX? You will need Android Studio 3.2 or higher. If you don’t have it installed, you can download the latest version from the Android Studio site. Open Android Studio. Select Open an existing Android Studio Project. Open the android directory within your app. Wait until the project has been synced successfully. (This happens automatically once you open the project, but if it doesn’t, select Sync Project with Gradle Files from the File menu). Select Migrate to AndroidX from the Refactor menu. If you are asked to backup the project before proceeding, check Backup project as Zip file, then click Migrate. Lastly, save the zip file in your location of preference. The refactoring preview shows the list of changes. Finally, click Do Refactor:
https://docs.flutter.dev/development/platform-integration/android/androidx-migration/index.html
f102d2552c53-2
The refactoring preview shows the list of changes. Finally, click Do Refactor: That is it! You successfully migrated your project to AndroidX. Finally, if you migrated a plugin, publish the new AndroidX version to pub and update your CHANGELOG.md to indicate that this new version is compatible with AndroidX. What if I can’t use Android Studio? You can create a new project using the Flutter tool and then move the Dart code and assets to the new project. To create a new project run: t <project-type> <new-project-path> Add to app If your Flutter project is a module type for adding to an existing Android app, and contains a .android directory, add the following line to pubspec.yaml: module ... androidX true # Add this line.
https://docs.flutter.dev/development/platform-integration/android/androidx-migration/index.html
f102d2552c53-3
androidX true # Add this line. Finally, run flutter clean. If your module contains an android directory instead, then follow the steps in previous section. How do I know if my project is using AndroidX? Starting from Flutter v1.12.13, new projects created with flutter create -t <project-type> use AndroidX by default. Projects created prior to this Flutter version mustn’t depend on any old build artifact or old Support Library class. In an app or module project, the file android/gradle.properties or .android/gradle.properties must contain: What if I don’t migrate my app or module to AndroidX?
https://docs.flutter.dev/development/platform-integration/android/androidx-migration/index.html
f102d2552c53-4
What if I don’t migrate my app or module to AndroidX? Your app might continue to work. However, combining AndroidX and Support artifacts is generally not recommended because it can result in dependency conflicts or other kind of Gradle failures. As a result, as more plugins migrate to AndroidX, plugins depending on Android core libraries are likely to cause build failures. What if my app is migrated to AndroidX, but not all of the plugins I use? The Flutter tool uses Jetifier to automatically migrate Flutter plugins using the Support Library to AndroidX, so you can use the same plugins even if they haven’t been migrated to AndroidX yet. I’m having issues migrating to AndroidX Open an issue on GitHub and add [androidx-migration] to the title of the issue.
https://docs.flutter.dev/development/platform-integration/android/androidx-migration/index.html
36b1c9570a0a-0
Binding to native Android code using dart:ffi Platform integration Android Binding to native Android 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 Platform library First-party library Open-source third-party Closed-source third-party library Android APK size (shared object compression) 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/android/c-interop/index.html
36b1c9570a0a-1
Note: This page describes using the dart:ffi library in Android apps. For information on iOS, see Binding to native iOS 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 Android 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 both Android and 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/android/c-interop/index.html
36b1c9570a0a-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 Android, a dynamically linked library is distributed as a set of .so (ELF) files, one for each architecture. A dynamically linked library can be loaded into Dart via 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
https://docs.flutter.dev/development/platform-integration/android/c-interop/index.html
36b1c9570a0a-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 Android build system about the native code so the code can be compiled and linked appropriately into the final application. You can add Android-specific sources to the android folder and modify CMakeLists.txt appropriately. Also, Gradle allows you to point to the ios folder, if that helps, but it’s not required to use the same sources for both iOS and Android;
https://docs.flutter.dev/development/platform-integration/android/c-interop/index.html
36b1c9570a0a-4
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. On Android, you need to create a CMakeLists.txt file to define how the sources should be compiled and point Gradle to it. From the root of your project directory, use the following instructions cat > android/CMakeLists.txt << EOF cmake_minimum_required(VERSION 3.4.1) # for example add_library( native_add # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). ../ios/Classes/native_add.cpp ) EOF
https://docs.flutter.dev/development/platform-integration/android/c-interop/index.html
36b1c9570a0a-5
EOF Finally, add an externalNativeBuild section to android/build.gradle. For example: 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 is not 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 (see above), 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 Platform library
https://docs.flutter.dev/development/platform-integration/android/c-interop/index.html
36b1c9570a0a-6
Other use cases Platform library To link against a platform library, use the following instructions: Find the desired library in the Android NDK Native APIs list in the Android docs. This lists stable native APIs. Load the library using DynamicLibrary.open. For example, to load OpenGL ES (v3): DynamicLibrary.open('libGLES_v3.so'); You might need to update the Android manifest file of the app or plugin if indicated by the documentation. First-party library The process for including native code in source code or binary form is the same for an app or plugin. Open-source third-party Follow the Add C and C++ code to your project instructions in the Android docs to add native code and support for the native code toolchain (either CMake or ndk-build). Closed-source third-party library
https://docs.flutter.dev/development/platform-integration/android/c-interop/index.html
36b1c9570a0a-7
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: Open the android/build.gradle file for your project. Add the AAR artifact as a dependency. Don’t include the artifact in your Flutter package. Instead, it should be downloaded from a repository, such as JCenter. Android APK size (shared object compression) Android guidelines in general recommend distributing native shared objects uncompressed because that actually saves on device space. Shared objects can be directly loaded from the APK instead of unpacking them on device into a temporary location and then loading. APKs are additionally packed in transit—that’s why you should be looking at download size.
https://docs.flutter.dev/development/platform-integration/android/c-interop/index.html
36b1c9570a0a-8
Flutter APKs by default don’t follow these guidelines and compress libflutter.so and libapp.so—this leads to smaller APK size but larger on device size. Shared objects from third parties can change this default setting with android:extractNativeLibs="true" in their AndroidManifest.xml and stop the compression of libflutter.so, libapp.so, and any user-added shared objects. To re-enable compression, override the setting in your_app_name/android/app/src/main/AndroidManifest.xml in the following way. @@ -1,5 +1,6 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.your_app_name">
https://docs.flutter.dev/development/platform-integration/android/c-interop/index.html
36b1c9570a0a-9
package="com.example.your_app_name"> + xmlns:tools="http://schemas.android.com/tools" + package="com.example.your_app_name" > <!-- io.flutter.app.FlutterApplication is an android.app.Application that calls FlutterMain.startInitialization(this); in its onCreate method. In most cases you can leave this as-is, but you if you want to provide additional functionality it is fine to subclass or reimplement FlutterApplication and put your custom class here. --> @@ -8,7 +9,9 @@ <application android:name="io.flutter.app.FlutterApplication" android:label="your_app_name" android:icon="@mipmap/ic_launcher"> + android:icon="@mipmap/ic_launcher" + android:extractNativeLibs="true" + tools:replace="android:extractNativeLibs">
https://docs.flutter.dev/development/platform-integration/android/c-interop/index.html
4137afd23f58-0
Targeting ChromeOS with Android Platform integration Android Targeting ChromeOS with Android Flutter & ChromeOS tips & tricks Flutter ChromeOS lint analysis This page discusses considerations unique to building Android apps that support ChromeOS with Flutter. Flutter & ChromeOS tips & tricks For the current versions of ChromeOS, only certain ports from Linux are exposed to the rest of the environment. Here’s an example of how to launch Flutter DevTools for an Android app with ports that will work: flutter pub global run devtools -port 8000 cd path/to/your/app flutter run -observatory-port =8080
https://docs.flutter.dev/development/platform-integration/android/chromeos/index.html
4137afd23f58-1
-observatory-port =8080 Then, navigate to http://127.0.0.1:8000/# in your Chrome browser and enter the URL to your application. The last flutter run command you just ran should output a URL similar to the format of http://127.0.0.1:8080/auth_code=/. Use this URL and select “Connect” to start the Flutter DevTools for your Android app. Flutter ChromeOS lint analysis Flutter has ChromeOS-specific lint analysis checks to make sure that the app that you’re building works well on ChromeOS. It looks for things like required hardware in your Android Manifest that aren’t available on ChromeOS devices, permissions that imply requests for unsupported hardware, as well as other properties or code that would bring a lesser experience on these devices.
https://docs.flutter.dev/development/platform-integration/android/chromeos/index.html
4137afd23f58-2
To activate these, you need to create a new analysis_options.yaml file in your project folder to include these options. (If you have an existing analysis_options.yaml file, you can update it) include package:flutter/analysis_options_user.yaml analyzer optional-checks chrome-os-manifest-checks To run these from the command line, use the following command: flutter analyze Sample output for this command might look like: Analyzing ... warning • This hardware feature is not supported on ChromeOS • android/app/src/main/AndroidManifest.xml:4:33 • unsupported_chrome_os_hardware
https://docs.flutter.dev/development/platform-integration/android/chromeos/index.html
0a101eac3478-0
Android Platform integration Android Topics: Adding a splash screen C interop Hosting native Android views AndroidX migration Deprecated Splash Screen API Migration Targeting ChromeOS with Android
https://docs.flutter.dev/development/platform-integration/android/index.html
004291a85f1d-0
Hosting native Android views in your Flutter app with Platform Views Platform integration Android Android platform-views On the Dart side Hybrid composition Virtual display On the platform side 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 SDK 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 iOS views in your Flutter app, see Hosting native iOS views. Flutter supports two modes: Hybrid composition and virtual displays. Which one to use depends on the use case. Let’s take a look:
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-1
Which one to use depends on the use case. Let’s take a look: Hybrid composition appends the native android.view.View to the view hierarchy. Therefore, keyboard handling, and accessibility work out of the box. Prior to Android 10, this mode might significantly reduce the frame throughput (FPS) of the Flutter UI. For more context, see Performance. Virtual displays render the android.view.View instance to a texture, so it’s not embedded within the Android Activity’s view hierarchy. Certain platform interactions such as keyboard handling and accessibility features might not work. To create a platform view on Android, use the following steps: On the Dart side On the Dart side, create a Widget and add one of the following build implementations. Hybrid composition In your Dart file, for example native_view_example.dart, use the following instructions: Add the following imports:
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-2
Add the following imports: import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.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. const Map<String, dynamic> creationParams = <String, dynamic>{};
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-3
return PlatformViewLink( viewType: viewType, surfaceFactory: (context, controller) { return AndroidViewSurface( controller: controller as AndroidViewController, gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, hitTestBehavior: PlatformViewHitTestBehavior.opaque, ); }, onCreatePlatformView: (params) { return PlatformViewsService.initSurfaceAndroidView( id: params.id, viewType: viewType, layoutDirection: TextDirection.ltr, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), onFocus: () { params.onFocusChanged(true); }, ) ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated) ..create(); }, ); } For more information, see the API docs for: PlatformViewLink AndroidViewSurface PlatformViewsService
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-4
AndroidViewSurface PlatformViewsService Virtual display In your Dart file, for example native_view_example.dart, use the following instructions: Add the following imports: import 'package:flutter/material.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>{}; return AndroidView( viewType: viewType, layoutDirection: TextDirection.ltr, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), ); } For more information, see the API docs for: AndroidView
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-5
For more information, see the API docs for: AndroidView On the platform side On the platform side, use the standard io.flutter.plugin.platform package in either Java or Kotlin: Kotlin Java In your native code, implement the following: Extend io.flutter.plugin.platform.PlatformView to provide a reference to the android.view.View (for example, NativeView.kt): package dev.flutter.example import android.content.Context import android.graphics.Color import android.widget.TextView import io.flutter.plugin.platform.PlatformView internal class NativeView context Context id
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-6
context Context id Int creationParams Map String ?, Any ?>?) PlatformView private val textView TextView override fun getView (): View return textView override fun dispose () {} init textView TextView context textView textSize 72f textView setBackgroundColor Color rgb
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-7
setBackgroundColor Color rgb 255 255 255 )) textView text "Rendered on a native Android view (id: $id)" Create a factory class that creates an instance of the NativeView created earlier (for example, NativeViewFactory.kt): package dev.flutter.example import android.content.Context import android.view.View import io.flutter.plugin.common.StandardMessageCodec import io.flutter.plugin.platform.PlatformView import io.flutter.plugin.platform.PlatformViewFactory class NativeViewFactory PlatformViewFactory
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-8
class NativeViewFactory PlatformViewFactory StandardMessageCodec INSTANCE override fun create context Context viewId Int args Any ?): PlatformView val creationParams args as Map String ?, Any ?>? return NativeView context viewId creationParams Finally, register the platform view. You can do this in an app or a plugin. For app registration, modify the app’s main activity (for example, MainActivity.kt):
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-9
package dev.flutter.example import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine class MainActivity FlutterActivity () override fun configureFlutterEngine flutterEngine FlutterEngine flutterEngine platformViewsController registry registerViewFactory "<platform-view-type>" NativeViewFactory ()) For plugin registration, modify the plugin’s main class (for example, PlatformViewPlugin.kt): package dev.flutter.plugin.example import io.flutter.embedding.engine.plugins.FlutterPlugin
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-10
io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding class PlatformViewPlugin FlutterPlugin override fun onAttachedToEngine binding FlutterPluginBinding binding platformViewRegistry registerViewFactory "<platform-view-type>" NativeViewFactory ()) override fun onDetachedFromEngine binding FlutterPluginBinding {} In your native code, implement the following: Extend io.flutter.plugin.platform.PlatformView to provide a reference to the android.view.View (for example, NativeView.java):
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-11
package dev.flutter.example import android.content.Context import android.graphics.Color import android.view.View import android.widget.TextView import androidx.annotation.NonNull import androidx.annotation.Nullable import io.flutter.plugin.platform.PlatformView import java.util.Map class NativeView implements PlatformView @NonNull private final TextView textView NativeView @NonNull Context context int id
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-12
Context context int id @Nullable Map String Object creationParams textView new TextView context ); textView setTextSize 72 ); textView setBackgroundColor Color rgb 255 255 255 )); textView setText "Rendered on a native Android view (id: " id ")" ); @NonNull @Override public
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-13
@NonNull @Override public View getView () return textView @Override public void dispose () {} Create a factory class that creates an instance of the NativeView created earlier (for example, NativeViewFactory.java): package dev.flutter.example import android.content.Context import androidx.annotation.Nullable import androidx.annotation.NonNull import io.flutter.plugin.common.StandardMessageCodec import io.flutter.plugin.platform.PlatformView import
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-14
io.flutter.plugin.platform.PlatformView import io.flutter.plugin.platform.PlatformViewFactory import java.util.Map class NativeViewFactory extends PlatformViewFactory NativeViewFactory () super StandardMessageCodec INSTANCE ); @NonNull @Override public PlatformView create @NonNull Context context int id @Nullable Object args final Map String Object creationParams Map String
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-15
creationParams Map String Object >) args return new NativeView context id creationParams ); Finally, register the platform view. You can do this in an app or a plugin. For app registration, modify the app’s main activity (for example, MainActivity.java): package dev.flutter.example import androidx.annotation.NonNull import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine public class MainActivity extends FlutterActivity @Override
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-16
extends FlutterActivity @Override public void configureFlutterEngine @NonNull FlutterEngine flutterEngine flutterEngine getPlatformViewsController () getRegistry () registerViewFactory "<platform-view-type>" new NativeViewFactory ()); For plugin registration, modify the plugin’s main file (for example, PlatformViewPlugin.java): package dev.flutter.plugin.example import androidx.annotation.NonNull import io.flutter.embedding.engine.plugins.FlutterPlugin public class PlatformViewPlugin
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-17
public class PlatformViewPlugin implements FlutterPlugin @Override public void onAttachedToEngine @NonNull FlutterPluginBinding binding binding getPlatformViewRegistry () registerViewFactory "<platform-view-type>" new NativeViewFactory ()); @Override public void onDetachedFromEngine @NonNull FlutterPluginBinding binding {} For more information, see the API docs for: FlutterPlugin PlatformViewRegistry PlatformViewFactory PlatformView
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-18
PlatformViewRegistry PlatformViewFactory PlatformView Finally, modify your build.gradle file to require one of the minimal Android SDK versions: android defaultConfig minSdkVersion 19 // if using hybrid composition minSdkVersion 20 // if using virtual display. 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.
https://docs.flutter.dev/development/platform-integration/android/platform-views/index.html
004291a85f1d-19
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. 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/android/platform-views/index.html
550898503800-0
Adding a splash screen to your Android app Platform integration Android Splash screen Overview Initializing the app Set up the FlutterActivity in AndroidManifest.xml Android 12 Splash screens (also known as launch screens) provide a simple initial experience while your Android app loads. They set the stage for your application, while allowing time for the app engine to load and your app to initialize. Overview Warning: If you are experiencing a crash from implementing a splash screen, you might need to migrate your code. See detailed instructions in the Deprecated Splash Screen API Migration guide. In Android, there are two separate screens that you can control: a launch screen shown while your Android app initializes, and a splash screen that displays while the Flutter experience initializes.
https://docs.flutter.dev/development/platform-integration/android/splash-screen/index.html
550898503800-1
Note: As of Flutter 2.5, the launch and splash screens have been consolidated—Flutter now only implements the Android launch screen, which is displayed until the framework draws the first frame. This launch screen can act as both an Android launch screen and an Android splash screen via customization, and thus, is referred to as both terms. For example of such customization, check out the Android splash screen sample app. If, prior to 2.5, you used flutter create to create an app, and you run the app on 2.5 or later, the app might app crash. For more info, see the Deprecated Splash Screen API Migration guide. Note: For apps that embed one or more Flutter screens within an existing Android app, consider pre-warming a FlutterEngine and reusing the same engine throughout your app to minimize wait time associated with initialization of the Flutter engine. Initializing the app
https://docs.flutter.dev/development/platform-integration/android/splash-screen/index.html
550898503800-2
Initializing the app Every Android app requires initialization time while the operating system sets up the app’s process. Android provides the concept of a launch screen to display a Drawable while the app is initializing. The default Flutter project template includes a definition of a launch theme and a launch background. You can customize this by editing styles.xml, where you can define a theme whose windowBackground is set to the Drawable that should be displayed as the launch screen. <style name= "LaunchTheme" parent= "@android:style/Theme.Black.NoTitleBar" <item name= "android:windowBackground" >@drawable/launch_background </item> </style>
https://docs.flutter.dev/development/platform-integration/android/splash-screen/index.html
550898503800-3
</item> </style> In addition, styles.xml defines a normal theme to be applied to FlutterActivity after the launch screen is gone. The normal theme background only shows for a very brief moment after the splash screen disappears, and during orientation change and Activity restoration. Therefore, it’s recommended that the normal theme use a solid background color that looks similar to the primary background color of the Flutter UI. <style name= "NormalTheme" parent= "@android:style/Theme.Black.NoTitleBar" <item name= "android:windowBackground" >@drawable/normal_background </item> </style> Set up the FlutterActivity in AndroidManifest.xml
https://docs.flutter.dev/development/platform-integration/android/splash-screen/index.html
550898503800-4
Set up the FlutterActivity in AndroidManifest.xml In AndroidManifest.xml, set the theme of FlutterActivity to the launch theme. Then, add a metadata element to the desired FlutterActivity to instruct Flutter to switch from the launch theme to the normal theme at the appropriate time. <activity android:name= ".MyActivity" android:theme= "@style/LaunchTheme" // ... <meta-data android:name= "io.flutter.embedding.android.NormalTheme" android:resource= "@style/NormalTheme" /> <intent-filter> <action android:name= "android.intent.action.MAIN" /> <category
https://docs.flutter.dev/development/platform-integration/android/splash-screen/index.html
550898503800-5
/> <category android:name= "android.intent.category.LAUNCHER" /> </intent-filter> </activity> The Android app now displays the desired launch screen while the app initializes. Android 12 To configure your launch screen on Android 12, check out Android Splash Screens. As of Android 12, you must use the new splash screen API in your styles.xml file. Consider creating an alternate resource file for Android 12 and higher. Also make sure that your background image is in line with the icon guidelines; check out Android Splash Screens for more details. <style name= "LaunchTheme" parent= "@android:style/Theme.Black.NoTitleBar" <item
https://docs.flutter.dev/development/platform-integration/android/splash-screen/index.html
550898503800-6
<item name= "android:windowSplashScreenBackground" >@color/bgColor </item> <item name= "android:windowSplashScreenAnimatedIcon" >@drawable/launch_background </item> </style> Make sure that io.flutter.embedding.android.SplashScreenDrawable is not set in your manifest, and that provideSplashScreen is not implemented, as these APIs are deprecated. Doing so causes the Android launch screen to fade smoothly into the Flutter when the app is launched and the app might crash. Some apps might want to continue showing the last frame of the Android launch screen in Flutter. For example, this preserves the illusion of a single frame while additional loading continues in Dart. To achieve this, the following Android APIs might be helpful: Java
https://docs.flutter.dev/development/platform-integration/android/splash-screen/index.html
550898503800-7
Java Kotlin import android.os.Build import android.os.Bundle import android.window.SplashScreenView import androidx.core.view.WindowCompat import io.flutter.embedding.android.FlutterActivity public class MainActivity extends FlutterActivity @Override protected void onCreate Bundle savedInstanceState // Aligns the Flutter view vertically with the window. WindowCompat setDecorFitsSystemWindows getWindow (), false ); if Build
https://docs.flutter.dev/development/platform-integration/android/splash-screen/index.html
550898503800-8
false ); if Build VERSION SDK_INT >= Build VERSION_CODES // Disable the Android splash screen fade out animation to avoid // a flicker before the similar frame is drawn in Flutter. getSplashScreen () setOnExitAnimationListener SplashScreenView splashScreenView > splashScreenView remove (); }); super onCreate savedInstanceState ); import android.os.Build import android.os.Bundle import
https://docs.flutter.dev/development/platform-integration/android/splash-screen/index.html
550898503800-9
import android.os.Bundle import androidx.core.view.WindowCompat import io.flutter.embedding.android.FlutterActivity class MainActivity FlutterActivity () override fun onCreate savedInstanceState Bundle ?) // Aligns the Flutter view vertically with the window. WindowCompat setDecorFitsSystemWindows getWindow (), false if Build VERSION SDK_INT >= Build VERSION_CODES // Disable the Android splash screen fade out animation to avoid
https://docs.flutter.dev/development/platform-integration/android/splash-screen/index.html
550898503800-10
// Disable the Android splash screen fade out animation to avoid // a flicker before the similar frame is drawn in Flutter. splashScreen setOnExitAnimationListener splashScreenView > splashScreenView remove () super onCreate savedInstanceState Then, you can reimplement the first frame in Flutter that shows elements of your Android launch screen in the same positions on screen. For an example of this, check out the Android splash screen sample app.
https://docs.flutter.dev/development/platform-integration/android/splash-screen/index.html
a967309c09f6-0
Deprecated Splash Screen API Migration Platform integration Android Deprecated Splash Screen API Migration Prior to Flutter 2.5, Flutter apps could add a splash screen by defining it within the metadata of their application manifest file (AndroidManifest.xml), by implementing provideSplashScreen within their FlutterActivity, or both. This would display momentarily in between the time after the Android launch screen is shown and when Flutter has drawn the first frame. This approach is now deprecated as of Flutter 2.5. Flutter now automatically keeps the Android launch screen displayed until it draws the first frame. To migrate from defining a custom splash screen to just defining a custom launch screen for your application, follow the steps that correspond to how your application’s custom splash screen was defined prior to the 2.5 release. Custom splash screen defined in FlutterActivity
https://docs.flutter.dev/development/platform-integration/android/splash-screen-migration/index.html
a967309c09f6-1
Custom splash screen defined in FlutterActivity Locate your application’s implementation of provideSplashScreen() within its FlutterActivity and delete it. This implementation should involve the construction of your application’s custom splash screen as a Drawable. For example: @Override public SplashScreen provideSplashScreen() { // ... return new DrawableSplashScreen( new SomeDrawable( ContextCompat.getDrawable(this, R.some_splash_screen))); } Use the steps in the section directly following to ensure that your Drawable splash screen (R.some_splash_screen in the previous example) is properly configured as your application’s custom launch screen. Custom splash screen defined in Manifest
https://docs.flutter.dev/development/platform-integration/android/splash-screen-migration/index.html
a967309c09f6-2
Custom splash screen defined in Manifest Locate your application’s AndroidManifest.xml file. Within this file, find the activity element. Within this element, identify the android:theme attribute and the meta-data element that defines a splash screen as an io.flutter.embedding.android.SplashScreenDrawable, and update it. For example: <activity // ... android:theme="@style/SomeTheme"> // ... <meta-data android:name="io.flutter.embedding.android.SplashScreenDrawable" android:resource="@drawable/some_splash_screen" /> </activity> If the android:theme attribute isn’t specified, add the attribute and define a launch theme for your application’s launch screen. Delete the meta-data element, as Flutter no longer uses that, but it can cause a crash.
https://docs.flutter.dev/development/platform-integration/android/splash-screen-migration/index.html
a967309c09f6-3
Locate the definition of the theme specified by the android:theme attribute within your application’s style resources. This theme specifies the launch theme of your application. Ensure that the style attribute configures the android:windowBackground attribute with your custom splash screen. For example: <resources> <style name="SomeTheme" // ... > <!-- Show a splash screen on the activity. Automatically removed when Flutter draws its first frame --> <item name="android:windowBackground">@drawable/some_splash_screen</item> </style> </resources>
https://docs.flutter.dev/development/platform-integration/android/splash-screen-migration/index.html
5d189424b446-0
Desktop support for Flutter Platform integration Desktop support for Flutter Requirements Additional Windows requirements Additional macOS requirements Additional Linux requirements Create a new project Set up Create and run Using an IDE From the command line Build a release app Add desktop support to an existing Flutter app Plugin support Writing a plugin Samples and codelabs Flutter provides support for compiling a native Windows, macOS, or Linux desktop app. Flutter’s desktop support also extends to plugins—you can install existing plugins that support the Windows, macOS, or Linux platforms, or you can create your own. Note: This page covers developing apps for all desktop platforms. Once you’ve read this, you can dive into specific platform information at the following links:
https://docs.flutter.dev/development/platform-integration/desktop/index.html
5d189424b446-1
Building Windows apps with Flutter Building macOS apps with Flutter Building Linux apps with Flutter Requirements To compile a desktop application, you must build it on the targeted platform: build a Windows application on Windows, a macOS application on macOS, and a Linux application on Linux. To create a Flutter application with desktop support, you need the following software: Flutter SDK. See the Flutter SDK installation instructions. Optional: An IDE that supports Flutter. You can install Android Studio, IntelliJ IDEA, or Visual Studio Code and install the Flutter and Dart plugins to enable language support and tools for refactoring, running, debugging, and reloading your desktop app within an editor. See setting up an editor for more details. Additional Windows requirements For Windows desktop development, you need the following in addition to the Flutter SDK:
https://docs.flutter.dev/development/platform-integration/desktop/index.html
5d189424b446-2
For Windows desktop development, you need the following in addition to the Flutter SDK: Visual Studio 2022 or Visual Studio Build Tools 2022 When installing Visual Studio or only the Build Tools, select the “Desktop development with C++” workload, including all of its default components, to install the necessary C++ toolchain and Windows SDK header files. Note: Visual Studio is different than Visual Studio Code. Additional macOS requirements For macOS desktop development, you need the following in addition to the Flutter SDK: Xcode the full version of Xcode is required, not just the commandline tools CocoaPods if you use plugins Additional Linux requirements For Linux desktop development, you need the following in addition to the Flutter SDK: Clang CMake GTK development headers Ninja build pkg-config
https://docs.flutter.dev/development/platform-integration/desktop/index.html
5d189424b446-3
Ninja build pkg-config liblzma-dev This dependency may be required One easy way to install the Flutter SDK along with the necessary dependencies is by using snapd. For more information, see Installing snapd. Once you have snapd, you can install Flutter using the Snap Store, or at the command line: sudo snap install flutter -classic Alternatively, if you prefer not to use snapd, you can use the following command: sudo apt-get install clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev Create a new project You can use the following steps to create a new project with desktop support. Set up
https://docs.flutter.dev/development/platform-integration/desktop/index.html
5d189424b446-4
Set up On Windows, desktop support is enabled on Flutter 2.10 or higher. On macOS and Linux, desktop support is enabled on Flutter 3 or higher. You might run flutter doctor to see if there are any unresolved issues. You should see a checkmark for each successfully configured area. It should look something like the following on Windows, with an entry for “develop for Windows”: C:\> flutter doctor
https://docs.flutter.dev/development/platform-integration/desktop/index.html
5d189424b446-5
C:\> flutter doctor Doctor summary (to see all details, run flutter doctor -v): [✓] Flutter (Channel stable, 3.0.0, on Microsoft Windows [Version 10.0.19044.1706], locale en-US) [✓] Chrome - develop for the web [✓] Visual Studio - develop for Windows (Visual Studio Professional 2022 17.2.0) [✓] VS Code (version 1.67.2) [✓] Connected device (3 available) [✓] HTTP Host Availability • No issues found! On macOS, look for a line like this: [✓] Xcode - develop for iOS and macOS On Linux, look for a line like this: [✓] Linux toolchain - develop for Linux desktop
https://docs.flutter.dev/development/platform-integration/desktop/index.html
5d189424b446-6
[✓] Linux toolchain - develop for Linux desktop If flutter doctor finds problems or missing components for a platform that you don’t want to develop for, you can ignore those warnings. Or you can disable the platform altogether using the flutter config command, for example: flutter config -no-enable-ios Other available flags: --no-enable-windows-desktop --no-enable-linux-desktop --no-enable-macos-desktop --no-enable-web --no-enable-android --no-enable-ios After enabling desktop support, restart your IDE so that it can detect the new device. Create and run Creating a new project with desktop support is no different than creating a new Flutter project for other platforms.
https://docs.flutter.dev/development/platform-integration/desktop/index.html
5d189424b446-7
Once you’ve configured your environment for desktop support, you can create and run a desktop application either in the IDE or from the command line. Using an IDE After you’ve configured your environment to support desktop, make sure you restart the IDE if it was already running. Create a new application in your IDE and it automatically creates iOS, Android, web, and desktop versions of your app. From the device pulldown, select windows (desktop), macOS (desktop), or linux (desktop) and run your application to see it launch on the desktop. From the command line To create a new application that includes desktop support (in addition to mobile and web support), run the following commands, substituting my_app with the name of your project: flutter create my_app cd my_app To launch your application from the command line, enter one of the following commands from the top of the package: C:\>
https://docs.flutter.dev/development/platform-integration/desktop/index.html
5d189424b446-8
C:\> flutter run d windows flutter run d macos flutter run d linux Note: If you do not supply the -d flag, flutter run lists the available targets to choose from. Build a release app To generate a release build, run one of the following commands: PS C:\> flutter build windows flutter build macos flutter build linux Add desktop support to an existing Flutter app To add desktop support to an existing Flutter project, run the following command in a terminal from the root project directory: flutter create -platforms =windows,macos,linux
https://docs.flutter.dev/development/platform-integration/desktop/index.html
5d189424b446-9
-platforms =windows,macos,linux This adds the necessary desktop files and directories to your existing Flutter project. To add only specific desktop platforms, change the platforms list to include only the platform(s) you want to add. Plugin support Flutter on the desktop supports using and creating plugins. To use a plugin that supports desktop, follow the steps for plugins in using packages. Flutter automatically adds the necessary native code to your project, as with any other platform. Writing a plugin
https://docs.flutter.dev/development/platform-integration/desktop/index.html
5d189424b446-10
Writing a plugin When you start building your own plugins, you’ll want to keep federation in mind. Federation is the ability to define several different packages, each targeted at a different set of platforms, brought together into a single plugin for ease of use by developers. For example, the Windows implementation of the url_launcher is really url_launcher_windows, but a Flutter developer can simply add the url_launcher package to their pubspec.yaml as a dependency and the build process pulls in the correct implementation based on the target platform. Federation is handy because different teams with different expertise can build plugin implementations for different platforms. You can add a new platform implementation to any endorsed federated plugin on pub.dev, so long as you coordinate this effort with the original plugin author. For more information, including information about endorsed plugins, see the following resources: Developing packages and plugins, particularly the Federated plugins section.
https://docs.flutter.dev/development/platform-integration/desktop/index.html
5d189424b446-11
Developing packages and plugins, particularly the Federated plugins section. How to write a Flutter web plugin, part 2, covers the structure of federated plugins and contains information applicable to desktop plugins. Modern Flutter Plugin Development covers recent enhancements to Flutter’s plugin support. Samples and codelabs Write a Flutter desktop application A codelab that walks you through building a desktop application that integrates the GitHub GraphQL API with your Flutter app. You can run the following samples as desktop apps, as well as download and inspect the source code to learn more about Flutter desktop support. running web app, repo
https://docs.flutter.dev/development/platform-integration/desktop/index.html
5d189424b446-12
running web app, repo A samples project hosted on GitHub to help developers evaluate and use Flutter. The Gallery consists of a collection of Material design widgets, behaviors, and vignettes implemented with Flutter. You can clone the project and run Gallery as a desktop app by following the instructions provided in the README. announcement blogpost, repo A Google contacts manager that integrates with GitHub and Twitter. It syncs with your Google account, imports your contacts, and allows you to manage them. Photo Search app A sample application built as a desktop application that uses desktop-supported plugins.
https://docs.flutter.dev/development/platform-integration/desktop/index.html
fa9d8f126d09-0
Platform integration Platform integration Topics: Supported platforms Building desktop apps with Flutter Writing platform-specific code Android iOS Linux macOS Web Windows
https://docs.flutter.dev/development/platform-integration/index.html
33cc08dd96bb-0
Adding iOS app extensions Platform integration iOS Adding iOS app extensions How do you add an app extension to your Flutter app? How do Flutter apps interact with App Extensions? Using higher-level APIs Sharing resources Background updates Deep linking Creating app extension UIs with Flutter iOS App extensions allow you to expand functionality outside your app. Your app could appear as a home screen widget, or you can make portions of your app available within other apps. To learn more about app extensions, check out Apple’s documentation. How do you add an app extension to your Flutter app? To add an app extension to your Flutter app, add the extension point target to your Xcode project. Open the default Xcode workspace in your project by running open ios/Runner.xcworkspace in a terminal window from your Flutter project directory.
https://docs.flutter.dev/development/platform-integration/ios/app-extensions/index.html