id
stringlengths
14
17
text
stringlengths
23
1.11k
source
stringlengths
35
114
0fb8076e2896-10
Be lazy! When building a large grid or list, use the lazy builder methods, with callbacks. That ensures that only the visible portion of the screen is built at startup time. For more information and examples, check out: Working with long lists in the Cookbook Creating a ListView that loads one page at a time a community article by AbdulRahman AlHamali Listview.builder API Avoid intrinsics For information on how intrinsic passes might be causing problems with your grids and lists, see the next section. Minimize layout passes caused by intrinsic operations If you’ve done much Flutter programming, you are probably familiar with how layout and constraints work when creating your UI. You might even have memorized Flutter’s basic layout rule: Constraints go down. Sizes go up. Parent sets position.
https://docs.flutter.dev/perf/best-practices/index.html
0fb8076e2896-11
For some widgets, particularly grids and lists, the layout process can be expensive. Flutter strives to perform just one layout pass over the widgets but, sometimes, a second pass (called an intrinsic pass) is needed, and that can slow performance. What is an intrinsic pass? An intrinsic pass happens when, for example, you want all cells to have the size of the biggest or smallest cell (or some similar calculation that requires polling all cells). For example, consider a large grid of Cards. A grid should have uniformly sized cells, so the layout code performs a pass, starting from the root of the grid (in the widget tree), asking each card in the grid (not just the visible cards) to return its intrinsic size—the size that the widget prefers, assuming no constraints. With this information, the framework determines a uniform cell size, and re-visits all grid cells a second time, telling each card what size to use.
https://docs.flutter.dev/perf/best-practices/index.html
0fb8076e2896-12
Debugging intrinsic passes To determine whether you have excessive intrinsic passes, enable the Track layouts option in DevTools (disabled by default), and look at the app’s stack trace to learn how many layout passes were performed. Once you enable tracking, intrinsic timeline events are labeled as ‘$runtimeType intrinsics’. Avoiding intrinsic passes You have a couple options for avoiding the intrinsic pass: Set the cells to a fixed size up front. Choose a particular cell to be the “anchor” cell—all cells will be sized relative to this cell. Write a custom render object that positions the child anchor first and then lays out the other children around it. To dive even deeper into how layout works, check out the layout and rendering section in the Flutter architectural overview. Build and display frames in 16ms
https://docs.flutter.dev/perf/best-practices/index.html
0fb8076e2896-13
Build and display frames in 16ms Since there are two separate threads for building and rendering, you have 16ms for building, and 16ms for rendering on a 60Hz display. If latency is a concern, build and display a frame in 16ms or less. Note that means built in 8ms or less, and rendered in 8ms or less, for a total of 16ms or less. If your frames are rendering in well under 16ms total in profile mode, you likely don’t have to worry about performance even if some performance pitfalls apply, but you should still aim to build and render a frame as fast as possible. Why? Lowering the frame render time below 16ms might not make a visual difference, but it improves battery life and thermal issues. It might run fine on your device, but consider performance for the lowest device you are targeting.
https://docs.flutter.dev/perf/best-practices/index.html
0fb8076e2896-14
As 120fps devices become more widely available, you’ll want to render frames in under 8ms (total) in order to provide the smoothest experience. If you are wondering why 60fps leads to a smooth visual experience, check out the video Why 60fps? Pitfalls If you need to tune your app’s performance, or perhaps the UI isn’t as smooth as you expect, the DevTools Performance view can help! Also, the Flutter plugin for your IDE might be useful. In the Flutter Performance window, enable the Show widget rebuild information check box. This feature helps you detect when frames are being rendered and displayed in more than 16ms. Where possible, the plugin provides a link to a relevant tip. The following behaviors might negatively impact your app’s performance.
https://docs.flutter.dev/perf/best-practices/index.html
0fb8076e2896-15
The following behaviors might negatively impact your app’s performance. Avoid using the Opacity widget, and particularly avoid it in an animation. Use AnimatedOpacity or FadeInImage instead. For more information, check out Performance considerations for opacity animation. When using an AnimatedBuilder, avoid putting a subtree in the builder function that builds widgets that don’t depend on the animation. This subtree is rebuilt for every tick of the animation. Instead, build that part of the subtree once and pass it as a child to the AnimatedBuilder. For more information, check out Performance optimizations. Avoid clipping in an animation. If possible, pre-clip the image before animating it. Avoid using constructors with a concrete List of children (such as Column() or ListView()) if most of the children are not visible on screen to avoid the build cost.
https://docs.flutter.dev/perf/best-practices/index.html
0fb8076e2896-16
Avoid overriding operator == on Widget objects. While it may seem like it would help by avoiding unnecessary rebuilds, in practice it hurts performance because it results in O(N²) behavior. The only exception to this rule is leaf widgets (widgets with no children), in the specific case where comparing the properties of the widget is likely to be significantly more efficient than rebuilding the widget and where the widget will rarely change configuration. Even in such cases, it is generally preferable to rely on caching the widgets, because even one override of operator == can result in across-the-board performance degradation as the compiler can no longer assume that the call is always static. Resources For more performance info, check out the following resources: Performance optimizations in the AnimatedBuilder API page Performance considerations for opacity animation in the Opacity API page Child elements’ lifecycle and how to load them efficiently, in the ListView API page Performance considerations of a StatefulWidget
https://docs.flutter.dev/perf/best-practices/index.html
cc3aff03dddb-0
Deferred components Introduction How to set your project up for deferred components Step 1: Dependencies and initial project setup Step 2: Implementing deferred Dart libraries Step 3: Building the app Running the app locally Releasing to the Google Play store Introduction Flutter has the capability to build apps that can download additional Dart code and assets at runtime. This allows apps to reduce install apk size and download features and assets when needed by the user. We refer to each uniquely downloadable bundle of Dart libraries and assets as a “deferred component”. This is achieved by using Dart’s deferred imports, which can be compiled into split AOT shared libraries.
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-1
Note: This feature is currently only available on Android, taking advantage of Android and Google Play Stores’ dynamic feature modules to deliver the deferred components packaged as Android modules. Deferred code does not impact other platforms, which continue to build as normal with all deferred components and assets included at initial install time. Also, note that this is an advanced feature. Though modules can be defer loaded, the entire application must be completely built and uploaded as a single Android App Bundle. Dispatching partial updates without re-uploading new Android App Bundles for the entire application is not supported. Deferred loading is only performed when the app is compiled to release or profile mode. In debug mode, all deferred components are treated as regular imports, so they are present at launch and load immediately. Therefore, debug builds can still hot reload. For a deeper dive into the technical details of how this feature works, see Deferred Components on the Flutter wiki.
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-2
How to set your project up for deferred components The following instructions explain how to set up your Android app for deferred loading. Step 1: Dependencies and initial project setup Add Play Core to the Android app’s build.gradle dependencies. In android/app/build.gradle add the following: ... dependencies { ... implementation "com.google.android.play:core:1.8.0" ... } If using the Google Play Store as the distribution model for dynamic features, the app must support SplitCompat and provide an instance of a PlayStoreDeferredComponentManager. Both of these tasks can be accomplished by setting the android:name property on the application in android/app/src/main/AndroidManifest.xml to io.flutter.embedding.android.FlutterPlayStoreSplitApplication:
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-3
<manifest ... <application android:name="io.flutter.embedding.android.FlutterPlayStoreSplitApplication" ... </application> </manifest> io.flutter.app.FlutterPlayStoreSplitApplication handles both of these tasks for you. If you use FlutterPlayStoreSplitApplication, you can skip to step 1.3. If your Android application is large or complex, you might want to separately support SplitCompat and provide the PlayStoreDynamicFeatureManager manually. To support SplitCompat, there are three methods (as detailed in the Android docs), any of which are valid: Make your application class extend SplitCompatApplication: public class MyApplication extends SplitCompatApplication { ... } Call SplitCompat.install(this); in the attachBaseContext() method:
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-4
@Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); // Emulates installation of future on demand modules using SplitCompat. SplitCompat.install(this); } Declare SplitCompatApplication as the application subclass and add the Flutter compatibility code from FlutterApplication to your application class: <application ... android:name="com.google.android.play.core.splitcompat.SplitCompatApplication"> </application> The embedder relies on an injected DeferredComponentManager instance to handle install requests for deferred components. Provide a PlayStoreDeferredComponentManager into the Flutter embedder by adding the following code to your app initialization:
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-5
import io.flutter.embedding.engine.dynamicfeatures.PlayStoreDeferredComponentManager; import io.flutter.FlutterInjector; ... PlayStoreDeferredComponentManager deferredComponentManager = new PlayStoreDeferredComponentManager(this, null); FlutterInjector.setInstance(new FlutterInjector.Builder() .setDeferredComponentManager(deferredComponentManager).build()); Opt into deferred components by adding the deferred-components entry to the app’s pubspec.yaml under the flutter entry:
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-6
... flutter: ... deferred-components: ... The flutter tool looks for the deferred-components entry in the pubspec.yaml to determine whether the app should be built as deferred or not. This can be left empty for now unless you already know the components desired and the Dart deferred libraries that go into each. You will fill in this section later in step 3.3 once gen_snapshot produces the loading units. Step 2: Implementing deferred Dart libraries Next, implement deferred loaded Dart libraries in your app’s Dart code. The implementation does not need to be feature complete yet. The example in the rest of this page adds a new simple deferred widget as a placeholder. You can also convert existing code to be deferred by modifying the imports and guarding usages of deferred code behind loadLibrary() Futures.
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-7
Create a new Dart library. For example, create a new DeferredBox widget that can be downloaded at runtime. This widget can be of any complexity but, for the purposes of this guide, create a simple box as a stand-in. To create a simple blue box widget, create box.dart with the following contents: // box.dart import 'package:flutter/material.dart'; /// A simple blue 30x30 box. class DeferredBox extends StatelessWidget { const DeferredBox({super.key}); @override Widget build(BuildContext context) { return Container( height: 30, width: 30, color: Colors.blue, ); } }
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-8
Import the new Dart library with the deferred keyword in your app and call loadLibrary() (see lazily loading a library). The following example uses FutureBuilder to wait for the loadLibrary Future (created in initState) to complete and display a CircularProgressIndicator as a placeholder. When the Future completes, it returns the DeferredBox widget. SomeWidget can then be used in the app as normal and won’t ever attempt to access the deferred Dart code until it has successfully loaded. import 'package:flutter/material.dart'; import 'box.dart' deferred as box; class SomeWidget extends StatefulWidget { const SomeWidget({super.key}); @override State<SomeWidget> createState() => _SomeWidgetState(); } class _SomeWidgetState extends State<SomeWidget> { late Future<void> _libraryFuture;
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-9
@override void initState() { _libraryFuture = box.loadLibrary(); super.initState(); } @override Widget build(BuildContext context) { return FutureBuilder<void>( future: _libraryFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } return box.DeferredBox(); } return const CircularProgressIndicator(); }, ); } }
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-10
The loadLibrary() function returns a Future<void> that completes successfully when the code in the library is available for use and completes with an error otherwise. All usage of symbols from the deferred library should be guarded behind a completed loadLibrary() call. All imports of the library must be marked as deferred for it to be compiled appropriately to be used in a deferred component. If a component has already been loaded, additional calls to loadLibrary() complete quickly (but not synchronously). The loadLibrary() function can also be called early to trigger a pre-load to help mask the loading time. You can find another example of deferred import loading in Flutter Gallery’s lib/deferred_widget.dart. Step 3: Building the app Use the following flutter command to build a deferred components app: flutter build appbundle
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-11
flutter build appbundle This command assists you by validating that your project is properly set up to build deferred components apps. By default, the build fails if the validator detects any issues and guides you through suggested changes to fix them. The flutter build appbundle command runs the validator and attempts to build the app with gen_snapshot instructed to produce split AOT shared libraries as separate .so files. On the first run, the validator will likely fail as it detects issues; the tool makes recommendations for how to set up the project and fix these issues. The validator is split into two sections: prebuild and post-gen_snapshot validation. This is because any validation referencing loading units cannot be performed until gen_snapshot completes and produces a final set of loading units.
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-12
Note: You can opt to have the tool attempt to build your app without the validator by passing the --no-validate-deferred-components flag. This can result in unexpected and confusing instructions to resolve failures. This flag is meant to be used in custom implementations that do not rely on the default Play-store-based implementation that the validator checks for. The validator detects any new, changed, or removed loading units generated by gen_snapshot. The current generated loading units are tracked in your <projectDirectory>/deferred_components_loading_units.yaml file. This file should be checked into source control to ensure that changes to the loading units by other developers can be caught. The validator also checks for the following in the android directory:
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-13
<projectDir>/android/app/src/main/res/values/strings.xml An entry for every deferred component mapping the key ${componentName}Name to ${componentName}. This string resource is used by the AndroidManifest.xml of each feature module to define the dist:title property. For example: <?xml version="1.0" encoding="utf-8"?> <resources> ... <string name="boxComponentName">boxComponent</string> </resources> <projectDir>/android/<componentName> An Android dynamic feature module for each deferred component exists and contains a build.gradle and src/main/AndroidManifest.xml file. This only checks for existence and does not validate the contents of these files. If a file does not exist, it generates a default recommended one.
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-14
<projectDir>/android/app/src/main/res/values/AndroidManifest.xml Contains a meta-data entry that encodes the mapping between loading units and component name the loading unit is associated with. This mapping is used by the embedder to convert Dart’s internal loading unit id to the name of a deferred component to install. For example: ... <application android:label="MyApp" android:name="io.flutter.app.FlutterPlayStoreSplitApplication" android:icon="@mipmap/ic_launcher"> ... <meta-data android:name="io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager.loadingUnitMapping" android:value="2:boxComponent"/> </application> ... The gen_snapshot validator won’t run until the prebuild validator passes.
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-15
For each of these checks, the tool produces the modified or new files needed to pass the check. These files are placed in the <projectDir>/build/android_deferred_components_setup_files directory. It is recommended that the changes be applied by copying and overwriting the same files in the project’s android directory. Before overwriting, the current project state should be committed to source control and the recommended changes should be reviewed to be appropriate. The tool won’t make any changes to your android/ directory automatically.
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-16
Once the available loading units are generated and logged in <projectDirectory>/deferred_components_loading_units.yaml, it is possible to fully configure the pubspec’s deferred-components section so that the loading units are assigned to deferred components as desired. To continue with the box example, the generated deferred_components_loading_units.yaml file would contain: loading-units: - id: 2 libraries: - package:MyAppName/box.Dart The loading unit id (‘2’ in this case) is used internally by Dart, and can be ignored. The base loading unit (id ‘1’) is not listed and contains everything not explicitly contained in another loading unit. You can now add the following to pubspec.yaml:
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-17
You can now add the following to pubspec.yaml: ... flutter: ... deferred-components: - name: boxComponent libraries: - package:MyAppName/box.Dart ... To assign a loading unit to a deferred component, add any Dart lib in the loading unit into the libraries section of the feature module. Keep the following guidelines in mind: Loading units should not be included in more than one component. Including one Dart library from a loading unit indicates that the entire loading unit is assigned to the deferred component. All loading units not assigned to a deferred component are included in the base component, which always exists implicitly. Loading units assigned to the same deferred component are downloaded, installed, and shipped together.
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-18
The base component is implicit and need not be defined in the pubspec. Assets can also be included by adding an assets section in the deferred component configuration: deferred-components: - name: boxComponent libraries: - package:MyAppName/box.Dart assets: - assets/image.jpg - assets/picture.png # wildcard directory - assets/gallery/ An asset can be included in multiple deferred components, but installing both components results in a replicated asset. Assets-only components can also be defined by omitting the libraries section. These assets-only components must be installed with the DeferredComponent utility class in services rather than loadLibrary(). Since Dart libs are packaged together with assets, if a Dart library is loaded with loadLibrary(), any assets in the component are loaded as well. However, installing by component name and the services utility won’t load any dart libraries in the component.
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-19
You are free to include assets in any component, as long as they are installed and loaded when they are first referenced, though typically, assets and the Dart code that uses those assets are best packed in the same component. Manually add all deferred components that you defined in pubspec.yaml into the android/settings.gradle file as includes. For example, if there are three deferred components defined in the pubspec named, boxComponent, circleComponent, and assetComponent, ensure that android/settings.gradle contains the following: include ':app', ':boxComponent', ':circleComponent', ':assetComponent' ... Repeat steps 3.1 through 3.6 (this step) until all validator recommendations are handled and the tool runs without further recommendations. When successful, this command outputs an app-release.aab file in build/app/outputs/bundle/release.
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-20
A successful build does not always mean the app was built as intended. It is up to you to ensure that all loading units and Dart libraries are included in the way you intended. For example, a common mistake is accidentally importing a Dart library without the deferred keyword, resulting in a deferred library being compiled as part of the base loading unit. In this case, the Dart lib would load properly because it is always present in the base, and the lib would not be split off. This can be checked by examining the deferred_components_loading_units.yaml file to verify that the generated loading units are described as intended. When adjusting the deferred components configurations, or making Dart changes that add, modify, or remove loading units, you should expect the validator to fail. Follow steps 3.1 through 3.6 (this step) to apply any recommended changes to continue the build. Running the app locally
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-21
Running the app locally Once your app has successfully built an .aab file, use Android’s bundletool to perform local testing with the --local-testing flag. To run the .aab file on a test device, download the bundletool jar executable from github.com/google/bundletool/releases and run: java jar bundletool.jar build-apks -bundle =<your_app_project_dir>/build/app/outputs/bundle/release/app-release.aab -output =<your_temp_dir>/app.apks -local-testing java jar bundletool.jar install-apks -apks =<your_temp_dir>/app.apks
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-22
=<your_temp_dir>/app.apks Where <your_app_project_dir> is the path to your app’s project directory and <your_temp_dir> is any temporary directory used to store the outputs of bundletool. This unpacks your .aab file into an .apks file and installs it on the device. All available Android dynamic features are loaded onto the device locally and installation of deferred components is emulated. Before running build-apks again, remove the existing app .apks file: rm <your_temp_dir>/app.apks Changes to the Dart codebase require either incrementing the Android build ID or uninstalling and reinstalling the app, as Android won’t update the feature modules unless it detects a new version number. Releasing to the Google Play store
https://docs.flutter.dev/perf/deferred-components/index.html
cc3aff03dddb-23
Releasing to the Google Play store The built .aab file can be uploaded directly to the Play store as normal. When loadLibrary() is called, the needed Android module containing the Dart AOT lib and assets is downloaded by the Flutter engine using the Play store’s delivery feature.
https://docs.flutter.dev/perf/deferred-components/index.html
db48ded20c08-0
Performance FAQ This page collects some frequently asked questions about evaluating and debugging Flutter’s performance. Which performance dashboards have metrics that are related to Flutter? Flutter dashboard on appspot Flutter Skia dashboard Flutter Engine Skia dashboard How do I add a benchmark to Flutter? How to write a render speed test for Flutter How to write a memory test for Flutter What are some tools for capturing and analyzing performance metrics? Dart DevTools Apple instruments Linux perf Chrome tracing (enter about:tracing in your Chrome URL field) Android systrace (adb systrace) Fuchsia fx traceutil Perfetto speedscope My Flutter app looks janky or stutters. How do I fix it? Improving rendering performance
https://docs.flutter.dev/perf/faq/index.html
db48ded20c08-1
What are some costly performance operations that I need to be careful with? Opacity, Clip.antiAliasWithSaveLayer, or anything that triggers saveLayer ImageFilter Also see Performance best practices How do I tell which widgets in my Flutter app are rebuilt in each frame? Set debugProfileBuildsEnabled true in widgets/debug.dart. Alternatively, change the performRebuild function in widgets/framework.dart to ignore debugProfileBuildsEnabled and always call Timeline.startSync(...)/finish. If you use IntelliJ, a GUI view of this data is available. Select show widget rebuild information, and you’ll visually see which widgets rebuild visually in your IDE. How do I query the target frames per second (of the display)? Get the display refresh rate
https://docs.flutter.dev/perf/faq/index.html
db48ded20c08-2
How to solve my app’s poor animations caused by an expensive Dart async function call that is blocking the UI thread? Spawn another isolate using the compute() method, as demonstrated in Parse JSON in the background cookbook. How do I determine my Flutter app’s package size that a user will download? See Measuring your app’s size How do I see the breakdown of the Flutter engine size? Visit the binary size dashboard, and replace the git hash in the URL with a recent commit hash from GitHub engine repository commits. How can I take a screenshot of an app that is running and export it as a SKP file? Run flutter screenshot --type=skia --observatory-uri=...
https://docs.flutter.dev/perf/faq/index.html
db48ded20c08-3
Note a known issue viewing screenshots: Issue 21237: Doesn’t record images in real devices. To analyze and visualize the SKP file, check out the Skia WASM debugger. How do I retrieve the shader persistent cache from a device? On Android, you can do the following: adb shell run-as <com.your_app_package_name> cp <your_folder> <some_public_folder, e.g., /sdcard> -r adb pull <some_public_folder/your_folder> How do I perform a trace in Fuchsia? See Fuchsia tracing guidelines
https://docs.flutter.dev/perf/faq/index.html
af3b0355cdba-0
Performance Speed App size Flutter performance basics Note: If your app has a performance issue and you are trying to debug it, check out the DevTool’s page on Using the Performance view. What is performance? Why is performance important? How do I improve performance? Our goal is to answer those three questions (mainly the third one), and anything related to them. This document should serve as the single entry point or the root node of a tree of resources that addresses any questions that you have about performance. The answers to the first two questions are mostly philosophical, and not as helpful to many developers who visit this page with specific performance issues that need to be solved. Therefore, the answers to those questions are in the appendix.
https://docs.flutter.dev/perf/index.html
af3b0355cdba-1
To improve performance, you first need metrics: some measurable numbers to verify the problems and improvements. In the metrics page, you’ll see which metrics are currently used, and which tools and APIs are available to get the metrics. There is a list of Frequently asked questions, so you can find out if the questions you have or the problems you’re having were already answered or encountered, and whether there are existing solutions. (Alternatively, you can check the Flutter GitHub issue database using the performance label.) Finally, the performance issues are divided into four categories. They correspond to the four labels that are used in the Flutter GitHub issue database: “perf: speed”, “perf: memory”, “perf: app size”, “perf: energy”. The rest of the content is organized using those four categories. Speed Are your animations janky (not smooth)? Learn how to evaluate and fix rendering issues.
https://docs.flutter.dev/perf/index.html
af3b0355cdba-2
Improving rendering performance App size How to measure your app’s size. The smaller the size, the quicker it is to download. Measuring your app’s size
https://docs.flutter.dev/perf/index.html
649ebffc85fc-0
Performance metrics Startup time to the first frame Check the time when WidgetsBinding.instance.firstFrameRasterized is true. See the perf dashboard. Frame buildDuration, rasterDuration, and totalSpan See FrameTiming in the API docs. Statistics of frame buildDuration (*_frame_build_time_millis) We recommend monitoring four stats: average, 90th percentile, 99th percentile, and worst frame build time. See, for example, metrics for the flutter_gallery__transition_perf test. Statistics of frame rasterDuration (*_frame_build_time_millis) We recommend monitoring four stats: average, 90th percentile, 99th percentile, and worst frame build time. See, for example, metrics for the flutter_gallery__transition_perf test.
https://docs.flutter.dev/perf/metrics/index.html
649ebffc85fc-1
CPU/GPU usage (a good approximation for energy use) The usage is currently only available through trace events. See profiling_summarizer.dart. See metrics for the simple_animation_perf_ios test. release_size_bytes to approximately measure the size of a Flutter app See the basic_material_app_android, basic_material_app_ios, hello_world_android, hello_world_ios, flutter_gallery_android, and flutter_gallery_ios tests. See metrics in the dashboard. For info on how to measure the size more accurately, see the app size page. For a complete list of performance metrics Flutter measures per commit, visit the following sites, click Query, and filter the test and sub_result fields: https://flutter-flutter-perf.skia.org/e/ https://flutter-engine-perf.skia.org/e/
https://docs.flutter.dev/perf/metrics/index.html
21918055df86-0
Improving rendering performance General advice Mobile-only advice Web-only advice Note: To learn how to use the Performance View (part of Flutter DevTools) for debugging performance issues, see Using the Performance view. Rendering animations in your app is one of the most cited topics of interest when it comes to measuring performance. Thanks in part to Flutter’s Skia engine and its ability to quickly create and dispose of widgets, Flutter applications are performant by default, so you only need to avoid common pitfalls to achieve excellent performance. General advice If you see janky (non smooth) animations, make sure that you are profiling performance with an app built in profile mode. The default Flutter build creates an app in debug mode, which is not indicative of release performance. For information, see Flutter’s build modes. A couple common pitfalls:
https://docs.flutter.dev/perf/rendering-performance/index.html
21918055df86-1
A couple common pitfalls: Rebuilding far more of the UI than expected each frame. To track widget rebuilds, see Show performance data. Building a large list of children directly, rather than using a ListView. For more information on evaluating performance including information on common pitfalls, see the following docs: Performance best practices Flutter performance profiling Mobile-only advice Do you see noticeable jank on your mobile app, but only on the first run of an animation? If so, see Reduce shader animation jank on mobile. Web-only advice The following series of articles cover what the Flutter Material team learned when improving performance of the Flutter Gallery app on the web: Optimizing performance in Flutter web apps with tree shaking and deferred loading Improving perceived performance with image placeholders, precaching, and disabled navigation transitions
https://docs.flutter.dev/perf/rendering-performance/index.html
21918055df86-2
Building performant Flutter widgets
https://docs.flutter.dev/perf/rendering-performance/index.html
57d891cff6e7-0
Shader compilation jank What is shader compilation jank? What do we mean by “first run”? How to use SkSL warmup Note: To learn how to use the Performance View (part of Flutter DevTools) for debugging performance issues, see Using the Performance view. If the animations on your mobile app appear to be janky, but only on the first run, this is likely due to shader compilation. Flutter’s long term solution to shader compilation jank is Impeller, which is in preview (behind a flag) for iOS. (It’s not yet available on Android.) Before continuing with the instructions below, please try Impeller on iOS, and let us know in a GitHub issue if it doesn’t address your issue. Impeller on Android is being actively developed, but is not yet in developer preview.
https://docs.flutter.dev/perf/shader/index.html
57d891cff6e7-1
While we work on making Impeller production ready, you can mitigate shader compilation jank by bundling precompiled shaders with an iOS app. Unfortunately, this approach doesn’t work well on Android due to precompiled shaders being device or GPU-specific. The Android hardware ecosystem is large enough that the GPU-specific precompiled shaders bundled with an application will work on only a small subset of devices, and will likely make jank worse on the other devices, or even create rendering errors. Also, please note that we aren’t planning to make improvements to the developer experience for creating precompiled shaders described below. Instead, we are focusing our energies on the more robust solution to this problem that Impeller offers. What is shader compilation jank?
https://docs.flutter.dev/perf/shader/index.html
57d891cff6e7-2
What is shader compilation jank? A shader is a piece of code that runs on a GPU (graphics processing unit). When the Skia graphics backend that Flutter uses for rendering sees a new sequence of draw commands for the first time, it sometimes generates and compiles a custom GPU shader for that sequence of commands. This allows that sequence and potentially similar sequences to render as fast as possible. Unfortunately, Skia’s shader generation and compilation happen in sequence with the frame workload. The compilation could cost up to a few hundred milliseconds whereas a smooth frame needs to be drawn within 16 milliseconds for a 60 fps (frame-per-second) display. Therefore, a compilation could cause tens of frames to be missed, and drop the fps from 60 to 6. This is compilation jank. After the compilation is complete, the animation should be smooth.
https://docs.flutter.dev/perf/shader/index.html
57d891cff6e7-3
On the other hand, Impeller generates and compiles all necessary shaders when we build the Flutter Engine. Therefore apps running on Impeller already have all the shaders they need, and the shaders can be used without introducing jank into animations. Definitive evidence for the presence of shader compilation jank is to see GrGLProgramBuilder::finalize in the tracing with --trace-skia enabled. See the following screenshot for an example timeline tracing. What do we mean by “first run”? On iOS, “first run” means that the user might see jank when an animation first occurs every time the user opens the app from scratch. How to use SkSL warmup
https://docs.flutter.dev/perf/shader/index.html
57d891cff6e7-4
How to use SkSL warmup As of release 1.20, Flutter provides command line tools for app developers to collect shaders that might be needed for end-users in the SkSL (Skia Shader Language) format. The SkSL shaders can then be packaged into the app, and get warmed up (pre-compiled) when an end-user first opens the app, thereby reducing the compilation jank in later animations. Use the following instructions to collect and package the SkSL shaders: Run the app with --cache-sksl turned on to capture shaders in SkSL: flutter run --profile --cache-sksl If the same app has been previously run without --cache-sksl, then the --purge-persistent-cache flag may be needed: flutter run --profile --cache-sksl --purge-persistent-cache
https://docs.flutter.dev/perf/shader/index.html
57d891cff6e7-5
This flag removes older non-SkSL shader caches that could interfere with SkSL shader capturing. It also purges the SkSL shaders so use it only on the first --cache-sksl run. Play with the app to trigger as many animations as needed; particularly those with compilation jank. Press M at the command line of flutter run to write the captured SkSL shaders into a file named something like flutter_01.sksl.json. For best results, capture SkSL shaders on an actual iOS device. A shader captured on a simulator isn’t likely to work correctly on actual hardware. Build the app with SkSL warm-up using the following, as appropriate: flutter build ios --bundle-sksl-path flutter_01.sksl.json
https://docs.flutter.dev/perf/shader/index.html
57d891cff6e7-6
If it’s built for a driver test like test_driver/app.dart, make sure to also specify --target=test_driver/app.dart (for example, flutter build ios --bundle-sksl-path flutter_01.sksl.json --target=test_driver/app.dart). Test the newly built app. Alternatively, you can write some integration tests to automate the first three steps using a single command. For example: flutter drive --profile --cache-sksl --write-sksl-on-exit flutter_01.sksl.json -t test_driver/app.dart
https://docs.flutter.dev/perf/shader/index.html
57d891cff6e7-7
With such integration tests, you can easily and reliably get the new SkSLs when the app code changes, or when Flutter upgrades. Such tests can also be used to verify the performance change before and after the SkSL warm-up. Even better, you can put those tests into a CI (continuous integration) system so the SkSLs are generated and tested automatically over the lifetime of an app. Note: The integration_test package is now the recommended way to write integration tests. See the Integration testing page for details. Take the original version of Flutter Gallery as an example. The CI system is set up to generate SkSLs for every Flutter commit, and verifies the performance, in the transitions_perf_test.dart test. For more details, see the flutter_gallery_sksl_warmup__transition_perf and flutter_gallery_sksl_warmup__transition_perf_e2e_ios32 tasks.
https://docs.flutter.dev/perf/shader/index.html
57d891cff6e7-8
The worst frame rasterization time is a nice metric from such integration tests to indicate the severity of shader compilation jank. For instance, the steps above reduce Flutter gallery’s shader compilation jank and speeds up its worst frame rasterization time on a Moto G4 from ~90 ms to ~40 ms. On iPhone 4s, it’s reduced from ~300 ms to ~80 ms. That leads to the visual difference as illustrated in the beginning of this article.
https://docs.flutter.dev/perf/shader/index.html
36c691888548-0
Flutter performance profiling Diagnosing performance problems Connect to a physical device Run in profile mode Launch DevTools The performance overlay Interpreting the graphs Flutter’s threads Displaying the performance overlay Using the Flutter inspector From the command line Programmatically Identifying problems in the UI graph Identifying problems in the GPU graph Checking for offscreen layers Checking for non-cached images Viewing the widget rebuild profiler Benchmarking Other resources Note: To learn how to use the Performance View (part of Flutter DevTools) for debugging performance issues, see Using the Performance view. What you’ll learn
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-1
What you’ll learn Flutter aims to provide 60 frames per second (fps) performance, or 120 fps performance on devices capable of 120Hz updates. For 60fps, frames need to render approximately every 16ms. Jank occurs when the UI doesn’t render smoothly. For example, every so often, a frame takes 10 times longer to render, so it gets dropped, and the animation visibly jerks. It’s been said that “a fast app is great, but a smooth app is even better.” If your app isn’t rendering smoothly, how do you fix it? Where do you begin? This guide shows you where to start, steps to take, and tools that can help. Note:
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-2
Note: An app’s performance is determined by more than one measure. Performance sometimes refers to raw speed, but also to the UI’s smoothness and lack of stutter. Other examples of performance include I/O or network speed. This page primarily focuses on the second type of performance (UI smoothness), but you can use most of the same tools to diagnose other performance problems. To perform tracing inside your Dart code, see Tracing Dart code in the Debugging page. Diagnosing performance problems To diagnose an app with performance problems, you’ll enable the performance overlay to look at the UI and raster threads. (The raster thread was previously known as the GPU thread.) Before you begin, you want to make sure that you’re running in profile mode, and that you’re not using an emulator. For best results, you might choose the slowest device that your users might use. Connect to a physical device
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-3
Connect to a physical device Almost all performance debugging for Flutter applications should be conducted on a physical Android or iOS device, with your Flutter application running in profile mode. Using debug mode, or running apps on simulators or emulators, is generally not indicative of the final behavior of release mode builds. You should consider checking performance on the slowest device that your users might reasonably use. Why you should run on a real device: Simulators and emulators don’t use the same hardware, so their performance characteristics are different—some operations are faster on simulators than real devices, and some are slower. Debug mode enables additional checks (such as asserts) that don’t run in profile or release builds, and these checks can be expensive.
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-4
Debug mode also executes code in a different way than release mode. The debug build compiles the Dart code “just in time” (JIT) as the app runs, but profile and release builds are pre-compiled to native instructions (also called “ahead of time”, or AOT) before the app is loaded onto the device. JIT can cause the app to pause for JIT compilation, which itself can cause jank. Run in profile mode Flutter’s profile mode compiles and launches your application almost identically to release mode, but with just enough additional functionality to allow debugging performance problems. For example, profile mode provides tracing information to the profiling tools. Note: DevTools can’t connect to a Flutter web app running in profile mode. Use Chrome DevTools to generate timeline events for a web app. Launch the app in profile mode as follows:
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-5
Launch the app in profile mode as follows: In VS Code, open your launch.json file, and set the flutterMode property to profile (when done profiling, change it back to release or debug): "configurations": [ { "name": "Flutter", "request": "launch", "type": "dart", "flutterMode": "profile" } ] In Android Studio and IntelliJ, use the Run > Flutter Run main.dart in Profile Mode menu item. From the command line, use the --profile flag: $ flutter run --profile For more information on the different modes, see Flutter’s build modes. You’ll begin by opening DevTools and viewing the performance overlay, as discussed in the next section. Launch DevTools
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-6
Launch DevTools DevTools provides features like profiling, examining the heap, displaying code coverage, enabling the performance overlay, and a step-by-step debugger. DevTools’ Timeline view allows you to investigate the UI performance of your application on a frame-by-frame basis. Once your app is running in profile mode, launch DevTools. The performance overlay The performance overlay displays statistics in two graphs that show where time is being spent in your app. If the UI is janky (skipping frames), these graphs help you figure out why. The graphs display on top of your running app, but they aren’t drawn like a normal widget—the Flutter engine itself paints the overlay and only minimally impacts performance. Each graph represents the last 300 frames for that thread. This section describes how to enable the performance overlay and use it to diagnose the cause of jank in your application. The following screenshot shows the performance overlay running on the Flutter Gallery example:
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-7
Performance overlay showing the raster thread (top), and UI thread (bottom).The vertical green bars represent the current frame. Interpreting the graphs The top graph (marked “GPU”) shows the time spent by the raster thread, the bottom one graph shows the time spent by the UI thread. The white lines across the graphs show 16ms increments along the vertical axis; if the graph ever goes over one of these lines then you are running at less than 60Hz. The horizontal axis represents frames. The graph is only updated when your application paints, so if it’s idle the graph stops moving. The overlay should always be viewed in profile mode, since debug mode performance is intentionally sacrificed in exchange for expensive asserts that are intended to aid development, and thus the results are misleading.
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-8
Each frame should be created and displayed within 1/60th of a second (approximately 16ms). A frame exceeding this limit (in either graph) fails to display, resulting in jank, and a vertical red bar appears in one or both of the graphs. If a red bar appears in the UI graph, the Dart code is too expensive. If a red vertical bar appears in the GPU graph, the scene is too complicated to render quickly. The vertical red bars indicate that the current frame is expensive to both render and paint.When both graphs display red, start by diagnosing the UI thread. Flutter’s threads Flutter uses several threads to do its work, though only two of the threads are shown in the overlay. All of your Dart code runs on the UI thread. Although you have no direct access to any other thread, your actions on the UI thread have performance consequences on other threads.
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-9
The platform’s main thread. Plugin code runs here. For more information, see the UIKit documentation for iOS, or the MainThread documentation for Android. This thread is not shown in the performance overlay. The UI thread executes Dart code in the Dart VM. This thread includes code that you wrote, and code executed by Flutter’s framework on your app’s behalf. When your app creates and displays a scene, the UI thread creates a layer tree, a lightweight object containing device-agnostic painting commands, and sends the layer tree to the raster thread to be rendered on the device. Don’t block this thread! Shown in the bottom row of the performance overlay.
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-10
The raster thread takes the layer tree and displays it by talking to the GPU (graphic processing unit). You cannot directly access the raster thread or its data but, if this thread is slow, it’s a result of something you’ve done in the Dart code. Skia, the graphics library, runs on this thread. Shown in the top row of the performance overlay. This thread was previously known as the “GPU thread” because it rasterizes for the GPU. But it is running on the CPU. We renamed it to “raster thread” because many developers wrongly (but understandably) assumed the thread runs on the GPU unit. Performs expensive tasks (mostly I/O) that would otherwise block either the UI or raster threads. This thread is not shown in the performance overlay. For links to more information and videos, see The Framework architecture on the GitHub wiki, and the community article, The Layer Cake. Displaying the performance overlay
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-11
Displaying the performance overlay You can toggle display of the performance overlay as follows: Using the Flutter inspector From the command line Programmatically Using the Flutter inspector The easiest way to enable the PerformanceOverlay widget is from the Flutter inspector, which is available in the Inspector view in DevTools. Simply click the Performance Overlay button to toggle the overlay on your running app. From the command line Toggle the performance overlay using the P key from the command line. Programmatically To enable the overlay programmatically, see Performance overlay, a section in the Debugging Flutter apps programmatically page. Identifying problems in the UI graph If the performance overlay shows red in the UI graph, start by profiling the Dart VM, even if the GPU graph also shows red. Identifying problems in the GPU graph
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-12
Identifying problems in the GPU graph Sometimes a scene results in a layer tree that is easy to construct, but expensive to render on the raster thread. When this happens, the UI graph has no red, but the GPU graph shows red. In this case, you’ll need to figure out what your code is doing that is causing rendering code to be slow. Specific kinds of workloads are more difficult for the GPU. They might involve unnecessary calls to saveLayer, intersecting opacities with multiple objects, and clips or shadows in specific situations. If you suspect that the source of the slowness is during an animation, click the Slow Animations button in the Flutter inspector to slow animations down by 5x. If you want more control on the speed, you can also do this programmatically.
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-13
Is the slowness on the first frame, or on the whole animation? If it’s the whole animation, is clipping causing the slow down? Maybe there’s an alternative way of drawing the scene that doesn’t use clipping. For example, overlay opaque corners onto a square instead of clipping to a rounded rectangle. If it’s a static scene that’s being faded, rotated, or otherwise manipulated, a RepaintBoundary might help. Checking for offscreen layers The saveLayer method is one of the most expensive methods in the Flutter framework. It’s useful when applying post-processing to the scene, but it can slow your app and should be avoided if you don’t need it. Even if you don’t call saveLayer explicitly, implicit calls might happen on your behalf. You can check whether your scene is using saveLayer with the PerformanceOverlayLayer.checkerboardOffscreenLayers switch.
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-14
Once the switch is enabled, run the app and look for any images that are outlined with a flickering box. The box flickers from frame to frame if a new frame is being rendered. For example, perhaps you have a group of objects with opacities that are rendered using saveLayer. In this case, it’s probably more performant to apply an opacity to each individual widget, rather than a parent widget higher up in the widget tree. The same goes for other potentially expensive operations, such as clipping or shadows. Note: Opacity, clipping, and shadows are not, in themselves, a bad idea. However, applying them to the top of the widget tree might cause extra calls to saveLayer, and needless processing. When you encounter calls to saveLayer, ask yourself these questions: Does the app need this effect? Can any of these calls be eliminated? Can I apply the same effect to an individual element instead of a group?
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-15
Can I apply the same effect to an individual element instead of a group? Checking for non-cached images Caching an image with RepaintBoundary is good, when it makes sense. One of the most expensive operations, from a resource perspective, is rendering a texture using an image file. First, the compressed image is fetched from persistent storage. The image is decompressed into host memory (GPU memory), and transferred to device memory (RAM). In other words, image I/O can be expensive. The cache provides snapshots of complex hierarchies so they are easier to render in subsequent frames. Because raster cache entries are expensive to construct and take up loads of GPU memory, cache images only where absolutely necessary. You can see which images are being cached by enabling the PerformanceOverlayLayer.checkerboardRasterCacheImages switch.
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-16
Run the app and look for images rendered with a randomly colored checkerboard, indicating that the image is cached. As you interact with the scene, the checkerboarded images should remain constant—you don’t want to see flickering, which would indicate that the cached image is being re-cached. In most cases, you want to see checkerboards on static images, but not on non-static images. If a static image isn’t cached, you can cache it by placing it into a RepaintBoundary widget. Though the engine might still ignore a repaint boundary if it thinks the image isn’t complex enough. Viewing the widget rebuild profiler The Flutter framework is designed to make it hard to create applications that are not 60fps and smooth. Often, if you have jank, it’s because there is a simple bug causing more of the UI to be rebuilt each frame than required. The Widget rebuild profiler helps you debug and fix performance problems due to these sorts of bugs.
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-17
You can view the widget rebuilt counts for the current screen and frame in the Flutter plugin for Android Studio and IntelliJ. For details on how to do this, see Show performance data Benchmarking You can measure and track your app’s performance by writing benchmark tests. The Flutter Driver library provides support for benchmarking. Using this integration test framework, you can generate metrics to track the following: Jank Download size Battery efficiency Startup time Tracking these benchmarks allows you to be informed when a regression is introduced that adversely affects performance. For more information, see Integration testing, a section in Testing Flutter apps. Other resources The following resources provide more information on using Flutter’s tools and debugging in Flutter: Debugging Flutter inspector
https://docs.flutter.dev/perf/ui-performance/index.html
36c691888548-18
Debugging Flutter inspector Flutter inspector talk, presented at DartConf 2018 Why Flutter Uses Dart, an article on Hackernoon Why Flutter uses Dart, a video on the Flutter channel DevTools: performance tooling for Dart and Flutter apps Flutter API docs, particularly the PerformanceOverlay class, and the dart:developer package
https://docs.flutter.dev/perf/ui-performance/index.html
8d7028551419-0
Flutter crash reporting Disabling analytics reporting If you have not opted-out of Flutter’s analytics and crash reporting, when a flutter command crashes it attempts to send a crash report to Google in order to help Google contribute improvements to Flutter over time. A crash report may contain the following information: The name and version of your local operating system. The version of Flutter. The runtime type of the error, for example StateError or NoSuchMethodError. The stack trace generated by the crash, which contains references to the Flutter CLI’s own code and contains no references to your application code. A client ID: a constant and unique number generated for the computer where Flutter is installed. It helps us deduplicate multiple identical crash reports coming from the same computer. It also helps us verify if a fix works as intended after you upgrade to the next version of Flutter.
https://docs.flutter.dev/reference/crash-reporting/index.html
8d7028551419-1
Google handles all data reported by this tool in accordance with the Google Privacy Policy. Disabling analytics reporting You can opt out of anonymous crash reporting and feature usage statistics from Flutter by running the following command: flutter config -no-analytics If you opt out of analytics, an opt-out event will be sent, and then no further information will be sent by that installation of Flutter. To display the current setting, you can run the following command: flutter config
https://docs.flutter.dev/reference/crash-reporting/index.html
53259934e47d-0
flutter: The Flutter command-line tool flutter commands The flutter command-line tool is how developers (or IDEs on behalf of developers) interact with Flutter. For Dart related commands, you can use the dart command-line tool. Here’s how you might use the flutter tool to create, analyze, test, and run an app: flutter create my_app cd my_app flutter analyze flutter test flutter run lib/main.dart To run pub commands using the flutter tool: flutter pub get flutter pub outdated flutter pub upgrade To view all commands that flutter supports: flutter -help -verbose To get the current version of the Flutter SDK, including its framework, engine, and tools: flutter
https://docs.flutter.dev/reference/flutter-cli/index.html
53259934e47d-1
flutter -version flutter commands The following table shows which commands you can use with the flutter tool: analyze flutter analyze -d <DEVICE_ID> Analyzes the project’s Dart source code.Use instead of dart analyze. assemble flutter assemble -o <DIRECTORY> Assemble and build flutter resources. attach flutter attach -d <DEVICE_ID> Attach to a running application. bash-completion flutter bash-completion Output command line shell completion setup scripts. build flutter build <DIRECTORY> Flutter build commands. channel flutter channel <CHANNEL_NAME> List or switch flutter channels. clean flutter clean
https://docs.flutter.dev/reference/flutter-cli/index.html
53259934e47d-2
List or switch flutter channels. clean flutter clean Delete the build/ and .dart_tool/ directories. config flutter config --build-dir=<DIRECTORY> Configure Flutter settings. To remove a setting, configure it to an empty string. create flutter create <DIRECTORY> Creates a new project. custom-devices flutter custom-devices list Add, delete, list, and reset custom devices. devices flutter devices -d <DEVICE_ID> List all connected devices. doctor flutter doctor Show information about the installed tooling. downgrade flutter downgrade Downgrade Flutter to the last active version for the current channel. drive
https://docs.flutter.dev/reference/flutter-cli/index.html
53259934e47d-3
drive flutter drive Runs Flutter Driver tests for the current project. emulators flutter emulators List, launch and create emulators. format flutter format <DIRECTORY|DART_FILE> Formats Flutter source code.Deprecated, instead use dart format. gen-l10n flutter gen-l10n <DIRECTORY> Generate localizations for the Flutter project. install flutter install -d <DEVICE_ID> Install a Flutter app on an attached device. logs flutter logs Show log output for running Flutter apps. precache flutter precache <ARGUMENTS> Populates the Flutter tool’s cache of binary artifacts.
https://docs.flutter.dev/reference/flutter-cli/index.html
53259934e47d-4
Populates the Flutter tool’s cache of binary artifacts. pub flutter pub <PUB_COMMAND> Works with packages.Use instead of dart pub. run flutter run <DART_FILE> Runs a Flutter program. screenshot flutter screenshot Take a screenshot of a Flutter app from a connected device. symbolize flutter symbolize --input=<STACK_TRACK_FILE> Symbolize a stack trace from the AOT compiled flutter application. test flutter test [<DIRECTORY|DART_FILE>] Runs tests in this package.Use instead of dart test. upgrade flutter upgrade Upgrade your copy of Flutter.
https://docs.flutter.dev/reference/flutter-cli/index.html
53259934e47d-5
flutter upgrade Upgrade your copy of Flutter. For additional help on any of the commands, enter flutter help <command> or follow the links in the More information column. You can also get details on pub commands — for example, flutter help pub outdated.
https://docs.flutter.dev/reference/flutter-cli/index.html
4c1a8c2b58f5-0
Security false positives Introduction Common concerns Shared objects should use fortified functions Shared objects should use RELRO Shared objects should use stack canary values Code should avoid using the _sscanf, _strlen, and _fopen APIs Code should use calloc (instead of _malloc) for memory allocations The iOS binary has a Runpath Search Path (@rpath) set CBC with PKCS5/PKCS7 padding vulnerability Apps can read and write to external storage Apps delete data using file.delete() Obsolete concerns The stack should have its NX bit set Reporting real concerns Introduction We occasionally receive false reports of security vulnerabilities in Dart and Flutter applications, generated by tools that were built for other kinds of applications (for example, those written with Java or C++). This document provides information on reports that we believe are incorrect and explains why the concerns are misplaced.
https://docs.flutter.dev/reference/security-false-positives/index.html
4c1a8c2b58f5-1
Common concerns Shared objects should use fortified functions The shared object does not have any fortified functions. Fortified functions provides buffer overflow checks against glibc’s commons insecure functions like strcpy, gets etc. Use the compiler option -D_FORTIFY_SOURCE=2 to fortify functions. When this refers to compiled Dart code (such as the libapp.so file in Flutter applications), this advice is misguided because Dart code doesn’t directly invoke libc functions; all Dart code goes through the Dart standard library. (In general, MobSF gets false positives here because it checks for any use of functions with a _chk suffix, but since Dart doesn’t use these functions at all, it doesn’t have calls with or without the suffix, and therefore MobSF treats the code as containing non-fortified calls.) Shared objects should use RELRO no RELRO found for libapp.so binaries
https://docs.flutter.dev/reference/security-false-positives/index.html
4c1a8c2b58f5-2
no RELRO found for libapp.so binaries Dart doesn’t use the normal Procedure Linkage Table (PLT) or Global Offsets Table (GOT) mechanisms at all, so the Relocation Read-Only (RELRO) technique doesn’t really make much sense for Dart. Dart’s equivalent of GOT is the pool pointer, which unlike GOT, is located in a randomized location and is therefore much harder to exploit. In principle, you can create vulnerable code when using Dart FFI, but normal use of Dart FFI wouldn’t be prone to these issues either, assuming it’s used with C code that itself uses RELRO appropriately. Shared objects should use stack canary values no canary are found for libapp.so binaries
https://docs.flutter.dev/reference/security-false-positives/index.html
4c1a8c2b58f5-3
no canary are found for libapp.so binaries This shared object does not have a stack canary value added to the stack. Stack canaries are used to detect and prevent exploits from overwriting return address. Use the option -fstack-protector-all to enable stack canaries. Dart doesn’t generate stack canaries because, unlike C++, Dart doesn’t have stack-allocated arrays (the primary source of stack smashing in C/C++). When writing pure Dart (without using dart:ffi), you already have much stronger isolation guarantees than any C++ mitigation can provide, simply because pure Dart code is a managed language where things like buffer overruns don’t exist. In principle, you can create vulnerable code when using Dart FFI, but normal use of Dart FFI would not be prone to these issues either, assuming it’s used with C code that itself uses stack canary values appropriately.
https://docs.flutter.dev/reference/security-false-positives/index.html
4c1a8c2b58f5-4
Code should avoid using the _sscanf, _strlen, and _fopen APIs The binary may contain the following insecure API(s) _sscanf , _strlen , _fopen. The tools that report these issues tend to be overly-simplistic in their scans; for example, finding custom functions with these names and assuming they refer to the standard library functions. Many of Flutter’s third-party dependencies have functions with similar names that trip these checks. It’s possible that some occurrences are valid concerns, but it’s impossible to tell from the output of these tools due to the sheer number of false positives. Code should use calloc (instead of _malloc) for memory allocations The binary may use _malloc function instead of calloc.
https://docs.flutter.dev/reference/security-false-positives/index.html
4c1a8c2b58f5-5
The binary may use _malloc function instead of calloc. Memory allocation is a nuanced topic, where trade-offs have to be made between performance and resilience to vulnerabilities. Merely using malloc is not automatically indicative of a security vulnerability. While we welcome concrete reports (see below) for cases where using calloc would be preferable, in practice it would be inappropriate to uniformly replace all malloc calls with calloc. The iOS binary has a Runpath Search Path (@rpath) set The binary has Runpath Search Path (@rpath) set. In certain cases an attacker can abuse this feature to run arbitrary executable for code execution and privilege escalation. Remove the compiler option -rpath to remove @rpath.
https://docs.flutter.dev/reference/security-false-positives/index.html
4c1a8c2b58f5-6
When the app is being built, Runpath Search Path refers to the paths the linker searches to find dynamic libraries (dylibs) used by the app. By default, iOS apps have this set to @executable_path/Frameworks, which means the linker should search for dylibs in the Frameworks directory relative to the app binary inside the app bundle. The Flutter.framework engine, like most embedded frameworks or dylibs, is correctly copied into this directory. When the app runs, it loads the library binary. Flutter apps use the default iOS build setting (LD_RUNPATH_SEARCH_PATHS=@executable_path/Frameworks). Vulnerabilities involving @rpath don’t apply in mobile settings, as attackers don’t have access to the file system and can’t arbitrarily swap out these frameworks. Even if an attacker somehow could swap out the framework with a malicious one, the app would crash on launch due to codesigning violations.
https://docs.flutter.dev/reference/security-false-positives/index.html
4c1a8c2b58f5-7
CBC with PKCS5/PKCS7 padding vulnerability We have received vague reports that there is a “CBC with PKCS5/PKCS7 padding vulnerability” in some Flutter packages. As far as we can tell, this is triggered by the HLS implementation in ExoPlayer (the com.google.android.exoplayer2.source.hls.Aes128DataSource class). HLS is Apple’s streaming format, which defines the type of encryption that must be used for DRM; this isn’t a vulnerability, as DRM doesn’t protect the user’s machine or data but instead merely provides obfuscation to limit the user’s ability to fully use their software and hardware. Apps can read and write to external storage App can read/write to External Storage. Any App can read data written to External Storage.
https://docs.flutter.dev/reference/security-false-positives/index.html
4c1a8c2b58f5-8
App can read/write to External Storage. Any App can read data written to External Storage. As with data from any untrusted source, you should perform input validation when handling data from external storage. We strongly recommend that you not store executables or class files on external storage prior to dynamic loading. If your app does retrieve executable files from external storage, the files should be signed and cryptographically verified prior to dynamic loading. We have received reports that some vulnerability scanning tools interpret the ability for image picker plugins to read and write to external storage as a threat. Reading images from local storage is the purpose of these plugins; this is not a vulnerability. Apps delete data using file.delete() When you delete a file using file. delete, only the reference to the file is removed from the file system table. The file still exists on disk until other data overwrites it, leaving it vulnerable to recovery.
https://docs.flutter.dev/reference/security-false-positives/index.html
4c1a8c2b58f5-9
Some vulnerability scanning tools interpret the deletion of temporary files after a camera plugin records data from the device’s camera as a security vulnerability. Because the video is recorded by the user and is stored on the user’s hardware, there is no actual risk. Obsolete concerns This section contains valid messages that might be seen with older versions of Dart and Flutter, but should no longer be seen with more recent versions. If you see these messages with old versions of Dart or Flutter, upgrade to the latest stable version. If you see these with the current stable version, please report them (see the section at the end of this document). The stack should have its NX bit set The shared object does not have NX bit set. NX bit offer protection against exploitation of memory corruption vulnerabilities by marking memory page as non-executable. Use option --noexecstack or -z noexecstack to mark stack as non executable.
https://docs.flutter.dev/reference/security-false-positives/index.html
4c1a8c2b58f5-10
(The message from MobSF is misleading; it’s looking for whether the stack is marked as non-executable, not the shared object.) In older versions of Dart and Flutter there was a bug where the ELF generator didn’t emit the gnustack segment with the ~X permission, but this is now fixed. Reporting real concerns While automated vulnerability scanning tools report false positives such as the examples above, we can’t rule out that there are real issues that deserve closer attention. Should you find an issue that you believe is a legitimate security vulnerability, we would greatly appreciate if you would report it: Flutter security policy Dart security policy
https://docs.flutter.dev/reference/security-false-positives/index.html
801ed97ecd08-0
Tutorials The Flutter tutorials teach you how to use the Flutter framework to build mobile applications for iOS and Android. Choose from the following: Building layouts How to build layouts using Flutter’s layout mechanism. Once you’ve learned basic principles, you’ll build the layout for a sample screenshot. Adding interactivity to your Flutter app You’ll extend the simple layout app created in “Building Layouts in Flutter” to make an icon tappable. Different ways of managing a widget’s state are also discussed. Animations in Flutter Explains the fundamental classes in the Flutter animation package (controllers, Animatable, curves, listeners, builders), as it guides you through a progression of tween animations using different aspects of the animation APIs.
https://docs.flutter.dev/reference/tutorials/index.html
801ed97ecd08-1
Internationalizing Flutter apps Learn how to internationalize your Flutter application. A guide through the widgets and classes that enable apps to display their content using the user’s language and formatting conventions.
https://docs.flutter.dev/reference/tutorials/index.html
8965fec2fbf6-0
Flutter widget index This is an alphabetical list of nearly every widget that is bundled with Flutter. You can also browse widgets by category. You might also want to check out our Widget of the Week video series on the Flutter YouTube channel. Each short episode features a different Flutter widget. For more video series, see our videos page. Widget of the Week playlist AbsorbPointer A widget that absorbs pointers during hit testing. When absorbing is true, this widget prevents its subtree from receiving pointer events by terminating hit testing... AlertDialog Alerts are urgent interruptions requiring acknowledgement that inform the user about a situation. The AlertDialog widget implements this component. Align A widget that aligns its child within itself and optionally sizes itself based on the child's size. AnimatedAlign
https://docs.flutter.dev/reference/widgets/index.html
8965fec2fbf6-1
AnimatedAlign Animated version of Align which automatically transitions the child's position over a given duration whenever the given alignment changes. AnimatedBuilder A general-purpose widget for building animations. AnimatedBuilder is useful for more complex widgets that wish to include animation as part of a larger build function.... AnimatedContainer A container that gradually changes its values over a period of time. AnimatedCrossFade A widget that cross-fades between two given children and animates itself between their sizes. AnimatedDefaultTextStyle Animated version of DefaultTextStyle which automatically transitions the default text style (the text style to apply to descendant Text widgets without explicit style) over a... AnimatedList A scrolling container that animates items when they are inserted or removed. AnimatedListState The state for a scrolling container that animates items when they are inserted or removed.
https://docs.flutter.dev/reference/widgets/index.html
8965fec2fbf6-2
The state for a scrolling container that animates items when they are inserted or removed. AnimatedModalBarrier A widget that prevents the user from interacting with widgets behind itself. AnimatedOpacity Animated version of Opacity which automatically transitions the child's opacity over a given duration whenever the given opacity changes. AnimatedPhysicalModel Animated version of PhysicalModel. AnimatedPositioned Animated version of Positioned which automatically transitions the child's position over a given duration whenever the given position changes. AnimatedSize Animated widget that automatically transitions its size over a given duration whenever the given child's size changes. AnimatedWidget A widget that rebuilds when the given Listenable changes value. AnimatedWidgetBaseState A base class for widgets with implicit animations. AppBar
https://docs.flutter.dev/reference/widgets/index.html
8965fec2fbf6-3
A base class for widgets with implicit animations. AppBar A Material Design app bar. An app bar consists of a toolbar and potentially other widgets, such as a TabBar and a FlexibleSpaceBar. AspectRatio A widget that attempts to size the child to a specific aspect ratio. AssetBundle Asset bundles contain resources, such as images and strings, that can be used by an application. Access to these resources is asynchronous so that they... Autocomplete A widget for helping the user make a selection by entering some text and choosing from among a list of options. BackdropFilter A widget that applies a filter to the existing painted content and then paints a child. This effect is relatively expensive, especially if the filter... Abc Baseline A widget that positions its child according to the child's baseline. BottomNavigationBar
https://docs.flutter.dev/reference/widgets/index.html
8965fec2fbf6-4
BottomNavigationBar Bottom navigation bars make it easy to explore and switch between top-level views in a single tap. The BottomNavigationBar widget implements this component. BottomSheet Bottom sheets slide up from the bottom of the screen to reveal more content. You can call showBottomSheet() to implement a persistent bottom sheet or... Card A Material Design card. A card has slightly rounded corners and a shadow. Center A widget that centers its child within itself. Checkbox Checkboxes allow the user to select multiple options from a set. The Checkbox widget implements this component. Chip A Material Design chip. Chips represent complex entities in small blocks, such as a contact. CircularProgressIndicator A material design circular progress indicator, which spins to indicate that the application is busy. ClipOval
https://docs.flutter.dev/reference/widgets/index.html
8965fec2fbf6-5
ClipOval A widget that clips its child using an oval. ClipPath A widget that clips its child using a path. ClipRect A widget that clips its child using a rectangle. Column Layout a list of child widgets in the vertical direction. ConstrainedBox A widget that imposes additional constraints on its child. Container A convenience widget that combines common painting, positioning, and sizing widgets. CupertinoActionSheet An iOS-style modal bottom action sheet to choose an option among many. CupertinoActivityIndicator An iOS-style activity indicator. Displays a circular 'spinner'. CupertinoAlertDialog An iOS-style alert dialog. CupertinoButton An iOS-style button.
https://docs.flutter.dev/reference/widgets/index.html
8965fec2fbf6-6
CupertinoButton An iOS-style button. CupertinoContextMenu An iOS-style full-screen modal route that opens when the child is long-pressed. Used to display relevant actions for your content. CupertinoDatePicker An iOS-style date or date and time picker. CupertinoDialogAction A button typically used in a CupertinoAlertDialog. CupertinoFullscreenDialogTransition An iOS-style transition used for summoning fullscreen dialogs. CupertinoListSection An iOS-style container for a scrollable view. CupertinoListTile An iOS-style tile that makes up a row in a list. CupertinoNavigationBar An iOS-style top navigation bar. Typically used with CupertinoPageScaffold.
https://docs.flutter.dev/reference/widgets/index.html
8965fec2fbf6-7
CupertinoPageScaffold Basic iOS style page layout structure. Positions a navigation bar and content on a background. CupertinoPageTransition Provides an iOS-style page transition animation. CupertinoPicker An iOS-style picker control. Used to select an item in a short list. CupertinoPopupSurface Rounded rectangle surface that looks like an iOS popup surface, such as an alert dialog or action sheet. CupertinoScrollbar An iOS-style scrollbar that indicates which portion of a scrollable widget is currently visible. CupertinoSearchTextField An iOS-style search field. CupertinoSegmentedControl An iOS-style segmented control. Used to select mutually exclusive options in a horizontal list. CupertinoSlider Used to select from a range of values.
https://docs.flutter.dev/reference/widgets/index.html