id
stringlengths
14
17
text
stringlengths
23
1.11k
source
stringlengths
35
114
8b9a5f78a039-10
During build, Flutter also avoids walking the parent chain using InheritedWidgets. If widgets commonly walked their parent chain, for example to determine the current theme color, the build phase would become O(N²) in the depth of the tree, which can be quite large due to aggressive composition. To avoid these parent walks, the framework pushes information down the element tree by maintaining a hash table of InheritedWidgets at each element. Typically, many elements will reference the same hash table, which changes only at elements that introduce a new InheritedWidget. Linear reconciliation Contrary to popular belief, Flutter does not employ a tree-diffing algorithm. Instead, the framework decides whether to reuse elements by examining the child list for each element independently using an O(N) algorithm. The child list reconciliation algorithm optimizes for the following cases: The old child list is empty. The two lists are identical.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-11
The old child list is empty. The two lists are identical. There is an insertion or removal of one or more widgets in exactly one place in the list. If each list contains a widget with the same key5, the two widgets are matched. The general approach is to match up the beginning and end of both child lists by comparing the runtime type and key of each widget, potentially finding a non-empty range in the middle of each list that contains all the unmatched children. The framework then places the children in the range in the old child list into a hash table based on their keys. Next, the framework walks the range in the new child list and queries the hash table by key for matches. Unmatched children are discarded and rebuilt from scratch whereas matched children are rebuilt with their new widgets. Tree surgery
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-12
Tree surgery Reusing elements is important for performance because elements own two critical pieces of data: the state for stateful widgets and the underlying render objects. When the framework is able to reuse an element, the state for that logical part of the user interface is preserved and the layout information computed previously can be reused, often avoiding entire subtree walks. In fact, reusing elements is so valuable that Flutter supports non-local tree mutations that preserve state and layout information. Developers can perform a non-local tree mutation by associating a GlobalKey with one of their widgets. Each global key is unique throughout the entire application and is registered with a thread-specific hash table. During the build phase, the developer can move a widget with a global key to an arbitrary location in the element tree. Rather than building a fresh element at that location, the framework will check the hash table and reparent the existing element from its previous location to its new location, preserving the entire subtree.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-13
The render objects in the reparented subtree are able to preserve their layout information because the layout constraints are the only information that flows from parent to child in the render tree. The new parent is marked dirty for layout because its child list has changed, but if the new parent passes the child the same layout constraints the child received from its old parent, the child can return immediately from layout, cutting off the walk. Global keys and non-local tree mutations are used extensively by developers to achieve effects such as hero transitions and navigation. Constant-factor optimizations In addition to these algorithmic optimizations, achieving aggressive composability also relies on several important constant-factor optimizations. These optimizations are most important at the leaves of the major algorithms discussed above.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-14
Child-model agnostic. Unlike most toolkits, which use child lists, Flutter’s render tree does not commit to a specific child model. For example, the RenderBox class has an abstract visitChildren() method rather than a concrete firstChild and nextSibling interface. Many subclasses support only a single child, held directly as a member variable, rather than a list of children. For example, RenderPadding supports only a single child and, as a result, has a simpler layout method that takes less time to execute.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-15
Visual render tree, logical widget tree. In Flutter, the render tree operates in a device-independent, visual coordinate system, which means smaller values in the x coordinate are always towards the left, even if the current reading direction is right-to-left. The widget tree typically operates in logical coordinates, meaning with start and end values whose visual interpretation depends on the reading direction. The transformation from logical to visual coordinates is done in the handoff between the widget tree and the render tree. This approach is more efficient because layout and painting calculations in the render tree happen more often than the widget-to-render tree handoff and can avoid repeated coordinate conversions.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-16
Text handled by a specialized render object. The vast majority of render objects are ignorant of the complexities of text. Instead, text is handled by a specialized render object, RenderParagraph, which is a leaf in the render tree. Rather than subclassing a text-aware render object, developers incorporate text into their user interface using composition. This pattern means RenderParagraph can avoid recomputing its text layout as long as its parent supplies the same layout constraints, which is common, even during tree surgery.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-17
Observable objects. Flutter uses both the model-observation and the reactive paradigms. Obviously, the reactive paradigm is dominant, but Flutter uses observable model objects for some leaf data structures. For example, Animations notify an observer list when their value changes. Flutter hands off these observable objects from the widget tree to the render tree, which observes them directly and invalidates only the appropriate stage of the pipeline when they change. For example, a change to an Animation<Color> might trigger only the paint phase rather than both the build and paint phases. Taken together and summed over the large trees created by aggressive composition, these optimizations have a substantial effect on performance. Separation of the Element and RenderObject trees
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-18
Separation of the Element and RenderObject trees The RenderObject and Element (Widget) trees in Flutter are isomorphic (strictly speaking, the RenderObject tree is a subset of the Element tree). An obvious simplification would be to combine these trees into one tree. However, in practice there are a number of benefits to having these trees be separate: Performance. When the layout changes, only the relevant parts of the layout tree need to be walked. Due to composition, the element tree frequently has many additional nodes that would have to be skipped. Clarity. The clearer separation of concerns allows the widget protocol and the render object protocol to each be specialized to their specific needs, simplifying the API surface and thus lowering the risk of bugs and the testing burden.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-19
Type safety. The render object tree can be more type safe since it can guarantee at runtime that children will be of the appropriate type (each coordinate system, e.g. has its own type of render object). Composition widgets can be agnostic about the coordinate system used during layout (for example, the same widget exposing a part of the app model could be used in both a box layout and a sliver layout), and thus in the element tree, verifying the type of render objects would require a tree walk. Infinite scrolling Infinite scrolling lists are notoriously difficult for toolkits. Flutter supports infinite scrolling lists with a simple interface based on the builder pattern, in which a ListView uses a callback to build widgets on demand as they become visible to the user during scrolling. Supporting this feature requires viewport-aware layout and building widgets on demand. Viewport-aware layout
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-20
Viewport-aware layout Like most things in Flutter, scrollable widgets are built using composition. The outside of a scrollable widget is a Viewport, which is a box that is “bigger on the inside,” meaning its children can extend beyond the bounds of the viewport and can be scrolled into view. However, rather than having RenderBox children, a viewport has RenderSliver children, known as slivers, which have a viewport-aware layout protocol. The sliver layout protocol matches the structure of the box layout protocol in that parents pass constraints down to their children and receive geometry in return. However, the constraint and geometry data differs between the two protocols. In the sliver protocol, children are given information about the viewport, including the amount of visible space remaining. The geometry data they return enables a variety of scroll-linked effects, including collapsible headers and parallax.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-21
Different slivers fill the space available in the viewport in different ways. For example, a sliver that produces a linear list of children lays out each child in order until the sliver either runs out of children or runs out of space. Similarly, a sliver that produces a two-dimensional grid of children fills only the portion of its grid that is visible. Because they are aware of how much space is visible, slivers can produce a finite number of children even if they have the potential to produce an unbounded number of children. Slivers can be composed to create bespoke scrollable layouts and effects. For example, a single viewport can have a collapsible header followed by a linear list and then a grid. All three slivers will cooperate through the sliver layout protocol to produce only those children that are actually visible through the viewport, regardless of whether those children belong to the header, the list, or the grid6. Building widgets on demand
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-22
Building widgets on demand If Flutter had a strict build-then-layout-then-paint pipeline, the foregoing would be insufficient to implement an infinite scrolling list because the information about how much space is visible through the viewport is available only during the layout phase. Without additional machinery, the layout phase is too late to build the widgets necessary to fill the space. Flutter solves this problem by interleaving the build and layout phases of the pipeline. At any point in the layout phase, the framework can start building new widgets on demand as long as those widgets are descendants of the render object currently performing layout.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-23
Interleaving build and layout is possible only because of the strict controls on information propagation in the build and layout algorithms. Specifically, during the build phase, information can propagate only down the tree. When a render object is performing layout, the layout walk has not visited the subtree below that render object, which means writes generated by building in that subtree cannot invalidate any information that has entered the layout calculation thus far. Similarly, once layout has returned from a render object, that render object will never be visited again during this layout, which means any writes generated by subsequent layout calculations cannot invalidate the information used to build the render object’s subtree. Additionally, linear reconciliation and tree surgery are essential for efficiently updating elements during scrolling and for modifying the render tree when elements are scrolled into and out of view at the edge of the viewport. API Ergonomics
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-24
API Ergonomics Being fast only matters if the framework can actually be used effectively. To guide Flutter’s API design towards greater usability, Flutter has been repeatedly tested in extensive UX studies with developers. These studies sometimes confirmed pre-existing design decisions, sometimes helped guide the prioritization of features, and sometimes changed the direction of the API design. For instance, Flutter’s APIs are heavily documented; UX studies confirmed the value of such documentation, but also highlighted the need specifically for sample code and illustrative diagrams. This section discusses some of the decisions made in Flutter’s API design in aid of usability. Specializing APIs to match the developer’s mindset The base class for nodes in Flutter’s Widget, Element, and RenderObject trees does not define a child model. This allows each node to be specialized for the child model that is applicable to that node.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-25
In some rare cases, more complicated child models are used. The RenderTable render object’s constructor takes an array of arrays of children, the class exposes getters and setters that control the number of rows and columns, and there are specific methods to replace individual children by x,y coordinate, to add a row, to provide a new array of arrays of children, and to replace the entire child list with a single array and a column count. In the implementation, the object does not use a linked list like most render objects but instead uses an indexable array. The Chip widgets and InputDecoration objects have fields that match the slots that exist on the relevant controls. Where a one-size-fits-all child model would force semantics to be layered on top of a list of children, for example, defining the first child to be the prefix value and the second to be the suffix, the dedicated child model allows for dedicated named properties to be used instead.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-26
This flexibility allows each node in these trees to be manipulated in the way most idiomatic for its role. It’s rare to want to insert a cell in a table, causing all the other cells to wrap around; similarly, it’s rare to want to remove a child from a flex row by index instead of by reference. The RenderParagraph object is the most extreme case: it has a child of an entirely different type, TextSpan. At the RenderParagraph boundary, the RenderObject tree transitions into being a TextSpan tree. The overall approach of specializing APIs to meet the developer’s expectations is applied to more than just child models. Similarly, hiding a widget subtree is easily done by not including the widget subtree in the build at all. However, developers typically expect there to be a widget to do this, and so the Visibility widget exists to wrap this pattern in a trivial reusable widget. Explicit arguments
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-27
Explicit arguments UI frameworks tend to have many properties, such that a developer is rarely able to remember the semantic meaning of each constructor argument of each class. As Flutter uses the reactive paradigm, it is common for build methods in Flutter to have many calls to constructors. By leveraging Dart’s support for named arguments, Flutter’s API is able to keep such build methods clear and understandable. This pattern is extended to any method with multiple arguments, and in particular is extended to any boolean argument, so that isolated true or false literals in method calls are always self-documenting. Furthermore, to avoid confusion commonly caused by double negatives in APIs, boolean arguments and properties are always named in the positive form (for example, enabled: true rather than disabled: false). Paving over pitfalls A technique used in a number of places in the Flutter framework is to define the API such that error conditions don’t exist. This removes entire classes of errors from consideration.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-28
For example, interpolation functions allow one or both ends of the interpolation to be null, instead of defining that as an error case: interpolating between two null values is always null, and interpolating from a null value or to a null value is the equivalent of interpolating to the zero analog for the given type. This means that developers who accidentally pass null to an interpolation function will not hit an error case, but will instead get a reasonable result. A more subtle example is in the Flex layout algorithm. The concept of this layout is that the space given to the flex render object is divided among its children, so the size of the flex should be the entirety of the available space. In the original design, providing infinite space would fail: it would imply that the flex should be infinitely sized, a useless layout configuration. Instead, the API was adjusted so that when infinite space is allocated to the flex render object, the render object sizes itself to fit the desired size of the children, reducing the possible number of error cases.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-29
In general, the approach is to define valid interpretations for all values in the input domain. The simplest example is the Color constructor. Instead of taking four integers, one for red, one for green, one for blue, and one for alpha, each of which could be out of range, the default constructor takes a single integer value, and defines the meaning of each bit (for example, the bottom eight bits define the red component), so that any input value is a valid color value. A more elaborate example is the paintImage() function. This function takes eleven arguments, some with quite wide input domains, but they have been carefully designed to be mostly orthogonal to each other, such that there are very few invalid combinations. Reporting error cases aggressively
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-30
Reporting error cases aggressively Not all error conditions can be designed out. For those that remain, in debug builds, Flutter generally attempts to catch the errors very early and immediately reports them. Asserts are widely used. Constructor arguments are sanity checked in detail. Lifecycles are monitored and when inconsistencies are detected they immediately cause an exception to be thrown. In some cases, this is taken to extremes: for example, when running unit tests, regardless of what else the test is doing, every RenderBox subclass that is laid out aggressively inspects whether its intrinsic sizing methods fulfill the intrinsic sizing contract. This helps catch errors in APIs that might otherwise not be exercised.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-31
When exceptions are thrown, they include as much information as is available. Some of Flutter’s error messages proactively probe the associated stack trace to determine the most likely location of the actual bug. Others walk the relevant trees to determine the source of bad data. The most common errors include detailed instructions including in some cases sample code for avoiding the error, or links to further documentation. Reactive paradigm Mutable tree-based APIs suffer from a dichotomous access pattern: creating the tree’s original state typically uses a very different set of operations than subsequent updates. Flutter’s rendering layer uses this paradigm, as it is an effective way to maintain a persistent tree, which is key for efficient layout and painting. However, it means that direct interaction with the rendering layer is awkward at best and bug-prone at worst.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-32
Flutter’s widget layer introduces a composition mechanism using the reactive paradigm7 to manipulate the underlying rendering tree. This API abstracts out the tree manipulation by combining the tree creation and tree mutation steps into a single tree description (build) step, where, after each change to the system state, the new configuration of the user interface is described by the developer and the framework computes the series of tree mutations necessary to reflect this new configuration. Interpolation Since Flutter’s framework encourages developers to describe the interface configuration matching the current application state, a mechanism exists to implicitly animate between these configurations. For example, suppose that in state S1 the interface consists of a circle, but in state S2 it consists of a square. Without an animation mechanism, the state change would have a jarring interface change. An implicit animation allows the circle to be smoothly squared over several frames.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-33
Each feature that can be implicitly animated has a stateful widget that keeps a record of the current value of the input, and begins an animation sequence whenever the input value changes, transitioning from the current value to the new value over a specified duration. For the circle-to-square transition, the lerp function would return an object representing a “rounded square” with a radius described as a fraction derived from the t value, a color interpolated using the lerp function for colors, and a stroke width interpolated using the lerp function for doubles. That object, which implements the same interface as circles and squares, would then be able to paint itself when requested to. This technique allows the state machinery, the mapping of states to configurations, the animation machinery, the interpolation machinery, and the specific logic relating to how to paint each frame to be entirely separated from each other.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-34
This approach is broadly applicable. In Flutter, basic types like Color and Shape can be interpolated, but so can much more elaborate types such as Decoration, TextStyle, or Theme. These are typically constructed from components that can themselves be interpolated, and interpolating the more complicated objects is often as simple as recursively interpolating all the values that describe the complicated objects. This allows the class hierarchy to be arbitrarily extended, with later additions being able to interpolate between previously-known values and themselves. In some cases, the interpolation itself cannot be described by any of the available classes, and a private class is defined to describe the intermediate stage. This is the case, for instance, when interpolating between a CircleBorder and a RoundedRectangleBorder.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-35
This mechanism has one further added advantage: it can handle interpolation from intermediate stages to new values. For example, half-way through a circle-to-square transition, the shape could be changed once more, causing the animation to need to interpolate to a triangle. So long as the triangle class can lerpFrom the rounded-square intermediate class, the transition can be seamlessly performed. Conclusion Flutter’s slogan, “everything is a widget,” revolves around building user interfaces by composing widgets that are, in turn, composed of progressively more basic widgets. The result of this aggressive composition is a large number of widgets that require carefully designed algorithms and data structures to process efficiently. With some additional design, these data structures also make it easy for developers to create infinite scrolling lists that build widgets on demand when they become visible. Footnotes:
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-36
Footnotes: 1 For layout, at least. It might be revisited for painting, for building the accessibility tree if necessary, and for hit testing if necessary. 2 Reality, of course, is a bit more complicated. Some layouts involve intrinsic dimensions or baseline measurements, which do involve an additional walk of the relevant subtree (aggressive caching is used to mitigate the potential for quadratic performance in the worst case). These cases, however, are surprisingly rare. In particular, intrinsic dimensions are not required for the common case of shrink-wrapping.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-37
3 Technically, the child’s position is not part of its RenderBox geometry and therefore need not actually be calculated during layout. Many render objects implicitly position their single child at 0,0 relative to their own origin, which requires no computation or storage at all. Some render objects avoid computing the position of their children until the last possible moment (for example, during the paint phase), to avoid the computation entirely if they are not subsequently painted. 4 There exists one exception to this rule. As discussed in the Building widgets on demand section, some widgets can be rebuilt as a result of a change in layout constraints. If a widget marked itself dirty for unrelated reasons in the same frame that it also is affected by a change in layout constraints, it will be updated twice. This redundant build is limited to the widget itself and does not impact its descendants. 5 A key is an opaque object optionally associated with a widget whose equality operator is used to influence the reconciliation algorithm.
https://docs.flutter.dev/resources/inside-flutter/index.html
8b9a5f78a039-38
6 For accessibility, and to give applications a few extra milliseconds between when a widget is built and when it appears on the screen, the viewport creates (but does not paint) widgets for a few hundred pixels before and after the visible widgets. 7 This approach was first made popular by Facebook’s React library. 8 In practice, the t value is allowed to extend past the 0.0-1.0 range, and does so for some curves. For example, the “elastic” curves overshoot briefly in order to represent a bouncing effect. The interpolation logic typically can extrapolate past the start or end as appropriate. For some types, for example, when interpolating colors, the t value is effectively clamped to the 0.0-1.0 range.
https://docs.flutter.dev/resources/inside-flutter/index.html
471f586f3709-0
Flutter News Toolkit The Flutter News Toolkit enables you to accelerate development of a mobile news app. The toolkit assists you in building a customized template app with prebuilt features required for most news apps, such authentication and monetization. After generating your template app, your primary tasks are to connect to your data source, and to customize the UI to reflect your brand. The Flutter News Toolkit includes critical features, such as: User onboarding Account creation/login Content feeds and content pages Analytics Notifications Social sharing Subscriptions Ads You can use these pre-integrated features out of the box, or modify and swap them with other functionality that you prefer. Generating your template app requires answering a few simple questions, as described on the Flutter News Toolkit Overview doc page.
https://docs.flutter.dev/resources/news-toolkit/index.html
471f586f3709-1
For complete documentation on how to configure your project, create a template app, develop the app, how to handle authentication, theming, work with an API server, and much more, check out the Flutter News Toolkit documentation. You might also check out: Announcing the Flutter News Toolkit, an article on Medium. Quick start to building a news app in Flutter an introduction to the toolkit on YouTube. Note: This is the first release of the news toolkit and, while is has been tested by early adopters, it might have issues or rough edges. Please don’t hesitate to file an issue.
https://docs.flutter.dev/resources/news-toolkit/index.html
dade139da41e-0
Platform-specific behaviors and adaptations Adaptation philosophy Page navigation Navigation transitions Platform-specific transition details Back navigation Scrolling Physics simulation Overscroll behavior Momentum Return to top Typography Iconography Haptic feedback Text editing Keyboard gesture navigation Text selection toolbar Single tap gesture Long-press gesture Long-press drag gesture Double tap gesture Adaptation philosophy There are generally two cases of platform adaptiveness: Things that are behaviors of the OS environment (such as text editing and scrolling) and that would be ‘wrong’ if a different behavior took place. Things that are conventionally implemented in apps using the OEM’s SDKs (such as using parallel tabs on iOS or showing an android.app.AlertDialog on Android).
https://docs.flutter.dev/resources/platform-adaptations/index.html
dade139da41e-1
This article mainly covers the automatic adaptations provided by Flutter in case 1 on Android and iOS. For case 2, Flutter bundles the means to produce the appropriate effects of the platform conventions but doesn’t adapt automatically when app design choices are needed. For a discussion, see issue #8410 and the Material/Cupertino adaptive widget problem definition. For an example of an app using different information architecture structures on Android and iOS but sharing the same content code, see the platform_design code samples. Page navigation Flutter provides the navigation patterns seen on Android and iOS and also automatically adapts the navigation animation to the current platform. Navigation transitions On Android, the default Navigator.push() transition is modeled after startActivity(), which generally has one bottom-up animation variant. On iOS:
https://docs.flutter.dev/resources/platform-adaptations/index.html
dade139da41e-2
On iOS: The default Navigator.push() API produces an iOS Show/Push style transition that animates from end-to-start depending on the locale’s RTL setting. The page behind the new route also parallax-slides in the same direction as in iOS. A separate bottom-up transition style exists when pushing a page route where PageRoute.fullscreenDialog is true. This represents iOS’s Present/Modal style transition and is typically used on fullscreen modal pages. Platform-specific transition details On Android, two page transition animation styles exist depending on your OS version: Pre API 28 uses a bottom-up animation that slides up and fades in. On API 28 and later, the bottom-up animation slides and clip-reveals up.
https://docs.flutter.dev/resources/platform-adaptations/index.html
dade139da41e-3
On iOS when the push style transition is used, Flutter’s bundled CupertinoNavigationBar and CupertinoSliverNavigationBar nav bars automatically animate each subcomponent to its corresponding subcomponent on the next or previous page’s CupertinoNavigationBar or CupertinoSliverNavigationBar. Back navigation On Android, the OS back button, by default, is sent to Flutter and pops the top route of the WidgetsApp’s Navigator. On iOS, an edge swipe gesture can be used to pop the top route. Scrolling Scrolling is an important part of the platform’s look and feel, and Flutter automatically adjusts the scrolling behavior to match the current platform. Physics simulation
https://docs.flutter.dev/resources/platform-adaptations/index.html
dade139da41e-4
Physics simulation Android and iOS both have complex scrolling physics simulations that are difficult to describe verbally. Generally, iOS’s scrollable has more weight and dynamic friction but Android has more static friction. Therefore iOS gains high speed more gradually but stops less abruptly and is more slippery at slow speeds. Overscroll behavior On Android, scrolling past the edge of a scrollable shows an overscroll glow indicator (based on the color of the current Material theme). On iOS, scrolling past the edge of a scrollable overscrolls with increasing resistance and snaps back. Momentum On iOS, repeated flings in the same direction stacks momentum and builds more speed with each successive fling. There is no equivalent behavior on Android. Return to top
https://docs.flutter.dev/resources/platform-adaptations/index.html
dade139da41e-5
Return to top On iOS, tapping the OS status bar scrolls the primary scroll controller to the top position. There is no equivalent behavior on Android. Typography When using the Material package, the typography automatically defaults to the font family appropriate for the platform. On Android, the Roboto font is used. On iOS, the OS’s San Francisco font family is used. When using the Cupertino package, the default theme always uses the San Francisco font. The San Francisco font license limits its usage to software running on iOS, macOS, or tvOS only. Therefore a fallback font is used when running on Android if the platform is debug-overridden to iOS or the default Cupertino theme is used. Iconography
https://docs.flutter.dev/resources/platform-adaptations/index.html
dade139da41e-6
Iconography When using the Material package, certain icons automatically show different graphics depending on the platform. For instance, the overflow button’s three dots are horizontal on iOS and vertical on Android. The back button is a simple chevron on iOS and has a stem/shaft on Android. The material library also provides a set of platform-adaptive icons through Icons.adaptive. Haptic feedback The Material and Cupertino packages automatically trigger the platform appropriate haptic feedback in certain scenarios. For instance, a word selection via text field long-press triggers a ‘buzz’ vibrate on Android and not on iOS. Scrolling through picker items on iOS triggers a ‘light impact’ knock and no feedback on Android. Text editing Flutter also makes the below adaptations while editing the content of text fields to match the current platform. Keyboard gesture navigation
https://docs.flutter.dev/resources/platform-adaptations/index.html
dade139da41e-7
Keyboard gesture navigation On Android, horizontal swipes can be made on the soft keyboard’s spacebar to move the cursor in Material and Cupertino text fields. On iOS devices with 3D Touch capabilities, a force-press-drag gesture could be made on the soft keyboard to move the cursor in 2D via a floating cursor. This works on both Material and Cupertino text fields. Text selection toolbar With Material on Android, the Android style selection toolbar is shown when a text selection is made in a text field. With Material on iOS or when using Cupertino, the iOS style selection toolbar is shown when a text selection is made in a text field. Single tap gesture With Material on Android, a single tap in a text field puts the cursor at the location of the tap. A collapsed text selection also shows a draggable handle to subsequently move the cursor.
https://docs.flutter.dev/resources/platform-adaptations/index.html
dade139da41e-8
A collapsed text selection also shows a draggable handle to subsequently move the cursor. With Material on iOS or when using Cupertino, a single tap in a text field puts the cursor at the nearest edge of the word tapped. Collapsed text selections don’t have draggable handles on iOS. Long-press gesture With Material on Android, a long press selects the word under the long press. The selection toolbar is shown upon release. With Material on iOS or when using Cupertino, a long press places the cursor at the location of the long press. The selection toolbar is shown upon release. Long-press drag gesture With Material on Android, dragging while holding the long press expands the words selected. With Material on iOS or when using Cupertino, dragging while holding the long press moves the cursor. Double tap gesture
https://docs.flutter.dev/resources/platform-adaptations/index.html
dade139da41e-9
Double tap gesture On both Android and iOS, a double tap selects the word receiving the double tap and shows the selection toolbar.
https://docs.flutter.dev/resources/platform-adaptations/index.html
694a1df24d14-0
Videos and online courses Series Flutter Forward Get ready for Flutter Forward Learning to Fly Decoding Flutter Flutter widget of the week Flutter package of the week The Boring Flutter show Flutter at Google I/O 2022 Flutter Engage 2021 Flutter in focus Conference talks Flutter developer stories Online courses These Flutter videos, produced both internally at Google and by the Flutter community, might help if you are a visual learner. Note that many people make Flutter videos. This page shows some that we like, but there are many others, including some in different languages. Series Flutter Forward Even if you couldn’t make it to Nairobi for the in-person event, you can enjoy the content created for Flutter Forward!
https://docs.flutter.dev/resources/videos/index.html
694a1df24d14-1
Flutter Forward livestream Flutter Forward playlist Get ready for Flutter Forward Flutter Forward is happening on Jan 25th, in Nairobi, Kenya. Before the event, the Flutter team provided 17 days of Flutter featuring new content and activities leading up to the event. This playlist contains these and other pre-event videos relating to Flutter Forward. 17 Days of Flutter! Get ready for Flutter Forward playlist Learning to Fly Note: Season 2 of Learning to Fly has been released as part of the 17 Days of Flutter, leading up to the 3.7 release! Season 2 centers around creating a platform game, DoodleDash, using the Flame engine.
https://docs.flutter.dev/resources/videos/index.html
694a1df24d14-2
Follow along with Khanh’s journey as she learns Flutter. From ideation down to the moments of confusion, learn alongside her as she asks important questions like: “What is the best way to build out a theme? How to approach using fonts?” And more! Building my first Flutter app | Learning to Fly Learning to Fly playlist Here are some of the series offered on the flutterdev YouTube channel. For more information, check out all of the Flutter channel’s playlists. Decoding Flutter This series focuses on tips, tricks, best practices, and general advice on getting the most out of Flutter. In the comments section for this series, you can submit suggestions future episodes. Introducing Decoding Flutter Decoding Flutter playlist Flutter widget of the week Do you have 60 seconds? Each one-minute video highlights a Flutter widget.
https://docs.flutter.dev/resources/videos/index.html
694a1df24d14-3
Introducing widget of the week Flutter widget of the week playlist Flutter package of the week If you have another minute (or two), each of these videos highlights a Flutter package. flutter_slidable package Flutter package of the week playlist The Boring Flutter show This series features Flutter programmers coding, unscripted and in real time. Mistakes, solutions (some of them correct), and snazzy intro music included. Introducing the Boring Flutter show The Boring Flutter show playlist Flutter at Google I/O 2022 Google I/O 2022 is over, but you can still catch the great Flutter content! Flutter at Google I/O playlist Flutter Engage 2021
https://docs.flutter.dev/resources/videos/index.html
694a1df24d14-4
Flutter Engage 2021 Flutter Engage 2021 was a day-long event that officially launched Flutter 2. Check out the Flutter Engage 2021 highlights reel: Watch recordings of the sessions on the Flutter YouTube channel: Keynote Flutter Engage 2021 playlist Watch recordings of the sessions offered by the Flutter community: Flutter Engage community talks playlist Flutter in focus Five-to-ten minute tutorials (more or less) on using Flutter. Introducing Flutter in focus Flutter in focus playlist Conference talks Here are a some Flutter talks given at various conferences. Conference talks playlist Flutter developer stories
https://docs.flutter.dev/resources/videos/index.html
694a1df24d14-5
Conference talks playlist Flutter developer stories Videos showing how various customers, such as Abbey Road Studio, Hamilton, and Alibaba, have used Flutter to create beautiful compelling apps with millions of downloads. Flutter developer stories playlist Online courses Learn how to build Flutter apps with these video courses. Before signing up for a course, verify that it includes up-to-date information, such as null safe Dart code. These courses are listed alphabetically. To include your course, submit a PR: The Complete 2021 Flutter Development Bootcamp Using Dart by App Brewery Flutter & Dart - the Complete Guide, 2021 edition Flutter Crash Course by Nick Manning Flutter leicht gemacht 2022 - Zero to Mastery! by Max Berktold (German)
https://docs.flutter.dev/resources/videos/index.html
694a1df24d14-6
Flutter Zero to Hero by Veli Bacik (Turkish) Dart & Flutter - Zero to Mastery 2023 + Clean Architecture by Max Berktold & Max Steffen
https://docs.flutter.dev/resources/videos/index.html
c11ae5653677-0
Search flutter.dev Search more sites.
https://docs.flutter.dev/search/index.html
f5004dc0938e-0
Search more sites Use this search when you want results from multiple Flutter-related sites. Want only results from flutter.dev? Search flutter.dev.
https://docs.flutter.dev/search-all/index.html
931ea1e23654-0
Security Security philosophy Reporting vulnerabilities Flagging existing issues as security-related Supported versions Expectations Receiving security updates Best practices The Flutter team takes the security of Flutter and the applications created with it seriously. This page describes how to report any vulnerabilities you might find, and lists best practices to minimize the risk of introducing a vulnerability. Security philosophy Flutter security strategy is based on five key pillars: Identify: Track and prioritize key security risks by identifying core assets, key threats, and vulnerabilities. Detect: Detect and identify vulnerabilities using techniques and tools like vulnerability scanning, static application security testing, and fuzzing. Protect: Eliminate risks by mitigating known vulnerabilities and protect critical assets against source threats.
https://docs.flutter.dev/security/index.html
931ea1e23654-1
Respond: Define processes to report, triage, and respond to vulnerabilities or attacks. Recover: Build capabilities to contain and recover from an incident with minimal impact. Reporting vulnerabilities Before reporting a security vulnerability found by a static analysis tool, consider checking our list of known false positives. To report a vulnerability, email [email protected] with a description of the issue, the steps you took to create the issue, affected versions, and if known, mitigations for the issue. We should reply within three working days. We use GitHub’s security advisory feature to track open security issues. You should expect a close collaboration as we work to resolve the issue that you have reported.
https://docs.flutter.dev/security/index.html
931ea1e23654-2
Please reach out to [email protected] again if you don’t receive prompt attention and regular updates. You might also reach out to the team using our public Discord chat channels; however, when reporting an issue, e-mail [email protected]. To avoid revealing information about vulnerabilities in public that could put users at risk, don’t post to Discord or file a GitHub issue. For more details on how we handle security vulnerabilities, see our security policy. Flagging existing issues as security-related If you believe that an existing issue is security-related, we ask that you send an email to [email protected]. The email should include the issue ID and a short description of why it should be handled according to this security policy. Supported versions We commit to publishing security updates for the version of Flutter currently on the stable branch. Expectations
https://docs.flutter.dev/security/index.html
931ea1e23654-3
Expectations We treat security issues equivalent to a P0 priority level and release a beta or hotfix for any major security issues found in the most recent stable version of our SDK. Any vulnerability reported for flutter websites like docs.flutter.dev doesn’t require a release and will be fixed in the website itself. Flutter doesn’t have a bug bounty program. Receiving security updates The best way to receive security updates is to subscribe to the flutter-announce mailing list or watch updates to the Discord channel. We also announce security updates in the technical release blog post. Best practices Keep current with the latest Flutter SDK releases. We regularly update Flutter, and these updates might fix security defects discovered in previous versions. Check the Flutter change log for security-related updates.
https://docs.flutter.dev/security/index.html
931ea1e23654-4
Keep your application’s dependencies up to date. Make sure you upgrade your package dependencies to keep the dependencies up to date. Avoid pinning to specific versions for your dependencies and, if you do, make sure you check periodically to see if your dependencies have had security updates, and update the pin accordingly. Keep your copy of Flutter up to date. Private, customized versions of Flutter tend to fall behind the current version and might not include important security fixes and enhancements. Instead, routinely update your copy of Flutter. If you’re making changes to improve Flutter, be sure to update your fork and consider sharing your changes with the community.
https://docs.flutter.dev/security/index.html
83d1db1f5c0d-0
Google uses cookies to deliver its services, to personalize ads, and to analyze traffic. You can adjust your privacy controls anytime in your Google settings. Learn more. Get started 1. Install 2. Set up an editor 3. Test drive 4. Write your first app 5. Learn more From another platform? Flutter for Android devs Flutter for SwiftUI devs Flutter for UIKit devs Flutter for React Native devs Flutter for web devs Flutter for Xamarin.Forms devs
https://docs.flutter.dev/subscribe/preferences/index.html
83d1db1f5c0d-1
Flutter for Xamarin.Forms devs Introduction to declarative UI Dart language overview open_in_new Samples & tutorials Flutter Gallery [running app] open_in_new Flutter Gallery [repo] open_in_new Sample apps on GitHub open_in_new Cookbook Codelabs Tutorials Development User interface Introduction to widgets
https://docs.flutter.dev/subscribe/preferences/index.html
83d1db1f5c0d-2
Building layouts Layouts in Flutter Tutorial Creating adaptive and responsive apps Building adaptive apps Understanding constraints Box constraints Adding interactivity Assets and images Material Design
https://docs.flutter.dev/subscribe/preferences/index.html
83d1db1f5c0d-3
Material Design Navigation & routing Navigation in Flutter Deep linking URL strategies Animations Introduction Overview Tutorial Implicit animations Hero animations Staggered animations Advanced UI Actions & shortcuts Fonts & typography Keyboard focus system Gestures Shaders Slivers Widget catalog
https://docs.flutter.dev/subscribe/preferences/index.html
83d1db1f5c0d-4
Data & backend State management Introduction Think declaratively Ephemeral vs app state Simple app state management Options Networking & http JSON and serialization Firebase Accessibility & internationalization Accessibility Internationalization Platform integration Supported platforms Building desktop apps with Flutter Writing platform-specific code
https://docs.flutter.dev/subscribe/preferences/index.html
83d1db1f5c0d-5
Android Adding a splash screen C interop Hosting native Android views AndroidX migration Deprecated Splash Screen API Migration Targeting ChromeOS with Android iOS Leveraging Apple's system libraries Adding a splash screen Adding iOS App Clip support Adding iOS app extensions
https://docs.flutter.dev/subscribe/preferences/index.html
83d1db1f5c0d-6
Adding iOS app extensions C interop Hosting native iOS views iOS debugging Linux Building Linux apps macOS Building macOS apps C interop Web Building web apps Web FAQ
https://docs.flutter.dev/subscribe/preferences/index.html
83d1db1f5c0d-7
Web FAQ Web renderers Custom app initialization Displaying images on the web Windows Building Windows apps Run loop migration Version information migration Dark mode migration Packages & plugins Background processes
https://docs.flutter.dev/subscribe/preferences/index.html
83d1db1f5c0d-8
Developing packages & plugins Flutter Favorites program Happy paths project Happy paths recommendations Plugins in Flutter tests Using packages Package site open_in_new Add Flutter to an existing app Introduction Adding to an Android app Project setup Add a single Flutter screen Add a Flutter Fragment Add a Flutter View Plugin setup Adding to an iOS app Project setup Add a single Flutter screen Debugging & hot reload
https://docs.flutter.dev/subscribe/preferences/index.html
83d1db1f5c0d-9
Loading sequence and performance Multiple Flutter instances Tools & features Android Studio & IntelliJ Visual Studio Code
https://docs.flutter.dev/subscribe/preferences/index.html
83d1db1f5c0d-10
Visual Studio Code DevTools Overview Install from Android Studio & IntelliJ Install from VS Code Install from command line Flutter inspector Performance view CPU Profiler view Memory view Network view Debugger Logging view App size tool Release notes Flutter SDK Overview Upgrading Releases Breaking changes Release notes Flutter and the pubspec file Hot reload Flutter Fix Code formatting
https://docs.flutter.dev/subscribe/preferences/index.html
83d1db1f5c0d-11
Flutter Fix Code formatting Testing & debugging Debugging tools Testing plugins **NEW** Debugging apps programmatically Using an OEM debugger Flutter's build modes Common Flutter errors Handling errors Testing Integration testing Migrating from flutter_driver Performance & optimization Overview Performance best practices App size Deferred components Rendering performance
https://docs.flutter.dev/subscribe/preferences/index.html
83d1db1f5c0d-12
Rendering performance Performance profiling Shader compilation jank Performance metrics Performance FAQ Appendix Deployment Obfuscating Dart code Creating flavors for Flutter Build and release an Android app Build and release an iOS app Build and release a macOS app Build and release a Linux app Build and release a Windows app Build and release a web app Continuous deployment Resources Architectural overview
https://docs.flutter.dev/subscribe/preferences/index.html
83d1db1f5c0d-13
Resources Architectural overview Books Compatibility policy Contributing to Flutter open_in_new Creating useful bug reports Dart resources Design documents FAQ Casual Games Toolkit Google Fonts package open_in_new Inside Flutter Flutter vs. Swift Concurrency Official brand assets open_in_new Platform adaptations Videos and online courses Reference
https://docs.flutter.dev/subscribe/preferences/index.html
83d1db1f5c0d-14
Videos and online courses Reference Who is Dash? Widget index API reference open_in_new flutter CLI reference Security false positives Package site open_in_new Multi-Platform Mobile Web Desktop Embedded Development Learn Flutter Favorites Packages Ecosystem Community Events Monetization Showcase Docs What's new Editor support Hot reload Profiling Install Flutter DevTools Cookbook Tutorials Get started
https://docs.flutter.dev/subscribe/preferences/index.html
83d1db1f5c0d-15
Get started Subscription preferences Update your experience level. By using this service, you agree to be bound by our Google Terms of Service. I acknowledge that the information provided in this form will be subject to Google's Privacy Policy terms brand usage security privacy español 社区中文资源 We stand in solidarity with the Black community. Black Lives Matter. Except as otherwise noted, this work is licensed under a Creative Commons Attribution 4.0 International License, and code samples are licensed under the BSD License.
https://docs.flutter.dev/subscribe/preferences/index.html
0c85a43415b0-0
Flutter's build modes Debug Release Profile The Flutter tooling supports three modes when compiling your app, and a headless mode for testing. You choose a compilation mode depending on where you are in the development cycle. Are you debugging your code? Do you need profiling information? Are you ready to deploy your app? A quick summary for when to use which mode is as follows: Use debug mode during development, when you want to use hot reload. Use profile mode when you want to analyze performance. Use release mode when you are ready to release your app. The rest of the page goes into more detail about these modes. For information on headless testing, see the Flutter wiki. Debug In debug mode, the app is set up for debugging on the physical device, emulator, or simulator. Debug mode for mobile apps mean that:
https://docs.flutter.dev/testing/build-modes/index.html
0c85a43415b0-1
Debug mode for mobile apps mean that: Assertions are enabled. Service extensions are enabled. Compilation is optimized for fast development and run cycles (but not for execution speed, binary size, or deployment). Debugging is enabled, and tools supporting source level debugging (such as DevTools) can connect to the process. Debug mode for a web app means that: The build is not minified and tree shaking has not been performed. The app is compiled with the dartdevc compiler for easier debugging. By default, flutter run compiles to debug mode. Your IDE supports this mode. Android Studio, for example, provides a Run > Debug… menu option, as well as a green bug icon overlayed with a small triangle on the project page. Note: Hot reload works only in debug mode. The emulator and simulator execute only in debug mode.
https://docs.flutter.dev/testing/build-modes/index.html
0c85a43415b0-2
The emulator and simulator execute only in debug mode. Application performance can be janky in debug mode. Measure performance in profile mode on an actual device. Release Use release mode for deploying the app, when you want maximum optimization and minimal footprint size. For mobile, release mode (which is not supported on the simulator or emulator), means that: Assertions are disabled. Debugging information is stripped out. Debugging is disabled. Compilation is optimized for fast startup, fast execution, and small package sizes. Service extensions are disabled. Release mode for a web app means that: The build is minified and tree shaking has been performed. The app is compiled with the dart2js compiler for best performance.
https://docs.flutter.dev/testing/build-modes/index.html
0c85a43415b0-3
The app is compiled with the dart2js compiler for best performance. The command flutter run --release compiles to release mode. Your IDE supports this mode. Android Studio, for example, provides a Run > Run… menu option, as well as a triangular green run button icon on the project page. You can compile to release mode for a specific target with flutter build <target>. For a list of supported targets, use flutter help build. For more information, see the docs on releasing iOS and Android apps. Profile In profile mode, some debugging ability is maintained—enough to profile your app’s performance. Profile mode is disabled on the emulator and simulator, because their behavior is not representative of real performance. On mobile, profile mode is similar to release mode, with the following differences: Some service extensions, such as the one that enables the performance overlay, are enabled.
https://docs.flutter.dev/testing/build-modes/index.html
0c85a43415b0-4
Some service extensions, such as the one that enables the performance overlay, are enabled. Tracing is enabled, and tools supporting source-level debugging (such as DevTools) can connect to the process. Profile mode for a web app means that: The build is not minified but tree shaking has been performed. The app is compiled with the dart2js compiler. DevTools can’t connect to a Flutter web app running in profile mode. Use Chrome DevTools to generate timeline events for a web app. Your IDE supports this mode. Android Studio, for example, provides a Run > Profile… menu option. The command flutter run --profile compiles to profile mode. Note: Use the DevTools suite to profile your app’s performance. For more information on the build modes, see Flutter’s build modes.
https://docs.flutter.dev/testing/build-modes/index.html
bb96dfeb6456-0
Debugging Flutter apps programmatically Logging Setting breakpoints Debug flags: application layers Widget tree Render tree Layer tree Semantics tree Scheduling Debug flags: layout Debugging animations Debug flags: performance Tracing Dart code performance Performance overlay Widget alignment grid This doc describes debugging features that you can enable in code. For a full list of debugging and profiling tools, see the Debugging page. Note: If you are looking for a way to use GDB to remotely debug the Flutter engine running within an Android app process, check out flutter_gdb. Logging Note: You can view logs in DevTools’ Logging view or in your system console. This sections shows how to set up your logging statements.
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-1
If you output too much at once, then Android sometimes discards some log lines. To avoid this, use debugPrint(), from Flutter’s foundation library. This is a wrapper around print that throttles the output to a level that avoids being dropped by Android’s kernel. The other option for application logging is to use the dart:developer log() function. This allows you to include a bit more granularity and information in the logging output. Here’s an example: You can also pass application data to the log call. The convention for this is to use the error: named parameter on the log() call, JSON encode the object you want to send, and pass the encoded string to the error parameter. If viewing the logging output in DevTool’s logging view, the JSON encoded error param is interpreted as a data object and rendered in the details view for that log entry. Setting breakpoints
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-2
Setting breakpoints Note: You can set breakpoints in DevTools’ Debugger, or in the built-in debugger of your IDE. If you want to set breakpoints programmatically, use the following instructions. You can insert programmatic breakpoints using the debugger() statement. To use this, you have to import the dart:developer package at the top of the relevant file. The debugger() statement takes an optional when argument that you can specify to only break when a certain condition is true, as in the following example: Debug flags: application layers Each layer of the Flutter framework provides a function to dump its current state or events to the console (using debugPrint). Widget tree
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-3
Widget tree To dump the state of the Widgets library, call debugDumpApp(). You can call this more or less any time that the application is not in the middle of running a build phase (in other words, not anywhere inside a build() method), if the app has built at least once and is in debug mode (in other words, any time after calling runApp()). For example, the following application: The previous app outputs something like the following (the precise details vary by the version of the framework, the size of the device, and so forth): This is the “flattened” tree, showing all the widgets projected through their various build functions. (This is the tree you obtain if you call toStringDeep() on the root of the widget tree.) You’ll see a lot of widgets in there that don’t appear in your application’s source, because they are inserted by the framework’s widgets’ build functions. For example, InkFeature is an implementation detail of the Material widget.
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-4
Since the debugDumpApp() call is invoked when the button changes from being pressed to being released, it coincides with the TextButton object calling setState() and thus marking itself dirty. That is why, when you look at the dump you should see that specific object marked as “dirty”. You can also see what gesture listeners have been registered; in this case, a single GestureDetector is listed, and it is listening only to a “tap” gesture (“tap” is the output of a TapGestureDetector’s toStringShort function). If you write your own widgets, you can add information by overriding debugFillProperties(). Add DiagnosticsProperty objects to the method’s argument, and call the superclass method. This function is what the toString method uses to fill in the widget’s description. Render tree
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-5
Render tree If you are trying to debug a layout issue, then the Widgets layer’s tree might be insufficiently detailed. In that case, you can dump the rendering tree by calling debugDumpRenderTree(). As with debugDumpApp(), you can call this more or less any time except during a layout or paint phase. As a general rule, calling it from a frame callback or an event handler is the best solution. To call debugDumpRenderTree(), you need to add import 'package:flutter/rendering.dart'; to your source file. The output for the previous tiny example would look something like the following: This is the output of the root RenderObject object’s toStringDeep() function. When debugging layout issues, the key fields to look at are the size and constraints fields. The constraints flow down the tree, and the sizes flow back up. RenderPositionedBox to be the size of the screen, with constraints of
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-6
RenderPositionedBox to be the size of the screen, with constraints of Center widget (as described by the RenderPadding, further inserts these constraints to ensure there is room for the padding, and thus the RenderConstrainedBox has a loose constraint of TextButton’s definition, sets a minimum width of 88 pixels on its contents and a specific height of 36.0. (This is the The inner-most RenderPositionedBox loosens the constraints again, this time to center the text within the button. The RenderParagraph picks its size based on its contents. If you now follow the sizes back up the chain, you’ll see how the text’s size is what influences the width of all the boxes that form the button, as they all take their child’s dimensions to size themselves.
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-7
Another way to notice this is by looking at the “relayoutSubtreeRoot” part of the descriptions of each box, which essentially tells you how many ancestors depend on this element’s size in some way. Thus the RenderParagraph has a relayoutSubtreeRoot=up8, meaning that when the RenderParagraph is dirtied, eight ancestors also have to be dirtied because they might be affected by the new dimensions. If you write your own render objects, you can add information to the dump by overriding debugFillProperties(). Add DiagnosticsProperty objects to the method’s argument, and call the superclass method. Layer tree If you are trying to debug a compositing issue, you can use debugDumpLayerTree(). For the previous example, it would output: This is the output of calling toStringDeep on the root Layer object.
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-8
This is the output of calling toStringDeep on the root Layer object. The transform at the root is the transform that applies the device pixel ratio; in this case, a ratio of 3.5 device pixels for every logical pixel. The RepaintBoundary widget, which creates a RenderRepaintBoundary in the render tree, creates a new layer in the layer tree. This is used to reduce how much needs to be repainted. Semantics tree You can also obtain a dump of the Semantics tree (the tree presented to the system accessibility APIs) using debugDumpSemanticsTree(). To use this, you have to have first enable accessibility, for example, by enabling a system accessibility tool or the SemanticsDebugger. For the previous example, it would output the following: Scheduling
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-9
For the previous example, it would output the following: Scheduling To find out where your events happen relative to the frame’s begin/end, you can toggle the debugPrintBeginFrameBanner and the debugPrintEndFrameBanner booleans to print the beginning and end of the frames to the console. For example: The debugPrintScheduleFrameStacks flag can also be used to print the call stack causing the current frame to be scheduled. Debug flags: layout You can also debug a layout problem visually, by setting debugPaintSizeEnabled to true. This is a boolean from the rendering library. It can be enabled at any time and affects all painting while it is true. The easiest way to set it is at the top of your void main() entry point. See an example in the following code:
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-10
When it is enabled, all boxes get a bright teal border, padding (from widgets like Padding) is shown in faded blue with a darker blue box around the child, alignment (from widgets like Center and Align) is shown with yellow arrows, and spacers (from widgets like Container when they have no child) are shown in gray. The debugPaintBaselinesEnabled flag does something similar but for objects with baselines. The alphabetic baseline is shown in bright green and the ideographic baseline in orange. The debugPaintPointersEnabled flag turns on a special mode whereby any objects that are being tapped get highlighted in teal. This can help you determine whether an object is somehow failing to correctly hit test (which might happen if, for instance, it is actually outside the bounds of its parent and thus not being considered for hit testing in the first place).
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-11
If you’re trying to debug compositor layers, for example to determine whether and where to add RepaintBoundary widgets, you can use the debugPaintLayerBordersEnabled flag, which outlines each layer’s bounds in orange, or the debugRepaintRainbowEnabled flag, which causes layers to be overlayed with a rotating set of colors whenever they are repainted. All of these flags only work in debug mode. In general, anything in the Flutter framework that starts with “debug...” only works in debug mode. Debugging animations Note: The easiest way to debug animations is to slow them down. You can do this using the Slow Animations button in DevTools’ Inspector view, which slows down the animation by 5x. If you want more control over the amount of slowness, use the following instructions.
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-12
Set the timeDilation variable (from the scheduler library) to a number greater than 1.0, for instance, 50.0. It’s best to only set this once on app startup. If you change it on the fly, especially if you reduce it while animations are running, it’s possible that the framework will observe time going backwards, which will probably result in asserts and generally interfere with your efforts. Debug flags: performance Note: You can achieve similar results to some of these debug flags using DevTools. Some of the debug flags aren’t particularly useful. If you find a flag that has functionality you would like to see added to DevTools, please file an issue.
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-13
Flutter provides a wide variety of debug flags and functions to help you debug your app at various points along the development cycle. To use these features, you must compile in debug mode. The following list, while not complete, highlights some of flags (and one function) from the rendering library for debugging performance issues. You can set these flags either by editing the framework code, or by importing the module and setting the value in your main() method, following by a hot restart. debugDumpRenderTree() Call this function when not in a layout or repaint phase to dump the rendering tree to the console. (Pressing t from flutter run calls this command.) Search for “RepaintBoundary” to see diagnostics on how useful a boundary is. debugPaintLayerBordersEnabled PENDING debugRepaintRainbowEnabled
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-14
PENDING debugRepaintRainbowEnabled You can enable this flag in the Flutter inspector by selecting the Highlight Repaints button. If any static widgets are rotating through the colors of the rainbow (for example, a static header), those areas are candidates for adding repaint boundaries. debugPrintMarkNeedsLayoutStacks Enable this flag if you’re seeing more layouts than you expect (for example, on the timeline, on a profile, or from a print statement inside a layout method). Once enabled, the console is flooded with stack traces showing why each render object is being marked dirty for layout. You can use the debugPrintStack() method from the services library to print your own stack traces on demand, if this kind of approach is useful to you. debugPrintMarkNeedsPaintStacks
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-15
debugPrintMarkNeedsPaintStacks Similar to debugPrintMarkNeedsLayoutStacks, but for excess painting. You can use the debugPrintStack() method from the services library to print your own stack traces on demand, if this kind of approach is useful to you. Tracing Dart code performance Note: You can use the DevTools Timeline events chart to perform traces. You can also import and export trace files into the Timeline view, but only files generated by DevTools. To perform custom performance traces programmatically and measure wall/CPU time of arbitrary segments of Dart code similar to what would be done on Android with systrace, use dart:developer Timeline utilities to wrap the code you want to measure such as: import 'dart:developer';
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-16
import 'dart:developer'; void main() { Timeline.startSync('interesting function'); // iWonderHowLongThisTakes(); Timeline.finishSync(); } Then open DevTools’ Timeline events chart while connected to your app, verify the Dart recording option is checked in the Performance settings, and perform the function you want to measure. Be sure to run your app in profile mode to ensure that the runtime performance characteristics closely match that of your final product. Performance overlay Note: You can toggle display of the performance overlay on your app using the Performance Overlay button in the Flutter inspector. If you prefer to do it in code, use the following instructions.
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-17
You can programmatically enable the PerformanceOverlay widget by setting the showPerformanceOverlay property to true on the MaterialApp, CupertinoApp, or WidgetsApp constructor: import 'package:flutter/material.dart'; class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( showPerformanceOverlay: true, title: 'My Awesome App', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'My Awesome App'), ); } } (If you’re not using MaterialApp, CupertinoApp, or WidgetsApp, you can get the same effect by wrapping your application in a stack and putting a widget on your stack that was created by calling PerformanceOverlay.allEnabled().)
https://docs.flutter.dev/testing/code-debugging/index.html
bb96dfeb6456-18
For information on how to interpret the graphs in the overlay, see The performance overlay in Profiling Flutter performance. Widget alignment grid You can programmatically overlay a Material Design baseline grid on top of your app to help verify alignments by using the debugShowMaterialGrid argument in the MaterialApp constructor. In non-Material applications, you can achieve a similar effect by using a GridPaper widget directly.
https://docs.flutter.dev/testing/code-debugging/index.html
76ae2896a3bc-0
Common Flutter errors Introduction ‘A RenderFlex overflowed…’ ‘RenderBox was not laid out’ ‘Vertical viewport was given unbounded height’ ‘An InputDecorator…cannot have an unbounded width’ ‘Incorrect use of ParentData widget’ ‘setState called during build’ References Introduction This page explains several frequently-encountered Flutter framework errors and gives suggestions on how to resolve them. This is a living document with more errors to be added in future revisions, and your contributions are welcomed. Feel free to open an issue or submit a pull request to make this page more useful to you and the Flutter community. ‘A RenderFlex overflowed…’ RenderFlex overflow is one of the most frequently encountered Flutter framework errors, and you probably have run into it already. What does the error look like?
https://docs.flutter.dev/testing/common-errors/index.html
76ae2896a3bc-1
What does the error look like? When it happens, you’ll see yellow & black stripes indicating the area of overflow in the app UI in addition to the error message in the debug console: How might you run into this error? The error often occurs when a Column or Row has a child widget that is not constrained in its size. For example, the code snippet below demonstrates a common scenario: In the above example, the Column tries to be wider than the space the Row (its parent) can allocate to it, causing an overflow error. Why does the Column try to do that? To understand this layout behavior, you need to know how Flutter framework performs layout: “To perform layout, Flutter walks the render tree in a depth-first traversal and passes down size constraints from parent to child… Children respond by passing up a size to their parent object within the constraints the parent established.” – Flutter architectural overview
https://docs.flutter.dev/testing/common-errors/index.html
76ae2896a3bc-2
In this case, the Row widget doesn’t constrain the size of its children, nor does the Column widget. Lacking constraints from its parent widget, the second Text widget tries to be as wide as all the characters it needs to display. The self-determined width of the Text widget then gets adopted by the Column which clashes with the maximum amount of horizontal space its parent the Row widget can provide. How to fix it? Well, you need to make sure the Column won’t attempt to be wider than it can be. To achieve this, you need to constrain its width. One way to do it is to wrap the Column in an Expanded widget: its source code shows. To further understand how to use the this Widget of the Week video on the Flexible widget. Further information: The resources linked below provide further information about this error. Flexible (Flutter Widget of the Week)
https://docs.flutter.dev/testing/common-errors/index.html
76ae2896a3bc-3
Flexible (Flutter Widget of the Week) How to debug layout issues with the Flutter Inspector Understanding constraints ‘RenderBox was not laid out’ While this error is pretty common, it’s often a side effect of a primary error occurring earlier in the rendering pipeline. What does the error look like? The message shown by the error looks like this: How might you run into this error? Usually, the issue is related to violation of box constraints, and it needs to be solved by providing more information to Flutter about how you’d like to constrain the widgets in question. You can learn more about how constraints work in Flutter on the page Understanding constraints. The RenderBox was not laid out error is often caused by one of two other errors: ‘Vertical viewport was given unbounded height’ ‘An InputDecorator…cannot have an unbounded width’
https://docs.flutter.dev/testing/common-errors/index.html
76ae2896a3bc-4
‘An InputDecorator…cannot have an unbounded width’ ‘Vertical viewport was given unbounded height’ This is another common layout error you could run into while creating a UI in your Flutter app. What does the error look like? The message shown by the error looks like this: How might you run into this error? How to fix it? To fix this error, specify how tall the ListView should be. To make it as tall as the remaining space in the Column, wrap it using an Expanded widget (see the example below). Otherwise, specify an absolute height using a SizedBox widget or a relative height using a Flexible widget. Further information: The resources linked below provide further information about this error. How to debug layout issues with the Flutter Inspector Understanding constraints ‘An InputDecorator…cannot have an unbounded width’
https://docs.flutter.dev/testing/common-errors/index.html