id
stringlengths 14
17
| text
stringlengths 23
1.11k
| source
stringlengths 35
114
|
---|---|---|
37192cb37310-5 | If indeed all that is needed is a callback, without all the complexity (or
flexibility) of Actions and Shortcuts, you can already use a Focus widget
for this. For example, here’s the implementation of Flutter’s simple
CallbackShortcuts widget that takes a map of activators and executes
callbacks for them:
This may be all that is needed for some apps.
Shortcuts
As you’ll see below, actions are useful on their own, but the most common use
case involves binding them to a keyboard shortcut. This is what the Shortcuts
widget is for.
The ShortcutManager
The shortcut manager, a longer-lived object than the Shortcuts widget, passes
on key events when it receives them. It contains the logic for deciding how to
handle the keys, the logic for walking up the tree to find other shortcut
mappings, and maintains a map of key combinations to intents. | https://docs.flutter.dev/development/ui/advanced/actions-and-shortcuts/index.html |
37192cb37310-6 | While the default behavior of the ShortcutManager is usually desirable, the
Shortcuts widget takes a ShortcutManager that you can subclass to customize
its functionality.
For example, if you wanted to log each key that a Shortcuts widget handled,
you could make a LoggingShortcutManager:
Now, every time the Shortcuts widget handles a shortcut, it prints out the key
event and relevant context.
Actions
Actions allow for the definition of operations that the application can
perform by invoking them with an Intent. Actions can be enabled or disabled,
and receive the intent instance that invoked them as an argument to allow
configuration by the intent.
Defining actions
Actions, in their simplest form, are just subclasses of Action<Intent> with an
invoke() method. Here’s a simple action that simply invokes a function on the
provided model:
Or, if it’s too much of a bother to create a new class, use a CallbackAction: | https://docs.flutter.dev/development/ui/advanced/actions-and-shortcuts/index.html |
37192cb37310-7 | Once you have an action, you add it to your application using the Actions
widget, which takes a map of Intent types to Actions:
Invoking Actions
The actions system has several ways to invoke actions. By far the most common
way is through the use of a Shortcuts widget covered in the previous section,
but there are other ways to interrogate the actions subsystem and invoke an
action. It’s possible to invoke actions that are not bound to keys.
For instance, to find an action associated with an intent, you can use:
To invoke the action (if it exists), call:
Combine that into one call with the following:
Sometimes you want to invoke an action as a result of pressing a button or
another control. Do this with the Actions.handler function, which creates a
handler closure if the intent has a mapping to an enabled action, and returns
null if it doesn’t, so that the button is disabled if there is no matching
enabled action in the context: | https://docs.flutter.dev/development/ui/advanced/actions-and-shortcuts/index.html |
37192cb37310-8 | The Actions widget only invokes actions when isEnabled(Intent intent)
returns true, allowing the action to decide if the dispatcher should consider it
for invocation. If the action isn’t enabled, then the Actions widget gives
another enabled action higher in the widget hierarchy (if it exists) a chance to
execute.
You can invoke an action without needing a BuildContext, but since the
Actions widget requires a context to find an enabled action to invoke, you
need to provide one, either by creating your own Action instance, or by
finding one in an appropriate context with Actions.find.
Action dispatchers
Most of the time, you just want to invoke an action, have it do its thing, and
forget about it. Sometimes, however, you might want to log the executed actions. | https://docs.flutter.dev/development/ui/advanced/actions-and-shortcuts/index.html |
37192cb37310-9 | This is where replacing the default ActionDispatcher with a custom dispatcher
comes in. You pass your ActionDispatcher to the Actions widget, and it
invokes actions from any Actions widgets below that one that doesn’t set a
dispatcher of its own.
The first thing Actions does when invoking an action is look up the
ActionDispatcher and pass the action to it for invocation. If there is none,
it creates a default ActionDispatcher that simply invokes the action.
If you want a log of all the actions invoked, however, you can create your own
LoggingActionDispatcher to do the job:
Then you pass that to your top-level Actions widget:
This logs every action as it executes, like so:
Putting it together | https://docs.flutter.dev/development/ui/advanced/actions-and-shortcuts/index.html |
37192cb37310-10 | Putting it together
The combination of Actions and Shortcuts is powerful: you can define generic
intents that map to specific actions at the widget level. Here’s a simple app
that illustrates the concepts described above. The app creates a text field that
also has “select all” and “copy to clipboard” buttons next to it. The buttons
invoke actions to accomplish their work. All the invoked actions and
shortcuts are logged. | https://docs.flutter.dev/development/ui/advanced/actions-and-shortcuts/index.html |
be7162bf47f0-0 | Understanding Flutter's keyboard focus system
UI
Advanced
Understanding Flutter's keyboard focus system
Overview
Focus use cases
Glossary
FocusNode and FocusScopeNode
Best practices for creating FocusNode objects
Unfocusing
Focus widget
Key events
Controlling what gets focus
Autofocus
Change notifications
Obtaining the FocusNode
Timing
FocusScope widget
FocusableActionDetector widget
Controlling focus traversal
FocusTraversalGroup widget
FocusTraversalPolicy
The focus manager | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-1 | The focus manager
This article explains how to control where keyboard input is directed. If you
are implementing an application that uses a physical keyboard, such as most
desktop and web applications, this page is for you. If your app won’t be used
with a physical keyboard, you can skip this.
Overview
Flutter comes with a focus system that directs the keyboard input to a
particular part of an application. In order to do this, users “focus” the input
onto that part of an application by tapping or clicking the desired UI element.
Once that happens, text entered with the keyboard flows to that part of the
application until the focus moves to another part of the application. Focus can
also be moved by pressing a particular keyboard shortcut, which is typically
bound to the Tab key, so it is sometimes called “tab traversal”. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-2 | This page explores the APIs used to perform these operations on a Flutter
application, and how the focus system works. We have noticed that there is some
confusion among developers about how to define and use FocusNode objects.
If that describes your experience, skip ahead to the best practices for
creating FocusNode objects.
Focus use cases
Some examples of situations where you might need to know how to use the focus
system:
Receiving/handling key events
Implementing a custom component that needs to be focusable
Receiving notifications when the focus changes
Changing or defining the “tab order” of focus traversal in an application
Defining groups of controls that should be traversed together
Preventing some controls in an application from being focusable
Glossary
Below are terms, as Flutter uses them, for elements of the focus system. The
various classes that implement some of these concepts are introduced below. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-3 | Focus tree - A tree of focus nodes that typically sparsely mirrors the
widget tree, representing all the widgets that can receive focus.
Focus node - A single node in a focus tree. This node can receive the
focus, and is said to “have focus” when it is part of the focus chain. It
participates in handling key events only when it has focus.
Primary focus - The farthest focus node from the root of the focus tree
that has focus. This is the focus node where key events start propagating to
the primary focus node and its ancestors.
Focus chain - An ordered list of focus nodes that starts at the primary
focus node and follows the branches of the focus tree to the root of the
focus tree.
Focus scope - A special focus node whose job is to contain a group of
other focus nodes, and allow only those nodes to receive focus. It contains
information about which nodes were previously focused in its subtree. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-4 | Focus traversal - The process of moving from one focusable node to
another in a predictable order. This is typically seen in applications when
the user presses the Tab key to move to the next focusable control or
field.
FocusNode and FocusScopeNode
The FocusNode and FocusScopeNode objects implement the
mechanics of the focus system. They are long-lived objects (longer than widgets,
similar to render objects) that hold the focus state and attributes so that they
are persistent between builds of the widget tree. Together, they form
the focus tree data structure. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-5 | They were originally intended to be developer-facing objects used to control
some aspects of the focus system, but over time they have evolved to mostly
implement details of the focus system. In order to prevent breaking existing
applications, they still contain public interfaces for their attributes. But, in
general, the thing for which they are most useful is to act as a relatively
opaque handle, passed to a descendant widget in order to call requestFocus()
on an ancestor widget, which requests that a descendant widget obtain focus.
Setting of the other attributes is best managed by a Focus or
FocusScope widget, unless you are not using them, or implementing your own
version of them.
Best practices for creating FocusNode objects
Some dos and don’ts around using these objects include:
Don’t allocate a new FocusNode for each build. This can cause
memory leaks, and occasionally causes a loss of focus when the widget
rebuilds while the node has focus. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-6 | Do create FocusNode and FocusScopeNode objects in a stateful widget.
FocusNode and FocusScopeNode need to be disposed of when you’re done
using them, so they should only be created inside of a stateful widget’s
state object, where you can override dispose to dispose of them.
Don’t use the same FocusNode for multiple widgets. If you do, the
widgets will fight over managing the attributes of the node, and you
probably won’t get what you expect.
Do set the debugLabel of a focus node widget to help with diagnosing
focus issues. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-7 | Do set the debugLabel of a focus node widget to help with diagnosing
focus issues.
Don’t set the onKey callback on a FocusNode or FocusScopeNode if
they are being managed by a Focus or FocusScope widget. If you want an
onKey handler, then add a new Focus widget around the widget subtree you
would like to listen to, and set the onKey attribute of the widget to your
handler. Set canRequestFocus: false on the widget if you also don’t want
it to be able to take primary focus. This is because the onKey attribute
on the Focus widget can be set to something else in a subsequent build,
and if that happens, it overwrites the onKey handler you set on the node.
Do call requestFocus() on a node to request that it receives the
primary focus, especially from an ancestor that has passed a node it owns to
a descendant where you want to focus. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-8 | Do use focusNode.requestFocus(). It is not necessary to call
FocusScope.of(context).requestFocus(focusNode). The
focusNode.requestFocus() method is equivalent and more performant.
Unfocusing
UnfocusDisposition.scope and
The previouslyFocusedChild disposition will search the scope to find the
previously focused child and request focus on it. If there is no previously
focused child, it is equivalent to scope.
Focus widget
The Focus widget owns and manages a focus node, and is the workhorse of the
focus system. It manages the attaching and detaching of the focus node it owns
from the focus tree, manages the attributes and callbacks of the focus node, and
has static functions to enable discovery of focus nodes attached to the widget
tree. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-9 | In its simplest form, wrapping the Focus widget around a widget subtree allows
that widget subtree to obtain focus as part of the focus traversal process, or
whenever requestFocus is called on the FocusNode passed to it. When combined
with a gesture detector that calls requestFocus, it can receive focus when
tapped or clicked.
The Focus widget is used in most of Flutter’s own controls to implement their
focus functionality.
Here is an example showing how to use the Focus widget to make a custom
control focusable. It creates a container with text that reacts to receiving the
focus.
Key events
If you wish to listen for key events in a subtree, set the onKey attribute of
the Focus widget to be a handler that either just listens to the key, or
handles the key and stops its propagation to other widgets. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-10 | Key events start at the focus node with primary focus. If that node doesn’t
return KeyEventResult.handled from its onKey handler, then its parent focus
node is given the event. If the parent doesn’t handle it, it goes to its parent,
and so on, until it reaches the root of the focus tree. If the event reaches the
root of the focus tree without being handled, then it is returned to the
platform to give to the next native control in the application (in case the
Flutter UI is part of a larger native application UI). Events that are handled
are not propagated to other Flutter widgets, and they are also not propagated to
native widgets.
Here’s an example of a Focus widget that absorbs every key that its subtree
doesn’t handle, without being able to be the primary focus:
Focus key events are processed before text entry events, so handling a key event
when the focus widget surrounds a text field prevents that key from being
entered into the text field. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-11 | Here’s an example of a widget that won’t allow the letter “a” to be typed into
the text field:
If the intent is input validation, this example’s functionality would probably
be better implemented using a TextInputFormatter, but the technique can still
be useful: the Shortcuts widget uses this method to handle shortcuts before
they become text input, for instance.
Controlling what gets focus
One of the main aspects of focus is controlling what can receive focus and how.
The attributes canRequestFocus, skipTraversal, and descendantsAreFocusable
control how this node and its descendants participate in the focus process.
If the skipTraversal attribute true, then this focus node doesn’t participate
in focus traversal. It is still focusable if requestFocus is called on its
focus node, but is otherwise skipped when the focus traversal system is looking
for the next thing to focus on. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-12 | The canRequestFocus attribute, unsurprisingly, controls whether or not the
focus node that this Focus widget manages can be used to request focus. If
this attribute is false, then calling requestFocus on the node has no effect.
It also implies that this node is skipped for focus traversal, since it can’t
request focus.
The descendantsAreFocusable attribute controls whether the descendants of this
node can receive focus, but still allows this node to receive focus. This
attribute can be used to turn off focusability for an entire widget subtree.
This is how the ExcludeFocus widget works: it’s just a Focus widget with
this attribute set.
Autofocus
Setting the autofocus attribute of a Focus widget tells the widget to
request the focus the first time the focus scope it belongs to is focused. If
more than one widget has autofocus set, then it is arbitrary which one
receives the focus, so try to only set it on one widget per focus scope. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-13 | The autofocus attribute only takes effect if there isn’t already a focus in
the scope that the node belongs to.
Setting the autofocus attribute on two nodes that belong to different focus
scopes is well defined: each one becomes the focused widget when their
corresponding scopes are focused.
Change notifications
The Focus.onFocusChanged callback can be used to get notifications that the
focus state for a particular node has changed. It notifies if the node is added
to or removed from the focus chain, which means it gets notifications even if it
isn’t the primary focus. If you only want to know if you have received the
primary focus, check and see if hasPrimaryFocus is true on the focus node.
Obtaining the FocusNode
Sometimes, it is useful to obtain the focus node of a Focus widget to
interrogate its attributes. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-14 | To access the focus node from an ancestor of the Focus widget, create and pass
in a FocusNode as the Focus widget’s focusNode attribute. Because it needs
to be disposed of, the focus node you pass needs to be owned by a stateful
widget, so don’t just create one each time it is built.
Builder to make sure you have
the correct context. This is shown in the following example:
Timing
One of the details of the focus system is that when focus is requested, it only
takes effect after the current build phase completes. This means that focus
changes are always delayed by one frame, because changing focus can
cause arbitrary parts of the widget tree to rebuild, including ancestors of the
widget currently requesting focus. Because descendants cannot dirty their
ancestors, it has to happen between frames, so that any needed changes can
happen on the next frame.
FocusScope widget | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-15 | FocusScope widget
The FocusScope widget is a special version of the Focus widget that manages
a FocusScopeNode instead of a FocusNode. The FocusScopeNode is a special
node in the focus tree that serves as a grouping mechanism for the focus nodes
in a subtree. Focus traversal stays within a focus scope unless a node outside
of the scope is explicitly focused.
The focus scope also keeps track of the current focus and history of the nodes
focused within its subtree. That way, if a node releases focus or is removed
when it had focus, the focus can be returned to the node that had focus
previously.
Focus scopes also serve as a place to return focus to if none of the descendants
have focus. This allows the focus traversal code to have a starting context for
finding the next (or first) focusable control to move to. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-16 | If you focus a focus scope node, it first attempts to focus the current, or most
recently focused node in its subtree, or the node in its subtree that requested
autofocus (if any). If there is no such node, it receives the focus itself.
FocusableActionDetector widget
The FocusableActionDetector is a widget that combines the functionality of
Actions, Shortcuts, MouseRegion and a Focus widget to create
a detector that defines actions and key bindings, and provides callbacks for
handling focus and hover highlights. It is what Flutter controls use to
implement all of these aspects of the controls. It is just implemented using the
constituent widgets, so if you don’t need all of its functionality, you can just
use the ones you need, but it is a convenient way to build these behaviors into
your custom controls.
Note:
To learn more, watch this short Widget of the Week video on the FocusableActionDetector widget:
Controlling focus traversal | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-17 | Controlling focus traversal
Once an application has the ability to focus, the next thing many apps want to
do is to allow the user to control the focus using the keyboard or another input
device. The most common example of this is “tab traversal” where the user
presses the Tab key to go to the “next” control. Controlling what “next”
means is the subject of this section. This kind of traversal is provided by
Flutter by default.
In a simple grid layout, it’s fairly easy to decide which control is next. If
you’re not at the end of the row, then it’s the one to the right (or left for
right-to-left locales). If you are at the end of a row, it’s the first control
in the next row. Unfortunately, applications are rarely laid out in grids, so
more guidance is often needed. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-18 | The default algorithm in Flutter (ReadingOrderTraversalPolicy) for focus
traversal is pretty good: It gives the right answer for most applications.
However, there are always pathological cases, or cases where the context or
design requires a different order than the one the default ordering algorithm
arrives at. For those cases, there are other mechanisms for achieving the
desired order.
FocusTraversalGroup widget
The FocusTraversalGroup widget should be placed in the tree around widget
subtrees that should be fully traversed before moving on to another widget or
group of widgets. Just grouping widgets into related groups is often enough to
resolve many tab traversal ordering problems. If not, the group can also be
given a FocusTraversalPolicy to determine the ordering within the group.
ReadingOrderTraversalPolicy is usually sufficient, but in
cases where more control over ordering is needed, an
OrderedTraversalPolicy can be used. The | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-19 | OrderedTraversalPolicy can be used. The
FocusTraversalOrder widget wrapped around the focusable components
determines the order. The order can be any subclass of
FocusOrder, but
NumericFocusOrder and
LexicalFocusOrder are provided.
If none of the provided focus traversal policies are sufficient for your
application, you could also write your own policy and use it to determine any
custom ordering you want.
Here’s an example of how to use the FocusTraversalOrder widget to traverse a
row of buttons in the order TWO, ONE, THREE using NumericFocusOrder.
FocusTraversalPolicy
FocusTraversalPolicy is the abstract base class for concrete policies, like
ReadingOrderTraversalPolicy, OrderedTraversalPolicy and the
DirectionalFocusTraversalPolicyMixin classes. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-20 | In order to use a FocusTraversalPolicy, you give one to a
FocusTraversalGroup, which determines the widget subtree in which the policy
will be effective. The member functions of the class are rarely called directly:
they are meant to be used by the focus system.
The focus manager
The FocusManager maintains the current primary focus for the system. It
only has a few pieces of API that are useful to users of the focus system. One
is the FocusManager.instance.primaryFocus property, which contains the
currently focused focus node and is also accessible from the global
primaryFocus field. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
be7162bf47f0-21 | Other useful properties are FocusManager.instance.highlightMode and
FocusManager.instance.highlightStrategy. These are used by widgets that need
to switch between a “touch” mode and a “traditional” (mouse and keyboard) mode
for their focus highlights. When a user is using touch to navigate, the focus
highlight is usually hidden, and when they switch to a mouse or keyboard, the
focus highlight needs to be shown again so they know what is focused. The
hightlightStrategy tells the focus manager how to interpret changes in the
usage mode of the device: it can either automatically switch between the two
based on the most recent input events, or it can be locked in touch or
traditional modes. The provided widgets in Flutter already know how to use this
information, so you only need it if you’re writing your own controls from
scratch. You can use addHighlightModeListener callback to listen for changes
in the highlight mode. | https://docs.flutter.dev/development/ui/advanced/focus/index.html |
e746f71433fa-0 | Taps, drags, and other gestures
UI
Advanced
Taps, drags, and other gestures
Pointers
Gestures
Adding gesture detection to widgets
Gesture disambiguation
This document explains how to listen for, and respond to,
gestures in Flutter. Examples of gestures include
taps, drags, and scaling.
The gesture system in Flutter has two separate layers.
The first layer has raw pointer events that describe
the location and movement of pointers (for example,
touches, mice, and styli) across the screen.
The second layer has gestures that describe semantic
actions that consist of one or more pointer movements.
Pointers
Pointers represent raw data about the user’s interaction
with the device’s screen.
There are four types of pointer events:
PointerDownEvent
The pointer has contacted the screen at a particular location. | https://docs.flutter.dev/development/ui/advanced/gestures/index.html |
e746f71433fa-1 | The pointer has contacted the screen at a particular location.
PointerMoveEvent
The pointer has moved from one location on the screen to another.
PointerUpEvent
The pointer has stopped contacting the screen.
PointerCancelEvent
Input from this pointer is no longer directed towards this app.
On pointer down, the framework does a hit test on your app
to determine which widget exists at the location where the
pointer contacted the screen. The pointer down event
(and subsequent events for that pointer) are then dispatched
to the innermost widget found by the hit test.
From there, the events bubble up the tree and are dispatched
to all the widgets on the path from the innermost
widget to the root of the tree. There is no mechanism for
canceling or stopping pointer events from being dispatched further. | https://docs.flutter.dev/development/ui/advanced/gestures/index.html |
e746f71433fa-2 | To listen to pointer events directly from the widgets layer, use a
Listener widget. However, generally,
consider using gestures (as discussed below) instead.
Gestures
Gestures represent semantic actions (for example, tap, drag,
and scale) that are recognized from multiple individual pointer
events, potentially even multiple individual pointers.
Gestures can dispatch multiple events, corresponding to the
lifecycle of the gesture (for example, drag start,
drag update, and drag end):
Tap
A pointer that might cause a tap has contacted
the screen at a particular location.
A pointer that will trigger a tap has stopped contacting
the screen at a particular location.
The pointer that previously triggered the onTapDown
has also triggered onTapUp which ends up causing a tap.
The pointer that previously triggered the onTapDown
will not end up causing a tap.
Double tap
The user has tapped the screen at the same location twice in
quick succession. | https://docs.flutter.dev/development/ui/advanced/gestures/index.html |
e746f71433fa-3 | The user has tapped the screen at the same location twice in
quick succession.
Long press
A pointer has remained in contact with the
screen at the same location for a long period of time.
Vertical drag
A pointer has contacted the screen and might begin to
move vertically.
A pointer that is in contact with the screen and
moving vertically has moved in the vertical direction.
A pointer that was previously in contact with the screen
and moving vertically is no longer in contact with the
screen and was moving at a specific velocity when it
stopped contacting the screen.
Horizontal drag
A pointer has contacted the screen and might begin to
move horizontally.
A pointer that is in contact with the screen and
moving horizontally has moved in the horizontal direction. | https://docs.flutter.dev/development/ui/advanced/gestures/index.html |
e746f71433fa-4 | A pointer that was previously in contact with the
screen and moving horizontally is no longer in contact
with the screen and was moving at a specific velocity
when it stopped contacting the screen.
Pan
A pointer has contacted the screen and might begin to move
horizontally or vertically. This callback causes a crash if
onHorizontalDragStart or onVerticalDragStart is set.
A pointer that is in contact with the screen and is moving
in the vertical or horizontal direction. This callback causes
a crash if onHorizontalDragUpdate or onVerticalDragUpdate
is set.
A pointer that was previously in contact with screen
is no longer in contact with the screen and is moving
at a specific velocity when it stopped contacting the screen.
This callback causes a crash if onHorizontalDragEnd or
onVerticalDragEnd is set.
Adding gesture detection to widgets
To listen to gestures from the widgets layer, use a
GestureDetector. | https://docs.flutter.dev/development/ui/advanced/gestures/index.html |
e746f71433fa-5 | To listen to gestures from the widgets layer, use a
GestureDetector.
Note:
To learn more, watch this short Widget of the Week video on the GestureDetector widget:
If you’re using Material Components,
many of those widgets already respond to taps or gestures.
For example, IconButton and TextButton
respond to presses (taps), and ListView
responds to swipes to trigger scrolling.
If you are not using those widgets, but you want the
“ink splash” effect on a tap, you can use InkWell.
Gesture disambiguation
At a given location on screen, there might be multiple gesture
detectors. All of these gesture detectors listen to the stream
of pointer events as they flow past and attempt to recognize
specific gestures. The GestureDetector widget decides
which gestures to attempt to recognize based on which of its
callbacks are non-null. | https://docs.flutter.dev/development/ui/advanced/gestures/index.html |
e746f71433fa-6 | When there is more than one gesture recognizer for a given
pointer on the screen, the framework disambiguates which
gesture the user intends by having each recognizer join
the gesture arena. The gesture arena determines which
gesture wins using the following rules:
At any time, a recognizer can declare defeat and leave the
arena. If there’s only one recognizer left in the arena,
that recognizer is the winner.
At any time, a recognizer can declare victory, which causes
it to win and all the remaining recognizers to lose.
For example, when disambiguating horizontal and vertical dragging,
both recognizers enter the arena when they receive the pointer
down event. The recognizers observe the pointer move events.
If the user moves the pointer more than a certain number of
logical pixels horizontally, the horizontal recognizer
declares victory and the gesture is interpreted as a horizontal
drag. Similarly, if the user moves more than a certain number
of logical pixels vertically, the vertical recognizer declares victory. | https://docs.flutter.dev/development/ui/advanced/gestures/index.html |
e746f71433fa-7 | The gesture arena is beneficial when there is only a horizontal
(or vertical) drag recognizer. In that case, there is only one
recognizer in the arena and the horizontal drag is recognized
immediately, which means the first pixel of horizontal movement
can be treated as a drag and the user won’t need to wait for
further gesture disambiguation. | https://docs.flutter.dev/development/ui/advanced/gestures/index.html |
296362747b7b-0 | Advanced UI
UI
Advanced
Topics:
Actions & shortcuts
Fonts & typography
Keyboard focus system
Gestures
Shaders
Slivers | https://docs.flutter.dev/development/ui/advanced/index.html |
bd7144d62229-0 | Writing and using fragment shaders
UI
Advanced
Fragment shaders
Adding shaders to an application
Loading shaders at runtime
Canvas API
Authoring shaders
Uniforms
Current position
Colors
Samplers
Performance considerations
Other resources
Note:
The CanvasKit backend supports this feature on the beta branch
and should support this API in the next stable release.
There are no current plans to support this feature in the HTML backend.
Custom shaders can be used to provide rich graphical effects
beyond those provided by the Flutter SDK.
A shader is a program authored in a small, Dart-like language,
known as GLSL,
and executed on the user’s GPU.
Custom shaders are added to a Flutter project
by listing them in the pubspec.yaml file,
and obtained using the FragmentProgram API. | https://docs.flutter.dev/development/ui/advanced/shaders/index.html |
bd7144d62229-1 | Adding shaders to an application
Shaders, in the form of GLSL files with the .frag extension,
must be declared in the shaders section of your project’s pubspec.yaml file.
The Flutter command-line tool compiles the shader to its appropriate backend format,
and generates its necessary runtime metadata.
The compiled shader is then included in the application just like an asset.
flutter
shaders
shaders/myshader.frag
When running in debug mode,
changes to a shader program trigger recompilation
and update the shader during hot reload or hot restart.
Shaders from packages are added to a project
with packages/$pkgname prefixed to the shader program’s name
(where $pkgname is the name of the package).
Loading shaders at runtime | https://docs.flutter.dev/development/ui/advanced/shaders/index.html |
bd7144d62229-2 | Loading shaders at runtime
To load a shader into a FragmentProgram object at runtime,
use the FragmentProgram.fromAsset constructor.
The asset’s name is the same as the path to the shader given in the pubspec.yaml file.
void
loadMyShader
()
async
var
program
await
FragmentProgram
fromAsset
'shaders/myshader.frag'
);
The FragmentProgram object can be used to create one or more FragmentShader instances.
A FragmentShader object represents a fragment program
along with a particular set of uniforms (configuration parameters).
The available uniforms depends on how the shader was defined.
void
updateShader
Canvas
canvas
Rect
rect
FragmentProgram | https://docs.flutter.dev/development/ui/advanced/shaders/index.html |
bd7144d62229-3 | Rect
rect
FragmentProgram
program
var
shader
program
createShader
();
shader
setFloat
42.0
);
canvas
drawRect
rect
Paint
().
shader
shader
);
Canvas API
Fragment shaders can be used with most Canvas APIs by setting Paint.shader.
For example, when using Canvas.drawRect the shader is evaluated for all
fragments within the rectangle. For an API like Canvas.drawPath with a
stroked path, the shader is evaluated for all fragments within the stroked
line. Some APIs, such as Canvas.drawImage, ignore the value of the shader. | https://docs.flutter.dev/development/ui/advanced/shaders/index.html |
bd7144d62229-4 | void
paint
Canvas
canvas
Size
size
FragmentShader
shader
// Draws a rectangle with the shader used as a color source.
canvas
drawRect
Rect
fromLTWH
size
width
size
height
),
Paint
().
shader
shader
);
// Draws a stroked rectangle with the shader only applied to the fragments
// that lie within the stroke.
canvas
drawRect
Rect
fromLTWH
size
width
size
height
), | https://docs.flutter.dev/development/ui/advanced/shaders/index.html |
bd7144d62229-5 | width
size
height
),
Paint
()
style
PaintingStyle
stroke
shader
shader
Authoring shaders
Fragment shaders are authored as GLSL source files.
By convention, these files have the .frag extension.
(Flutter does not support vertex shaders, which would have the .vert extension.)
Any GLSL version from 460 down to 100 is supported,
though some available features are restricted.
The rest of the examples in this document use version 460 core.
Shaders are subject to the following limitations when used with Flutter:
UBOs and SSBOs aren’t supported.
sampler2D is the only supported sampler type. | https://docs.flutter.dev/development/ui/advanced/shaders/index.html |
bd7144d62229-6 | sampler2D is the only supported sampler type.
Only the two-argument version of texture (sampler and uv) is supported.
No additional varying inputs may be declared.
All precision hints are ignored when targeting Skia.
Unsigned integers and booleans aren’t supported.
Uniforms
A fragment program can be configured by defining uniform values in the GLSL shader source
and then setting these values in Dart for each fragment shader instance.
FragmentShader.setFloat method.
GLSL sampler values, which use the
FragmentShader.setImageSampler method.
The correct index for each uniform value is determined by the order
that the uniform values are defined in the fragment program.
For data types composed of multiple floats, such as a vec4,
you must call FragmentShader.setFloat once for each value.
For example, given the following uniforms declarations in a GLSL fragment program: | https://docs.flutter.dev/development/ui/advanced/shaders/index.html |
bd7144d62229-7 | For example, given the following uniforms declarations in a GLSL fragment program:
uniform
float
uScale
uniform
sampler2D
uTexture
uniform
vec2
uMagnitude
uniform
vec4
uColor
The corresponding Dart code to initialize these uniform values is as follows:
void
updateShader
FragmentShader
shader
Color
color
Image
image
shader
setFloat
23
);
// uScale
shader
setFloat
114
);
// uMagnitude x | https://docs.flutter.dev/development/ui/advanced/shaders/index.html |
bd7144d62229-8 | );
// uMagnitude x
shader
setFloat
83
);
// uMagnitude y
// Convert color to premultiplied opacity.
shader
setFloat
color
red
255
color
opacity
);
// uColor r
shader
setFloat
color
green
255
color
opacity
);
// uColor g
shader
setFloat
color
blue
255
color
opacity
); | https://docs.flutter.dev/development/ui/advanced/shaders/index.html |
bd7144d62229-9 | color
opacity
);
// uColor b
shader
setFloat
color
opacity
);
// uColor a
// Initialize sampler uniform.
shader
setImageSampler
image
);
Observe that the indices used with FragmentShader.setFloat
do not count the sampler2D uniform.
This uniform is set separately with FragmentShader.setImageSampler,
with the index starting over at 0.
Any float uniforms that are left uninitialized will default to 0.0.
Current position | https://docs.flutter.dev/development/ui/advanced/shaders/index.html |
bd7144d62229-10 | Current position
The shader has access to a varying value that contains the local coordinates for
the particular fragment being evaluated. Use this feature to compute
effects that depend on the current position, which can be accessed by
importing the flutter/runtime_effect.glsl library and calling the
FlutterFragCoord function. For example:
#include
<flutter/runtime_effect.glsl>
void
main
()
vec2
currentPos
FlutterFragCoord
().
xy | https://docs.flutter.dev/development/ui/advanced/shaders/index.html |
bd7144d62229-11 | ().
xy
The value returned from FlutterFragCoord is distinct from gl_FragCoord.
gl_FragCoord provides the screen space coordinates and should generally be
avoided to ensure that shaders are consistent across backends. When targeting a
Skia backend, the calls to gl_FragCoord are rewritten to access local
coordinates but this rewriting isn’t possible with Impeller.
Colors
There isn’t a built-in data type for colors. Instead they are commonly
represented as a vec4 with each component corresponding to one of the RGBA
color channels.
The single output fragColor expects that the color value is normalized to be
in the range of 0.0 to 1.0 and that it has premultiplied alpha. This is
different than typical Flutter colors which use a 0-255 value encoding and
have unpremultipled alpha.
Samplers | https://docs.flutter.dev/development/ui/advanced/shaders/index.html |
bd7144d62229-12 | Samplers
A sampler provides access to a dart:ui Image object.
This image can be acquired either from a decoded image
or from part of the application using
Scene.toImageSync or Picture.toImageSync.
#include
<flutter/runtime_effect.glsl>
uniform
vec2
uSize
uniform
sampler2D
uTexture
out
vec4
fragColor
void
main
()
vec2
uv
FlutterFragCoord
().
xy
uSize
fragColor
texture
uTexture
uv
); | https://docs.flutter.dev/development/ui/advanced/shaders/index.html |
bd7144d62229-13 | uTexture
uv
);
By default, the image uses TileMode.clamp to determine how values outside
of the range of [0, 1] behave. Customization of the tile mode is not
supported and needs to be emulated in the shader.
Performance considerations
When targeting the Skia backend, loading the shader might be expensive since it
must be compiled to the appropriate platform-specific shader at runtime. If you
intend to use one or more shaders during an animation, consider precaching the
fragment program objects before starting the animation.
You can reuse a FragmentShader object across frames;
this is more efficient than creating a new FragmentShader for each frame.
For a more detailed guide on writing performant shaders,
check out Writing efficient shaders on GitHub.
Other resources
For more information, here are a few resources.
The Book of Shaders by Patricio Gonzalez Vivo and Jen Lowe | https://docs.flutter.dev/development/ui/advanced/shaders/index.html |
bd7144d62229-14 | The Book of Shaders by Patricio Gonzalez Vivo and Jen Lowe
Shader toy, a collaborative shader playground
simple_shader, a simple Flutter fragment shaders sample project | https://docs.flutter.dev/development/ui/advanced/shaders/index.html |
05fdec1b0b7a-0 | Using slivers to achieve fancy scrolling
UI
Advanced
Using slivers to achieve fancy scrolling
A sliver is a portion of a scrollable area that you
can define to behave in a special way.
You can use slivers to achieve custom scrolling effects,
such as elastic scrolling.
For a free, instructor-led video workshop that also uses DartPad,
check out the following video about using slivers:
Resources
For more information on implementing fancy scrolling effects
in Flutter, see the following resources:
Slivers, Demystified
A free article on Medium that
explains how to implement custom scrolling
using the sliver classes.
SliverAppBar
A one-minute Widget-of-the-week
video that gives an overview of the
SliverAppBar widget.
SliverList and SliverGrid | https://docs.flutter.dev/development/ui/advanced/slivers/index.html |
05fdec1b0b7a-1 | SliverList and SliverGrid
A one-minute Widget-of-the-week
video that gives an overview of the SliverList
and SliverGrid widgets.
Slivers explained - Making dynamic layouts
A 50-minute episode of The Boring Show
where Ian Hickson, Flutter’s Tech Lead, and Filip Hracek
discuss the power of slivers.
API docs
Here some links to relevant API docs:
SliverAppBar
SliverGrid
SliverList | https://docs.flutter.dev/development/ui/advanced/slivers/index.html |
4ba607c8ad22-0 | Flutter's fonts and typography
UI
Advanced
Flutter's fonts and typography
Variable fonts
Using the Google Fonts type tester
Static fonts
Using the Google Fonts site
Other resources
Typography covers the style and appearance of
type or fonts: it specifies how heavy the font is,
the slant of the font, the spacing between
the letters, and other visual aspects of the text.
All fonts are not created the same. Fonts are a huge
topic and beyond the scope of this site, however,
this page discusses Flutter’s support for variable
and static fonts.
Variable fonts | https://docs.flutter.dev/development/ui/advanced/typography/index.html |
4ba607c8ad22-1 | Variable fonts
Variable fonts (also called OpenType fonts),
allow you to control pre-defined aspects of text styling.
Variable fonts support specific axes, such as width,
weight, slant (to name a few).
The user can select any value along the continuous axis
when specifying the type.
However, the font must first define what axes are available,
and that isn’t always easy to figure out. If you are using
a Google Font, you can learn what axes are available using
the type tester feature, described in the next section.
Using the Google Fonts type tester
The Google Fonts site offers both variable and static fonts.
Use the type tester to learn more about its variable fonts.
To investigate a variable Google font, go to the Google Fonts
website. Note that in the upper right corner of each font card,
it says either variable for a variable font, or
x styles indicating how many styles a static
font supports.
To see all variable fonts, check the Show only variable fonts
checkbox. | https://docs.flutter.dev/development/ui/advanced/typography/index.html |
4ba607c8ad22-2 | To see all variable fonts, check the Show only variable fonts
checkbox.
Either scroll down (or use the search field) to find Roboto.
This lists several Roboto variable fonts.
Select Roboto Serif to open up its details page.
On the details page, select the Type tester tab.
For the Roboto Serif font,
the Variable axes column looks like the following:
In real time, move the slider on any of the axes to
see how it affects the font. When programming a variable font,
use the FontVariation class to modify the font’s design axes.
The FontVariation class conforms to the
OpenType font variables spec.
Static fonts
Google Fonts also contains static fonts. As with variable fonts,
you need to know how the font is designed to know what options
are available to you.
Once again, the Google Fonts site can help.
Using the Google Fonts site | https://docs.flutter.dev/development/ui/advanced/typography/index.html |
4ba607c8ad22-3 | Using the Google Fonts site
Use the font’s details page to learn more about its static fonts.
To investigate a variable Google font, go to the Google Fonts
website. Note that in the upper right corner of each font card,
it says either variable for a variable font, or
x styles indicating how many styles a static
font supports.
Make sure that Show only variable fonts is not checked
and the search field is empty.
Open the Font properties menu. Check the Number of styles
checkbox, and move the slider to 10+.
Select a font, such as Roboto to open up its details page.
Roboto has 12 styles, and each style is previewed on its details
page, along with the name of that variation.
In real time, move the pixel slider to preview the font at
different pixel sizes.
Select the Type tester tab to see the supported styles for
the font. In this case, there are 3 supported styles. | https://docs.flutter.dev/development/ui/advanced/typography/index.html |
4ba607c8ad22-4 | Select the Glyph tab. This shows the glyphs that the
font supports.
Use the following API to programmaticaly alter a static font
(but remember that this only works if the font was designed
to support the feature):
FontFeature to select glyphs
FontWeight to modify weight
FontStyle to italicize
A FontFeature corresponds to an OpenType feature tag
and can be thought of as a boolean flag to enable or disable
a feature of a given font.
The following example is for CSS, but illustrates the concept:
Other resources
The following video shows you some of the capabilities
of Flutter’s typography and combines it with the Material
and Cupertino look and feel (depending on the platform
the app runs on), animation, and custom fragment shaders:
Prototyping beautiful designs with Flutter | https://docs.flutter.dev/development/ui/advanced/typography/index.html |
4ba607c8ad22-5 | Prototyping beautiful designs with Flutter
To read one engineer’s experience
customizing variable fonts and animating them as they
morph (and was the basis for the above video),
check out Playful typography with Flutter,
a free article on Medium. The associated example also
uses a custom shader. | https://docs.flutter.dev/development/ui/advanced/typography/index.html |
8b28f0d07f84-0 | Hero animations
UI
Animations
Hero
Basic structure of a hero animation
Behind the scenes
Essential classes
Standard hero animations
What’s going on?
PhotoHero class
HeroAnimation class
Radial hero animations
What’s going on?
Photo class
RadialExpansion class
What you’ll learn
The hero refers to the widget that flies between screens.
Create a hero animation using Flutter’s Hero widget.
Fly the hero from one screen to another.
Animate the transformation of a hero’s shape from circular to
rectangular while flying it from one screen to another.
The Hero widget in Flutter implements a style of animation
commonly known as shared element transitions or
shared element animations. | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-1 | You’ve probably seen hero animations many times. For example, a screen displays
a list of thumbnails representing items for sale. Selecting an item flies it to
a new screen, containing more details and a “Buy” button. Flying an image from
one screen to another is called a hero animation in Flutter, though the same
motion is sometimes referred to as a shared element transition.
You might want to watch this one-minute video introducing the Hero widget:
This guide demonstrates how to build standard hero animations, and hero
animations that transform the image from a circular shape to a square shape
during flight.
Examples: This guide provides examples of each hero animation style at
the following links.
Standard hero animation code
Radial hero animation code
New to Flutter?
This page assumes you know how to create a layout
using Flutter’s widgets. For more information, see
Building Layouts in Flutter. | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-2 | Terminology:
A Route describes a page or screen in a Flutter app.
You can create this animation in Flutter with Hero widgets.
As the hero animates from the source to the destination route,
the destination route (minus the hero) fades into view.
Typically, heroes are small parts of the UI, like images,
that both routes have in common. From the user’s perspective
the hero “flies” between the routes. This guide shows how
to create the following hero animations:
Standard hero animations
A standard hero animation flies the hero from one route to a new route,
usually landing at a different location and with a different size. | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-3 | The following video (recorded at slow speed) shows a typical example.
Tapping the flippers in the center of the route flies them to the
upper left corner of a new, blue route, at a smaller size.
Tapping the flippers in the blue route (or using the device’s
back-to-previous-route gesture) flies the flippers back to
the original route.
Radial hero animations
In radial hero animation, as the hero flies between routes
its shape appears to change from circular to rectangular.
The following video (recorded at slow speed),
shows an example of a radial hero animation. At the start, a
row of three circular images appears at the bottom of the route.
Tapping any of the circular images flies that image to a new route
that displays it with a square shape.
Tapping the square image flies the hero back to
the original route, displayed with a circular shape. | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-4 | Before moving to the sections specific to
standard
or radial hero animations,
read basic structure of a hero animation
to learn how to structure hero animation code,
and behind the scenes to understand
how Flutter performs a hero animation.
Basic structure of a hero animation
What's the point?
Use two hero widgets in different routes but with matching tags to
implement the animation.
The Navigator manages a stack containing the app’s routes.
Pushing a route on or popping a route from the Navigator’s stack
triggers the animation.
The Flutter framework calculates a rectangle tween,
RectTween that defines the hero’s boundary
as it flies from the source to the destination route.
During its flight, the hero is moved to
an application overlay, so that it appears on top of both routes.
Terminology:
If the concept of tweens or tweening is new to you,
see the Animations in Flutter tutorial. | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-5 | Hero animations are implemented using two Hero
widgets: one describing the widget in the source route,
and another describing the widget in the destination route.
From the user’s point of view, the hero appears to be shared, and
only the programmer needs to understand this implementation detail.
Hero animation code has the following structure:
Define a starting Hero widget, referred to as the source
hero. The hero specifies its graphical representation
(typically an image), and an identifying tag, and is in
the currently displayed widget tree as defined by the source route.
Define an ending Hero widget, referred to as the destination hero.
This hero also specifies its graphical representation,
and the same tag as the source hero.
It’s essential that both hero widgets are created with
the same tag, typically an object that represents the
underlying data. For best results, the heroes should have
virtually identical widget trees.
Create a route that contains the destination hero.
The destination route defines the widget tree that exists
at the end of the animation. | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-6 | Trigger the animation by pushing the destination route on the
Navigator’s stack. The Navigator push and pop operations trigger
a hero animation for each pair of heroes with matching tags in
the source and destination routes.
Flutter calculates the tween that animates the Hero’s bounds from
the starting point to the endpoint (interpolating size and position),
and performs the animation in an overlay.
The next section describes Flutter’s process in greater detail.
Behind the scenes
The following describes how Flutter performs the
transition from one route to another.
Before transition, the source hero waits in the source
route’s widget tree. The destination route does not yet exist,
and the overlay is empty.
Pushing a route to the Navigator triggers the animation.
At t=0.0, Flutter does the following: | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-7 | Calculates the destination hero’s path, offscreen,
using the curved motion as described in the Material
motion spec. Flutter now knows where the hero ends up.
Places the destination hero in the overlay,
at the same location and size as the source hero.
Adding a hero to the overlay changes its Z-order so that it
appears on top of all routes.
Moves the source hero offscreen.
As the hero flies, its rectangular bounds are animated using
Tween<Rect>, specified in Hero’s
createRectTween property.
By default, Flutter uses an instance of
MaterialRectArcTween, which animates the
rectangle’s opposing corners along a curved path.
(See Radial hero animations for an example
that uses a different Tween animation.)
When the flight completes:
Flutter moves the hero widget from the overlay to
the destination route. The overlay is now empty.
The destination hero appears in its final position
in the destination route. | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-8 | The destination hero appears in its final position
in the destination route.
The source hero is restored to its route.
Popping the route performs the same process,
animating the hero back to its size
and location in the source route.
Essential classes
The examples in this guide use the following classes to
implement hero animations:
Hero
The widget that flies from the source to the destination route.
Define one Hero for the source route and another for the
destination route, and assign each the same tag.
Flutter animates pairs of heroes with matching tags.
Inkwell
Specifies what happens when tapping the hero.
The InkWell’s onTap() method builds the
new route and pushes it to the Navigator’s stack.
Navigator
The Navigator manages a stack of routes. Pushing a route on or
popping a route from the Navigator’s stack triggers the animation. | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-9 | Route
Specifies a screen or page. Most apps,
beyond the most basic, have multiple routes.
Standard hero animations
What's the point?
Specify a route using MaterialPageRoute, CupertinoPageRoute,
or build a custom route using PageRouteBuilder.
The examples in this section use MaterialPageRoute.
Change the size of the image at the end of the transition by
wrapping the destination’s image in a SizedBox.
Change the location of the image by placing the destination’s
image in a layout widget. These examples use Container.
Standard hero animation code
Each of the following examples demonstrates flying an image from one
route to another. This guide describes the first example.
hero_animation
Encapsulates the hero code in a custom PhotoHero widget.
Animates the hero’s motion along a curved path,
as described in the Material motion spec. | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-10 | basic_hero_animation
Uses the hero widget directly.
This more basic example, provided for your reference, isn’t
described in this guide.
What’s going on?
Flying an image from one route to another is easy to implement
using Flutter’s hero widget. When using MaterialPageRoute
to specify the new route, the image flies along a curved path,
as described by the Material Design motion spec.
Create a new Flutter example and
update it using the files from the hero_animation.
To run the example:
Tap on the home route’s photo to fly the image to a new route
showing the same photo at a different location and scale.
Return to the previous route by tapping the image, or by using the
device’s back-to-the-previous-route gesture.
You can slow the transition further using the timeDilation
property.
PhotoHero class | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-11 | PhotoHero class
The custom PhotoHero class maintains the hero,
and its size, image, and behavior when tapped.
The PhotoHero builds the following widget tree:
Here’s the code:
Key information:
The starting route is implicitly pushed by MaterialApp when
HeroAnimation is provided as the app’s home property.
An InkWell wraps the image, making it trivial to add a tap
gesture to the both the source and destination heroes.
Defining the Material widget with a transparent color
enables the image to “pop out” of the background as it
flies to its destination.
The SizedBox specifies the hero’s size at the start and
end of the animation.
Setting the Image’s fit property to BoxFit.contain,
ensures that the image is as large as possible during the
transition without changing its aspect ratio.
HeroAnimation class | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-12 | HeroAnimation class
The HeroAnimation class creates the source and destination
PhotoHeroes, and sets up the transition.
Here’s the code:
timeDilation = 5.0; // 1.0 means normal animation speed.
return Scaffold(
appBar: AppBar(
title: const Text('Basic Hero Animation'),
),
body: Center(
child: PhotoHero(
photo: 'images/flippers-alpha.png',
width: 300.0,
onTap: () {
Navigator.of(context).push(MaterialPageRoute<void>( | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-13 | Navigator.of(context).push(MaterialPageRoute<void>(
builder: (BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flippers Page'),
),
body: Container(
// The blue background emphasizes that it's a new route.
color: Colors.lightBlueAccent,
padding: const EdgeInsets.all(16.0),
alignment: Alignment.topLeft,
child: PhotoHero(
photo: 'images/flippers-alpha.png',
width: 100.0,
onTap: () {
Navigator.of(context).pop();
},
),
),
);
}
));
},
),
),
);
}
}
Key information: | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-14 | Key information:
When the user taps the InkWell containing the source hero,
the code creates the destination route using MaterialPageRoute.
Pushing the destination route to the Navigator’s stack triggers
the animation.
The Container positions the PhotoHero in the destination
route’s top-left corner, below the AppBar.
The onTap() method for the destination PhotoHero
pops the Navigator’s stack, triggering the animation
that flies the Hero back to the original route.
Use the timeDilation property to slow the transition
while debugging.
Radial hero animations
What's the point?
A radial transformation animates a circular shape into a square
shape.
A radial hero animation performs a radial transformation while
flying the hero from the source route to the destination route.
MaterialRectCenterArcTween defines the tween animation.
Build the destination route using PageRouteBuilder. | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-15 | Build the destination route using PageRouteBuilder.
Flying a hero from one route to another as it transforms
from a circular shape to a rectangular shape is a slick
effect that you can implement using Hero widgets.
To accomplish this, the code animates the intersection of
two clip shapes: a circle and a square.
Throughout the animation, the circle clip (and the image)
scales from minRadius to maxRadius, while the square
clip maintains constant size. At the same time,
the image flies from its position in the source route to its
position in the destination route. For visual examples
of this transition, see Radial transformation
in the Material motion spec.
This animation might seem complex (and it is), but you can customize the
provided example to your needs. The heavy lifting is done for you.
Radial hero animation code
Each of the following examples demonstrates a radial hero animation.
This guide describes the first example.
radial_hero_animation | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-16 | radial_hero_animation
A radial hero animation as described in the Material motion spec.
basic_radial_hero_animation
The simplest example of a radial hero animation. The destination
route has no Scaffold, Card, Column, or Text.
This basic example, provided for your reference, isn’t
described in this guide.
radial_hero_animation_animate_rectclip
Extends radial_hero_animaton by also animating the size of the
rectangular clip. This more advanced example,
provided for your reference, isn’t described in this guide.
Pro tip:
The radial hero animation involves intersecting a round shape with
a square shape. This can be hard to see, even when slowing
the animation with timeDilation, so you might consider enabling
the debugPaintSizeEnabled flag during development.
What’s going on? | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-17 | What’s going on?
The following diagram shows the clipped image at the beginning
(t = 0.0), and the end (t = 1.0) of the animation.
The blue gradient (representing the image), indicates where the clip
shapes intersect. At the beginning of the transition,
the result of the intersection is a circular clip (ClipOval).
During the transformation, the ClipOval scales from minRadius
to maxRadius while the ClipRect maintains a constant size.
At the end of the transition the intersection of the circular and
rectangular clips yield a rectangle that’s the same size as the hero
widget. In other words, at the end of the transition the image is no
longer clipped.
Create a new Flutter example and
update it using the files from the
radial_hero_animation GitHub directory.
To run the example: | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-18 | To run the example:
Tap on one of the three circular thumbnails to animate the image
to a larger square positioned in the middle of a new route that
obscures the original route.
Return to the previous route by tapping the image, or by using the
device’s back-to-the-previous-route gesture.
You can slow the transition further using the timeDilation
property.
Photo class
The Photo class builds the widget tree that holds the image:
Material(
// Slightly opaque color appears where the image has transparency.
color: Theme.of(context).primaryColor.withOpacity(0.25),
child:
InkWell(
onTap:
onTap,
child:
Image.asset(
photo,
fit: BoxFit.contain,
)
),
);
}
} | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-19 | Key information:
The Inkwell captures the tap gesture.
The calling function passes the onTap() function to the
Photo’s constructor.
During flight, the InkWell draws its splash on its first
Material ancestor.
The Material widget has a slightly opaque color, so the
transparent portions of the image are rendered with color.
This ensures that the circle-to-square transition is easy to see,
even for images with transparency.
The Photo class does not include the Hero in its widget tree.
For the animation to work, the hero
wraps the RadialExpansion widget.
RadialExpansion class
The RadialExpansion widget, the core of the demo, builds the
widget tree that clips the image during the transition.
The clipped shape results from the intersection of a circular clip
(that grows during flight),
with a rectangular clip (that remains a constant size throughout).
To do this, it builds the following widget tree: | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-20 | To do this, it builds the following widget tree:
Here’s the code:
clipRectSize = 2.0 * (maxRadius / math.sqrt2),
super(key: key);
final double maxRadius;
final clipRectSize;
final Widget child;
@override
Widget build(BuildContext context) {
return
ClipOval(
child:
Center(
child:
SizedBox(
width: clipRectSize,
height: clipRectSize,
child:
ClipRect(
child:
child, // Photo
),
),
),
);
}
}
Key information:
The hero wraps the RadialExpansion widget. | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-21 | Key information:
The hero wraps the RadialExpansion widget.
As the hero flies, its size changes and,
because it constrains its child’s size,
the RadialExpansion widget changes size to match.
The RadialExpansion animation is created by two overlapping clips.
The example defines the tweening interpolation using
MaterialRectCenterArcTween.
The default flight path for a hero animation
interpolates the tweens using the corners of the heroes.
This approach affects the hero’s aspect ratio during
the radial transformation, so the new flight path uses
MaterialRectCenterArcTween to interpolate the tweens using the
center point of each hero.
Here’s the code:
static RectTween _createRectTween(Rect begin, Rect end) {
return MaterialRectCenterArcTween(begin: begin, end: end);
} | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
8b28f0d07f84-22 | The hero’s flight path still follows an arc,
but the image’s aspect ratio remains constant. | https://docs.flutter.dev/development/ui/animations/hero-animations/index.html |
aa3844cbd227-0 | Implicit animations
UI
Animations
Implicit animations
Documentation
Flutter in Focus videos
The Boring Show
Widget of the Week videos
With Flutter’s animation library,
you can add motion and create visual effects
for the widgets in your UI.
One part of the library is an assortment of widgets
that manage animations for you.
These widgets are collectively referred to as implicit animations,
or implicitly animated widgets, deriving their name from the
ImplicitlyAnimatedWidget class that they implement.
The following set of resources provide many ways to learn
about implicit animations in Flutter.
Documentation
Implicit animations codelab
Jump right into the code!
This codelab uses interactive examples
and step-by-step instructions to teach you
how to use implicit animations.
AnimatedContainer sample | https://docs.flutter.dev/development/ui/animations/implicit-animations/index.html |
aa3844cbd227-1 | AnimatedContainer sample
A step-by-step recipe from the Flutter cookbook
for using the AnimatedContainer
implicitly animated widget.
ImplicitlyAnimatedWidget API page
All implicit animations extend the ImplicitlyAnimatedWidget class.
Flutter in Focus videos
Flutter in Focus videos feature 5-10 minute tutorials
with real code that cover techniques
that every Flutter dev needs to know from top to bottom.
The following videos cover topics
that are relevant to implicit animations.
The Boring Show
Watch the Boring Show to follow Google Engineers build apps
from scratch in Flutter. The following episode covers
using implicit animations in a news aggregator app.
Widget of the Week videos | https://docs.flutter.dev/development/ui/animations/implicit-animations/index.html |
aa3844cbd227-2 | Widget of the Week videos
A weekly series of short animated videos each showing
the important features of one particular widget.
In about 60 seconds, you’ll see real code for each
widget with a demo about how it works.
The following Widget of the Week videos cover
implicitly animated widgets: | https://docs.flutter.dev/development/ui/animations/implicit-animations/index.html |
8e40cf1f02d5-0 | Introduction to animations
UI
Animations
Choosing an approach
Codelabs, tutorials, and articles
Animation types
Tween animation
Physics-based animation
Pre-canned animations
Common animation patterns
Animated list or grid
Shared element transition
Staggered animation
Other resources
Well-designed animations make a UI feel more intuitive,
contribute to the slick look and feel of a polished app,
and improve the user experience.
Flutter’s animation support makes it easy to implement a variety of
animation types. Many widgets, especially Material widgets,
come with the standard motion effects defined in their design spec,
but it’s also possible to customize these effects.
Choosing an approach | https://docs.flutter.dev/development/ui/animations/index.html |
8e40cf1f02d5-1 | Choosing an approach
There are different approaches you can take when creating
animations in Flutter. Which approach is right for you?
To help you decide, check out the video,
How to choose which Flutter Animation Widget is right for you?
(Also published as a companion article.)
(To dive deeper into the decision process,
watch the Animations in Flutter done right video,
presented at Flutter Europe.)
As shown in the video, the following
decision tree helps you decide what approach
to use when implementing a Flutter animation:
If a pre-packaged implicit animation (the easiest animation
to implement) suits your needs, watch
Animation basics with implicit animations.
(Also published as a companion article.)
To create a custom implicit animation, watch
Creating your own custom implicit animations with TweenAnimationBuilder.
(Also published as a companion article.) | https://docs.flutter.dev/development/ui/animations/index.html |
8e40cf1f02d5-2 | To create an explicit animation (where you control the animation,
rather than letting the framework control it), perhaps
you can use one of the built-in explicit animations classes.
For more information, watch
Making your first directional animations with
built-in explicit animations.
(Also published as a companion article.)
If you need to build an explicit animation from scratch, watch
Creating custom explicit animations with
AnimatedBuilder and AnimatedWidget.
(Also published as a companion article.)
For a deeper understanding of just how animations work in Flutter, watch
Animation deep dive.
(Also published as a companion article.)
Codelabs, tutorials, and articles
The following resources are a good place to start learning
the Flutter animation framework. Each of these documents
shows how to write animation code.
Implicit animations codelab
Covers how to use implicit animations
using step-by-step instructions and interactive examples. | https://docs.flutter.dev/development/ui/animations/index.html |
8e40cf1f02d5-3 | Animations tutorial
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. This tutorial shows
how to create your own custom explicit animations.
Zero to One with Flutter, part 1 and part 2
Medium articles showing how to create an animated chart using tweening.
Write your first Flutter app on the web
Codelab demonstrating how to create a form
that uses animation to show the user’s progress
as they fill in the fields.
Animation types
Generally, animations are either tween- or physics-based.
The following sections explain what these terms mean,
and point you to resources where you can learn more.
Tween animation | https://docs.flutter.dev/development/ui/animations/index.html |
8e40cf1f02d5-4 | Tween animation
Short for in-betweening. In a tween animation, the beginning
and ending points are defined, as well as a timeline, and a curve
that defines the timing and speed of the transition.
The framework calculates how to transition from the beginning point
to the end point.
The documents listed above, such as the
Animations tutorial, are not specifically
about tweening, but they use tweens in their examples.
Physics-based animation
In physics-based animation, motion is modeled to resemble real-world
behavior. When you toss a ball, for example, where and when it lands
depends on how fast it was tossed and how far it was from the ground.
Similarly, dropping a ball attached to a spring falls
(and bounces) differently than dropping a ball attached to a string.
Animate a widget using a physics simulation
A recipe in the animations section of the Flutter cookbook. | https://docs.flutter.dev/development/ui/animations/index.html |
8e40cf1f02d5-5 | Flutter Gallery
Under Material Components, the Grid example
demonstrates a fling animation. Select one of the
images from the grid and zoom in. You can pan the
image with flinging or dragging gestures.
Also see the API documentation for
AnimationController.animateWith and
SpringSimulation.
Pre-canned animations
If you are using Material widgets, you might check
out the animations package available on pub.dev.
This package contains pre-built animations for
the following commonly used patterns:
Container transforms, shared axis transitions,
fade through transitions, and fade transitions.
Common animation patterns
Most UX or motion designers find that certain
animation patterns are used repeatedly when designing a UI.
This section lists some of the commonly
used animation patterns, and tells you where to learn more.
Animated list or grid
This pattern involves animating the addition or removal of
elements from a list or grid. | https://docs.flutter.dev/development/ui/animations/index.html |
8e40cf1f02d5-6 | This pattern involves animating the addition or removal of
elements from a list or grid.
AnimatedList example
This demo, from the Sample app catalog, shows how to
animate adding an element to a list, or removing a selected element.
The internal Dart list is synced as the user modifies the list using
the plus (+) and minus (-) buttons.
Shared element transition
In this pattern, the user selects an element—often an
image—from the page, and the UI animates the selected element
to a new page with more detail. In Flutter, you can easily implement
shared element transitions between routes (pages)
using the Hero widget.
Hero animations
How to create two styles of Hero animations:
The hero flies from one page to another while changing position
and size.
The hero’s boundary changes shape, from a circle to a square,
as its flies from one page to another. | https://docs.flutter.dev/development/ui/animations/index.html |
8e40cf1f02d5-7 | Flutter Gallery
You can build the Gallery app yourself,
or download it from the Play Store. The Shrine
demo includes an example of a hero animation.
Also see the API documentation for the
Hero, Navigator, and PageRoute classes.
Staggered animation
Animations that are broken into smaller motions,
where some of the motion is delayed.
The smaller animations might be sequential,
or might partially or completely overlap.
Staggered Animations
Other resources
Learn more about Flutter animations at the following links:
Animation samples from the Sample app catalog.
Animation recipes from the Flutter cookbook.
Animation videos from the Flutter YouTube channel.
Animations: overview
A look at some of the major classes in the
animations library, and Flutter’s animation architecture. | https://docs.flutter.dev/development/ui/animations/index.html |
8e40cf1f02d5-8 | Animation and motion widgets
A catalog of some of the animation widgets
provided in the Flutter APIs.
The animation library in the Flutter API documentation
The animation API for the Flutter framework. This link
takes you to a technical overview page for the library. | https://docs.flutter.dev/development/ui/animations/index.html |
af4a10d2bc4a-0 | Animations overview
UI
Animations
Overview
Animation
addListener
addStatusListener
AnimationController
Tweens
Architecture
Scheduler
Tickers
Simulations
Animatables
Tweens
Composing animatables
Curves
Animations
Composable animations
Animation controllers
Attaching animatables to animations
The animation system in Flutter is based on typed
Animation objects. Widgets can either
incorporate these animations in their build
functions directly by reading their current value and listening to their
state changes or they can use the animations as the basis of more elaborate
animations that they pass along to other widgets.
Animation | https://docs.flutter.dev/development/ui/animations/overview/index.html |
af4a10d2bc4a-1 | Animation
The primary building block of the animation system is the
Animation class. An animation represents a value
of a specific type that can change over the lifetime of
the animation. Most widgets that perform an animation
receive an Animation object as a parameter,
from which they read the current value of the animation
and to which they listen for changes to that value.
addListener
Whenever the animation’s value changes,
the animation notifies all the listeners added with
addListener. Typically, a State
object that listens to an animation calls
setState on itself in its listener callback
to notify the widget system that it needs to
rebuild with the new value of the animation.
AnimatedWidget and
AnimatedBuilder.
The first,
build function.
The second,
addStatusListener
AnimationStatus,
which indicates how the animation will evolve over time.
Whenever the animation’s status changes,
the animation notifies all the listeners added with | https://docs.flutter.dev/development/ui/animations/overview/index.html |
af4a10d2bc4a-2 | addStatusListener. Typically, animations start
out in the
AnimationController
To create an animation, first create an AnimationController.
As well as being an animation itself, an AnimationController
lets you control the animation. For example,
you can tell the controller to play the animation
forward or stop the animation.
You can also fling animations,
which uses a physical simulation, such as a spring,
to drive the animation.
Once you’ve created an animation controller,
you can start building other animations based on it.
For example, you can create a ReverseAnimation
that mirrors the original animation but runs in the
opposite direction (from 1.0 to 0.0).
Similarly, you can create a CurvedAnimation
whose value is adjusted by a Curve.
Tweens
Tween<T>, which interpolates between its
begin and
end values. Many types have specific | https://docs.flutter.dev/development/ui/animations/overview/index.html |
af4a10d2bc4a-3 | begin and
end values. Many types have specific
ColorTween interpolates between colors and
RectTween interpolates between rects.
You can define your own interpolations by creating
your own subclass of
lerp function.
By itself, a tween just defines how to interpolate
between two values. To get a concrete value for the
current frame of an animation, you also need an
animation to determine the current state.
There are two ways to combine a tween
with an animation to get a concrete value:
You can evaluate the tween at the current
value of an animation. This approach is most useful
for widgets that are already listening to the animation and hence
rebuilding whenever the animation changes value. | https://docs.flutter.dev/development/ui/animations/overview/index.html |
af4a10d2bc4a-4 | You can animate the tween based on the animation.
Rather than returning a single value, the animate function
returns a new Animation that incorporates the tween.
This approach is most useful when you want to give the
newly created animation to another widget,
which can then read the current value that incorporates
the tween as well as listen for changes to the value.
Architecture
Animations are actually built from a number of core building blocks.
Scheduler
The SchedulerBinding is a singleton class
that exposes the Flutter scheduling primitives. | https://docs.flutter.dev/development/ui/animations/overview/index.html |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.