id
stringlengths 14
17
| text
stringlengths 23
1.11k
| source
stringlengths 35
114
|
---|---|---|
569481dcb67d-0 | Effects
Cookbook
Effects
Create a download button
Create a nested navigation flow
Create a photo filter carousel
Create a scrolling parallax effect
Create a shimmer loading effect
Create a staggered menu animation
Create a typing indicator
Create an expandable FAB
Create gradient chat bubbles
Drag a UI element | https://docs.flutter.dev/cookbook/effects/index.html |
5edcbedc41f9-0 | Create a download button
Create a photo filter carousel
Create a nested navigation flow
Cookbook
Effects
Create a nested navigation flow
Prepare for navigation
Display an app bar for the setup flow
Generate nested routes
Interactive example
Apps accumulate dozens and then hundreds of routes over time.
Some of your routes make sense as top-level (global) routes.
For example, “/”, “profile”, “contact”, “social_feed” are all
possible top-level routes within your app.
But, imagine that you defined every possible route in your
top-level Navigator widget. The list would be very long,
and many of these routes would
be better handled nested within another widget. | https://docs.flutter.dev/cookbook/effects/nested-nav/index.html |
5edcbedc41f9-1 | Consider an Internet of Things (IoT) setup flow for a wireless
light bulb that you control with your app.
This setup flow consists of 4 pages:
find nearby bulbs, select the bulb that you want to add,
add the bulb, and then complete the setup.
You could orchestrate this behavior from your top-level
Navigator widget. However, it makes more sense to define a second,
nested Navigator widget within your SetupFlow widget,
and let the nested Navigator take ownership over the 4 pages
in the setup flow. This delegation of navigation facilitates
greater local control, which is
generally preferable when developing software.
The following animation shows the app’s behavior:
In this recipe, you implement a four-page IoT setup
flow that maintains its own navigation nested beneath
the top-level Navigator widget.
Prepare for navigation | https://docs.flutter.dev/cookbook/effects/nested-nav/index.html |
5edcbedc41f9-2 | Prepare for navigation
This IoT app has two top-level screens,
along with the setup flow. Define these
route names as constants so that they can
be referenced within code.
The home and settings screens are referenced with
static names. The setup flow pages, however,
use two paths to create their route names:
a /setup/ prefix followed by the name of the specific page.
By combining the two paths, your Navigator can determine
that a route name is intended for the setup flow without
recognizing all the individual pages associated with
the setup flow.
The top-level Navigator isn’t responsible for identifying
individual setup flow pages. Therefore, your top-level
Navigator needs to parse the incoming route name to
identify the setup flow prefix. Needing to parse the route name
means that you can’t use the routes property of your top-level
Navigator. Instead, you must provide a function for the
onGenerateRoute property. | https://docs.flutter.dev/cookbook/effects/nested-nav/index.html |
5edcbedc41f9-3 | Implement onGenerateRoute to return the appropriate widget
for each of the three top-level paths.
Notice that the home and settings routes are matched with exact
route names. However, the setup flow route condition only
checks for a prefix. If the route name contains the setup
flow prefix, then the rest of the route name is ignored
and passed on to the SetupFlow widget to process.
This splitting of the route name is what allows the top-level
Navigator to be agnostic toward the various subroutes
within the setup flow.
Create a stateful widget called SetupFlow that
accepts a route name.
Display an app bar for the setup flow
The setup flow displays a persistent app bar
that appears across all pages.
Return a Scaffold widget from your SetupFlow
widget’s build() method,
and include the desired AppBar widget. | https://docs.flutter.dev/cookbook/effects/nested-nav/index.html |
5edcbedc41f9-4 | The app bar displays a back arrow and exits the setup
flow when the back arrow is pressed. However,
exiting the flow causes the user to lose all progress.
Therefore, the user is prompted to confirm whether they
want to exit the setup flow.
Prompt the user to confirm exiting the setup flow,
and ensure that the prompt appears when the user
presses the hardware back button on Android.
When the user taps the back arrow in the app bar,
or presses the back button on Android,
an alert dialog pops up to confirm that the
user wants to leave the setup flow.
If the user presses Leave, then the setup flow pops itself
from the top-level navigation stack.
If the user presses Stay, then the action is ignored.
You might notice that the Navigator.pop()
is invoked by both the Leave and
Stay buttons. To be clear,
this pop() action pops the alert dialog off
the navigation stack, not the setup flow. | https://docs.flutter.dev/cookbook/effects/nested-nav/index.html |
5edcbedc41f9-5 | Generate nested routes
The setup flow’s job is to display the appropriate
page within the flow.
Add a Navigator widget to SetupFlow,
and implement the onGenerateRoute property.
The _onGenerateRoute function works the same as
for a top-level Navigator. A RouteSettings
object is passed into the function,
which includes the route’s name.
Based on that route name,
one of four flow pages is returned.
The finished page provides the user with a Finish
button. When the user taps Finish,
the _exitSetup callback is invoked, which pops the entire
setup flow off the top-level Navigator stack,
taking the user back to the home screen.
Congratulations!
You implemented nested navigation with four subroutes.
Interactive example
Run the app: | https://docs.flutter.dev/cookbook/effects/nested-nav/index.html |
5edcbedc41f9-6 | Interactive example
Run the app:
On the Add your first bulb screen,
click the FAB, shown with a plus sign, +.
This brings you to the Select a nearby device
screen. A single bulb is listed.
Click the listed bulb. A Finished! screen appears.
Click the Finished button to return to the
first screen.
Create a download button
Create a photo filter carousel | https://docs.flutter.dev/cookbook/effects/nested-nav/index.html |
77a6d5fd7e8a-0 | Create a photo filter carousel
Create a shimmer loading effect
Create a scrolling parallax effect
Cookbook
Effects
Create a scrolling parallax effect
Create a list to hold the parallax items
Display items with text and a static image
Implement the parallax effect
Interactive example
When you scroll a list of cards (containing images,
for example) in an app, you might notice that those
images appear to scroll more slowly than the rest of the
screen. It almost looks as if the cards in the list
are in the foreground, but the images themselves sit
far off in the distant background. This effect is
known as parallax.
In this recipe, you create the parallax effect by building
a list of cards (with rounded corners containing some text).
Each card also contains an image.
As the cards slide up the screen,
the images within each card slide down. | https://docs.flutter.dev/cookbook/effects/parallax-scrolling/index.html |
77a6d5fd7e8a-1 | The following animation shows the app’s behavior:
Create a list to hold the parallax items
To display a list of parallax scrolling images,
you must first display a list.
Create a new stateless widget called ParallaxRecipe.
Within ParallaxRecipe, build a widget tree with a
SingleChildScrollView and a Column, which forms
a list.
Display items with text and a static image
Each list item displays a rounded-rectangle background
image, exemplifying one of seven locations in the world.
Stacked on top of that background image is the
name of the location and its country,
positioned in the lower left. Between the
background image and the text is a dark gradient,
which improves the legibility
of the text against the background. | https://docs.flutter.dev/cookbook/effects/parallax-scrolling/index.html |
77a6d5fd7e8a-2 | Implement a stateless widget called LocationListItem
that consists of the previously mentioned visuals.
For now, use a static Image widget for the background.
Later, you’ll replace that widget with a parallax version.
Next, add the list items to your ParallaxRecipe widget.
You now have a typical, scrollable list of cards
that displays seven unique locations in the world.
In the next step, you add a parallax effect to the
background image.
Implement the parallax effect
A parallax scrolling effect is achieved by slightly
pushing the background image in the opposite direction
of the rest of the list. As the list items slide up
the screen, each background image slides slightly downward.
Conversely, as the list items slide down the screen,
each background image slides slightly upward.
Visually, this results in parallax. | https://docs.flutter.dev/cookbook/effects/parallax-scrolling/index.html |
77a6d5fd7e8a-3 | The parallax effect depends on the list item’s
current position within its ancestor Scrollable.
As the list item’s scroll position changes, the position
of the list item’s background image must also change.
This is an interesting problem to solve. The position
of a list item within the Scrollable isn’t
available until Flutter’s layout phase is complete.
This means that the position of the background image
must be determined in the paint phase, which comes after
the layout phase. Fortunately, Flutter provides a widget
called Flow, which is specifically designed to give you
control over the transform of a child widget immediately
before the widget is painted. In other words,
you can intercept the painting phase and take control
to reposition your child widgets however you want.
Note:
To learn more, watch this short Widget of the Week video on the Flow widget:
Note:
In cases where you need control over what a child paints,
rather than where a child is painted,
consider using a CustomPaint widget. | https://docs.flutter.dev/cookbook/effects/parallax-scrolling/index.html |
77a6d5fd7e8a-4 | In cases where you need control over the layout,
painting, and hit testing, consider defining a
custom RenderBox.
Wrap your background Image widget with a
Flow widget.
Introduce a new FlowDelegate called ParallaxFlowDelegate.
A FlowDelegate controls how its children are sized
and where those children are painted. In this case,
your Flow widget has only one child: the background
image. That image must be exactly as wide as the Flow widget.
Return tight width constraints for your background image child.
Your background images are now sized appropriately.
But, you still need to calculate the vertical position
of each background image based on its scroll
position, and then paint it.
There are three critical pieces of information that
you need to compute the desired position of a
background image:
The bounds of the ancestor Scrollable
The bounds of the individual list item | https://docs.flutter.dev/cookbook/effects/parallax-scrolling/index.html |
77a6d5fd7e8a-5 | The bounds of the individual list item
The size of the image after it’s scaled down
to fit in the list item
To look up the bounds of the Scrollable,
you pass a ScrollableState into your FlowDelegate.
To look up the bounds of your individual list item,
you pass your list item’s BuildContext into your FlowDelegate.
To look up the final size of your background image,
you assign a GlobalKey to your Image widget,
and then you pass that GlobalKey into your
FlowDelegate.
Make this information available to ParallaxFlowDelegate.
Having all the information needed to implement
parallax scrolling, implement the shouldRepaint() method.
Now, implement the layout calculations for the parallax effect.
First, calculate the pixel position of a list
item within its ancestor Scrollable. | https://docs.flutter.dev/cookbook/effects/parallax-scrolling/index.html |
77a6d5fd7e8a-6 | First, calculate the pixel position of a list
item within its ancestor Scrollable.
Use the pixel position of the list item to calculate its
percentage from the top of the Scrollable.
A list item at the top of the scrollable area should
produce 0%, and a list item at the bottom of the
scrollable area should produce 100%.
Use the scroll percentage to calculate an Alignment.
At 0%, you want Alignment(0.0, -1.0),
and at 100%, you want Alignment(0.0, 1.0).
These coordinates correspond to top and bottom
alignment, respectively.
Use verticalAlignment, along with the size of the
list item and the size of the background image,
to produce a Rect that determines where the
background image should be positioned.
Using childRect, paint the background image with
the desired translation transformation.
It’s this transformation over time that gives you the
parallax effect. | https://docs.flutter.dev/cookbook/effects/parallax-scrolling/index.html |
77a6d5fd7e8a-7 | You need one final detail to achieve the parallax effect.
The ParallaxFlowDelegate repaints when the inputs change,
but the ParallaxFlowDelegate doesn’t repaint every time
the scroll position changes.
Pass the ScrollableState’s ScrollPosition to
the FlowDelegate superclass so that the FlowDelegate
repaints every time the ScrollPosition changes.
Congratulations!
You now have a list of cards with parallax,
scrolling background images.
Interactive example
Run the app:
Scroll up and down to observe the parallax effect.
Create a photo filter carousel
Create a shimmer loading effect | https://docs.flutter.dev/cookbook/effects/parallax-scrolling/index.html |
35525a794e24-0 | Create a nested navigation flow
Create a scrolling parallax effect
Create a photo filter carousel
Cookbook
Effects
Create a photo filter carousel
Add a selector ring and dark gradient
Create a filter carousel item
Implement the filter carousel
Interactive example
Everybody knows that a photo looks better with a filter.
In this recipe, you build a scrollable,
filter selection carousel.
The following animation shows the app’s behavior:
This recipe begins with the photo and filters
already in place. Filters are applied with the
color and colorBlendMode properties of the
Image widget.
Add a selector ring and dark gradient
The selected filter circle is displayed within a
selector ring. Additionally, a dark gradient is
behind the available filters, which helps the contrast
between the filters and any photo that you choose. | https://docs.flutter.dev/cookbook/effects/photo-filter-carousel/index.html |
35525a794e24-1 | Create a new stateful widget called
FilterSelector that you’ll use to
implement the selector.
Add the FilterSelector widget to the existing
widget tree. Position the FilterSelector widget
on top of the photo, at the bottom and centered.
Within the FilterSelector widget,
display a selector ring on top of a
dark gradient by using a Stack widget.
The size of the selector circle and the background gradient
depends on the size of an individual filter in the carousel
called itemSize. The itemSize depends on the available width.
Therefore, a LayoutBuilder widget is used to determine the
available space, and then you calculate the size of an
individual filter’s itemSize.
The selector ring includes an IgnorePointer widget
because when carousel interactivity is added,
the selector ring shouldn’t interfere with
tap and drag events.
Create a filter carousel item | https://docs.flutter.dev/cookbook/effects/photo-filter-carousel/index.html |
35525a794e24-2 | Create a filter carousel item
Each filter item in the carousel displays a
circular image with a color applied to the image
that corresponds to the associated filter color.
Define a new stateless widget called FilterItem
that displays a single list item.
Implement the filter carousel
Filter items scroll to the left and right as the user drags. Scrolling requires
some kind of Scrollable widget.
You might consider using a horizontal ListView widget,
but a ListView widget positions the first element at the
beginning of the available space, not at
the center, where your selector ring sits.
A PageView widget is better suited for a carousel.
A PageView widget lays out its children from the
center of the available space and provides snapping physics.
Snapping physics is what causes an item to snap to the center,
no matter where the user releases a drag.
Scrollable widget with a
viewportBuilder, and place a | https://docs.flutter.dev/cookbook/effects/photo-filter-carousel/index.html |
35525a794e24-3 | Scrollable widget with a
viewportBuilder, and place a
Flow widget inside the
delegate property
that allows you to position child widgets wherever
you want, based on the current
Configure your widget tree to make space for the PageView.
Build each FilterItem widget within the
PageView widget based on the given index.
Create a PageViewController and connect it to the
PageView widget.
With the PageViewController added, five FilterItem
widgets are visible on the screen at the same time,
and the photo filter changes as you scroll, but
the FilterItem widgets are still the same size.
Wrap each FilterItem widget with an AnimatedBuilder
to change the visual properties of each FilterItem
widget as the scroll position changes.
The AnimatedBuilder widget rebuilds every time the
_controller changes its scroll position.
These rebuilds allow you to change the FilterItem
size and opacity as the user drags. | https://docs.flutter.dev/cookbook/effects/photo-filter-carousel/index.html |
35525a794e24-4 | Calculate an appropriate scale and opacity for each
FilterItem widget within the AnimatedBuilder and
apply those values.
Each FilterItem widget now shrinks and fades
away as it moves farther from the center of the screen.
Add a method to change the selected filter when a
FilterItem widget is tapped.
Configure each FilterItem widget to invoke
_onFilterTapped when tapped.
Congratulations!
You now have a draggable, tappable photo filter carousel.
Interactive example
Create a nested navigation flow
Create a scrolling parallax effect | https://docs.flutter.dev/cookbook/effects/photo-filter-carousel/index.html |
8ee8a55b05b5-0 | Create a scrolling parallax effect
Create a staggered menu animation
Create a shimmer loading effect
Cookbook
Effects
Create a shimmer loading effect
Draw the shimmer shapes
Paint the shimmer gradient
Paint one big shimmer
Animate the shimmer
Loading times are unavoidable in application development.
From a user experience (UX) perspective,
the most important thing is to show your users
that loading is taking place. One popular approach
to communicate to users that data is loading is to
display a chrome color with a shimmer animation over
the shapes that approximate the type of content that is loading.
The following animation shows the app’s behavior: | https://docs.flutter.dev/cookbook/effects/shimmer-loading/index.html |
8ee8a55b05b5-1 | The following animation shows the app’s behavior:
This recipe begins with the content widgets defined and positioned.
There is also a Floating Action Button (FAB) in the bottom-right
corner that toggles between a loading mode and a loaded mode
so that you can easily validate your implementation.
Draw the shimmer shapes
The shapes that shimmer in this effect are independent
from the actual content that eventually loads.
Therefore, the goal is to display shapes that represent
the eventual content as accurately as possible.
Displaying accurate shapes is easy in situations where the
content has a clear boundary. For example, in this recipe,
there are some circular images and some rounded rectangle images.
You can draw shapes that precisely match the outlines
of those images. | https://docs.flutter.dev/cookbook/effects/shimmer-loading/index.html |
8ee8a55b05b5-2 | On the other hand, consider the text that appears beneath the
rounded rectangle images. You won’t know how many lines of
text exist until the text loads.
Therefore, there is no point in trying to draw a rectangle
for every line of text. Instead, while the data is loading,
you draw a couple of very thin rounded rectangles that
represent the text that will appear. The shape and size
doesn’t quite match, but that is OK.
Start with the circular list items at the top of the screen.
Ensure that each CircleListItem widget displays a circle
with a color while the image is loading.
As long as your widgets display some kind of shape,
you can apply the shimmer effect in this recipe.
Similar to the CircleListItem widgets,
ensure that the CardListItem widgets
display a color where the image will appear.
Also, in the CardListItem widget,
switch between the display of the text and
the rectangles based on the current loading status. | https://docs.flutter.dev/cookbook/effects/shimmer-loading/index.html |
8ee8a55b05b5-3 | Your UI now renders itself differently depending on
whether it’s loading or loaded.
By temporarily commenting out the image URLs,
you can see the two ways your UI renders.
The next goal is to paint all of the colored areas
with a single gradient that looks like a shimmer.
Paint the shimmer gradient
The key to the effect achieved in this recipe is to use a widget
called ShaderMask. The ShaderMask widget, as the name suggests,
applies a shader to its child, but only in the areas where
the child already painted something. For example,
you’ll apply a shader to only the black shapes that you
configured earlier.
Define a chrome-colored, linear gradient that gets applied to the
shimmer shapes.
Wrap your CircleListItem widgets with a ShimmerLoading widget.
Wrap your CardListItem widgets with a ShimmerLoading widget. | https://docs.flutter.dev/cookbook/effects/shimmer-loading/index.html |
8ee8a55b05b5-4 | Wrap your CardListItem widgets with a ShimmerLoading widget.
When your shapes are loading, they now display
the shimmer gradient that is
returned from the shaderCallback.
This is a big step in the right direction,
but there’s a problem with this gradient display.
Each CircleListItem widget and each CardListItem widget
displays a new version of the gradient.
For this recipe, the entire screen should
look like one, big shimmering surface.
You solve this problem in the next step.
Paint one big shimmer
To paint one big shimmer across the screen,
each ShimmerLoading widget needs
to paint the same full-screen gradient based
on the position of that ShimmerLoading
widget on the screen. | https://docs.flutter.dev/cookbook/effects/shimmer-loading/index.html |
8ee8a55b05b5-5 | To be more precise, rather than assume that the shimmer
should take up the entire screen,
there should be some area that shares the shimmer.
Maybe that area takes up the entire screen,
or maybe it doesn’t. The way to solve this
kind of problem in Flutter is to define another widget
that sits above all of the ShimmerLoading widgets
in the widget tree, and call it Shimmer.
Then, each ShimmerLoading widget gets a reference
to the Shimmer ancestor
and requests the desired size and gradient to display.
Define a new stateful widget called Shimmer that
takes in a LinearGradient and provides descendants
with access to its State object.
Wrap all of your screen’s content with the Shimmer widget.
Use the Shimmer widget within your
ShimmerLoading widget to paint the shared gradient.
Your ShimmerLoading widgets now display a shared
gradient that takes up all of the space within the
Shimmer widget.
Animate the shimmer | https://docs.flutter.dev/cookbook/effects/shimmer-loading/index.html |
8ee8a55b05b5-6 | Animate the shimmer
The shimmer gradient needs to move in order to
give the appearance of a shimmering shine.
The LinearGradient has a property called transform
that can be used to transform the appearance of the gradient,
for example, to move it horizontally.
The transform property accepts a GradientTransform instance.
Define a class called _SlidingGradientTransform that implements
GradientTransform to achieve the appearance of horizontal sliding.
The gradient slide percentage changes over time
in order to create the appearance of motion.
To change the percentage, configure an
AnimationController in the ShimmerState class.
Apply the _SlidingGradientTransform to the gradient
by using the _shimmerController’s value as the slidePercent.
The gradient now animates, but your individual
ShimmerLoading widgets don’t repaint themselves
as the gradient changes. Therefore, it looks like nothing
is happening. | https://docs.flutter.dev/cookbook/effects/shimmer-loading/index.html |
8ee8a55b05b5-7 | Expose the _shimmerController from ShimmerState
as a Listenable.
In ShimmerLoading, listen for changes to the ancestor
ShimmerState’s shimmerChanges property,
and repaint the shimmer gradient.
Congratulations!
You now have a full-screen,
animated shimmer effect that turns
on and off as the content loads.
Note:
This recipe doesn’t provide an interactive DartPad because
ShaderMask widgets have not yet been implemented for the web.
You can run this recipe on a mobile or desktop device by
cloning the example code. See the “UI loading animation”
example under the “cookbook” directory.
Create a scrolling parallax effect
Create a staggered menu animation | https://docs.flutter.dev/cookbook/effects/shimmer-loading/index.html |
3ca106db67a6-0 | Create a shimmer loading effect
Create a typing indicator
Create a staggered menu animation
Cookbook
Effects
Create a staggered menu animation
Create the menu without animations
Prepare for animations
Animate the list items and button
Interactive example
A single app screen might contain multiple animations.
Playing all of the animations at the same time can be
overwhelming. Playing the animations one after the other
can take too long. A better option is to stagger the animations.
Each animation begins at a different time,
but the animations overlap to create a shorter duration.
In this recipe, you build a drawer menu with animated
content that is staggered and has a button that pops
in at the bottom.
The following animation shows the app’s behavior:
Create the menu without animations | https://docs.flutter.dev/cookbook/effects/staggered-menu-animation/index.html |
3ca106db67a6-1 | Create the menu without animations
The drawer menu displays a list of titles,
followed by a Get started button at
the bottom of the menu.
Define a stateful widget called Menu
that displays the list and button
in static locations.
Prepare for animations
Control of the animation timing requires an
AnimationController.
Add the SingleTickerProviderStateMixin
to the MenuState class. Then, declare and
instantiate an AnimationController.
The length of the delay before every animation is
up to you. Define the animation delays,
individual animation durations, and the total
animation duration. | https://docs.flutter.dev/cookbook/effects/staggered-menu-animation/index.html |
3ca106db67a6-2 | In this case, all the animations are delayed by 50 ms.
After that, list items begin to appear.
Each list item’s appearance is delayed by 50 ms after the
previous list item begins to slide in.
Each list item takes 250 ms to slide from right to left.
After the last list item begins to slide in,
the button at the bottom waits another 150 ms to pop in.
The button animation takes 500 ms.
With each delay and animation duration defined,
the total duration is calculated so that it can be
used to calculate the individual animation times.
The desired animation times are shown in the following diagram: | https://docs.flutter.dev/cookbook/effects/staggered-menu-animation/index.html |
3ca106db67a6-3 | The desired animation times are shown in the following diagram:
To animate a value during a subsection of a larger animation,
Flutter provides the Interval class.
An Interval takes a start time percentage and an end
time percentage. That Interval can then be used to
animate a value between those start and end times,
instead of using the entire animation’s start and
end times. For example, given an animation that takes 1 second,
an interval from 0.2 to 0.5 would start at 200 ms
(20%) and end at 500 ms (50%).
Declare and calculate each list item’s Interval and the
bottom button Interval.
Animate the list items and button
The staggered animation plays as soon as the menu becomes visible.
Start the animation in initState().
Each list item slides from right to left and
fades in at the same time. | https://docs.flutter.dev/cookbook/effects/staggered-menu-animation/index.html |
3ca106db67a6-4 | Each list item slides from right to left and
fades in at the same time.
Use the list item’s Interval and an easeOut
curve to animate the opacity and translation
values for each list item.
Use the same approach to animate the opacity and
scale of the bottom button. This time, use an
elasticOut curve to give the button a springy effect.
Congratulations!
You have an animated menu where the appearance of each
list item is staggered, followed by a bottom button that
pops into place.
Interactive example
Create a shimmer loading effect
Create a typing indicator | https://docs.flutter.dev/cookbook/effects/staggered-menu-animation/index.html |
3af7c9f2c09b-0 | Create a staggered menu animation
Create an expandable FAB
Create a typing indicator
Cookbook
Effects
Create a typing indicator
Define the typing indicator widget
Make room for the typing indicator
Animate the speech bubbles
Animate the flashing circles
Interactive example
Modern chat apps display indicators when other users
are actively typing responses. These indicators help
prevent rapid and conflicting responses between you
and the other person. In this recipe, you build a
speech bubble typing indicator that animates in and out of view.
The following animation shows the app’s behavior:
Define the typing indicator widget | https://docs.flutter.dev/cookbook/effects/typing-indicator/index.html |
3af7c9f2c09b-1 | Define the typing indicator widget
The typing indicator exists within its own widget so that
it can be used anywhere in your app. As with any widget
that controls animations, the typing indicator needs to
be a stateful widget. The widget accepts a boolean value
that determines whether the indicator is visible.
This speech-bubble-typing indicator accepts a color
for the bubbles and two colors for the light and dark
phases of the flashing circles within the large speech bubble.
Define a new stateful widget called TypingIndicator.
Make room for the typing indicator
The typing indicator doesn’t occupy any space when it
isn’t displayed. Therefore, the indicator needs to grow
in height when it appears, and shrink in height
when it disappears. | https://docs.flutter.dev/cookbook/effects/typing-indicator/index.html |
3af7c9f2c09b-2 | The height of the typing indicator could be the natural
height of the speech bubbles within the typing indicator.
However, the speech bubbles expand with an elastic curve.
This elasticity would be too visually jarring if it quickly
pushed all the conversation messages up or down. Instead,
the height of the typing indicator animates on its own,
smoothly expanding before the bubbles appear.
When the bubbles disappear, the height smoothly contracts to zero.
This behavior requires an explicit animation for the
height of the typing indicator.
Define an animation for the height of the typing indicator,
and then apply that animated value to the SizedBox
widget within the typing indicator.
The TypingIndicator runs an animation forward or backward
depending on whether the incoming showIndicator variable
is true or false, respectively. | https://docs.flutter.dev/cookbook/effects/typing-indicator/index.html |
3af7c9f2c09b-3 | The animation that controls the height uses different
animation curves depending on its direction.
When the animation moves forward, it needs to quickly make
space for the speech bubbles. For this reason,
the forward curve runs the entire height animation within
the first 40% of the overall appearance animation.
When the animation reverses, it needs to give the speech bubbles
enough time to disappear before contracting the height.
An ease-out curve that uses all the available time is a
good way to accomplish this behavior.
Animate the speech bubbles
The typing indicator displays three speech bubbles.
The first two bubbles are small and round. The third
bubble is oblong and contains a few flashing circles.
These bubbles are staggered in position from the lower
left of the available space. | https://docs.flutter.dev/cookbook/effects/typing-indicator/index.html |
3af7c9f2c09b-4 | Each bubble appears by animating its scale from 0% to 100%,
and each bubble does this at slightly different times so
that it looks like each bubble appears after the one before it.
This is called a staggered animation.
Paint the three bubbles in the desired positions from the
lower left. Then, animate the scale of the bubbles
so that the bubbles are staggered whenever the showIndicator
property changes.
Animate the flashing circles
Within the large speech bubble, the typing indicator
displays three small circles that flash repeatedly.
Each circle flashes at a slightly different time,
giving the impression that a single light source is
moving behind each circle. This flashing animation
repeats indefinitely.
Introduce a repeating AnimationController to
implement the circle flashing and pass it to the
StatusBubble. | https://docs.flutter.dev/cookbook/effects/typing-indicator/index.html |
3af7c9f2c09b-5 | Each circle calculates its color using a sine (sin)
function so that the color changes gradually at the
minimum and maximum points. Additionally,
each circle animates its color within a specified interval
that takes up a portion of the overall animation time.
The position of these intervals generates the visual
effect of a single light source moving behind the three dots.
Congratulations! You now have a typing indicator that lets users
know when someone else is typing. The indicator animates in and out,
and displays a repeating animation while the other user is typing.
Interactive example
Run the app:
Click the round on/off switch at the bottom
of the screen to turn the typing indicator bubble
on and off.
Create a staggered menu animation
Create an expandable FAB | https://docs.flutter.dev/cookbook/effects/typing-indicator/index.html |
c3f7df168026-0 | Retrieve the value of a text field
Add Material touch ripples
Focus and text fields
Cookbook
Forms
Focus and text fields
Focus a text field as soon as it’s visible
Focus a text field when a button is tapped
1. Create a FocusNode
2. Pass the FocusNode to a TextField
3. Give focus to the TextField when a button is tapped
Interactive example
When a text field is selected and accepting input,
it is said to have “focus.”
Generally, users shift focus to a text field by tapping,
and developers shift focus to a text field programmatically by
using the tools described in this recipe. | https://docs.flutter.dev/cookbook/forms/focus/index.html |
c3f7df168026-1 | Managing focus is a fundamental tool for creating forms with an intuitive
flow. For example, say you have a search screen with a text field.
When the user navigates to the search screen,
you can set the focus to the text field for the search term.
This allows the user to start typing as soon as the screen
is visible, without needing to manually tap the text field.
In this recipe, learn how to give the focus
to a text field as soon as it’s visible,
as well as how to give focus to a text field
when a button is tapped.
Focus a text field as soon as it’s visible
To give focus to a text field as soon as it’s visible,
use the autofocus property.
TextField
autofocus:
true
);
For more information on handling input and creating text fields,
see the Forms section of the cookbook.
Focus a text field when a button is tapped | https://docs.flutter.dev/cookbook/forms/focus/index.html |
c3f7df168026-2 | Focus a text field when a button is tapped
Rather than immediately shifting focus to a specific text field,
you might need to give focus to a text field at a later point in time.
In the real world, you might also need to give focus to a specific
text field in response to an API call or a validation error.
In this example, give focus to a text field after the user
presses a button using the following steps:
Create a FocusNode.
Pass the FocusNode to a TextField.
Give focus to the TextField when a button is tapped.
1. Create a FocusNode
First, create a FocusNode.
Use the FocusNode to identify a specific TextField in Flutter’s
“focus tree.” This allows you to give focus to the TextField
in the next steps. | https://docs.flutter.dev/cookbook/forms/focus/index.html |
c3f7df168026-3 | Since focus nodes are long-lived objects, manage the lifecycle
using a State object. Use the following instructions to create
a FocusNode instance inside the initState() method of a
State class, and clean it up in the dispose() method:
2. Pass the FocusNode to a TextField
Now that you have a FocusNode,
pass it to a specific TextField in the build() method.
3. Give focus to the TextField when a button is tapped
Finally, focus the text field when the user taps a floating
action button. Use the requestFocus() method to perform
this task.
Interactive example
Retrieve the value of a text field
Add Material touch ripples | https://docs.flutter.dev/cookbook/forms/focus/index.html |
9819f966f5a4-0 | Forms
Cookbook
Forms
Build a form with validation
Create and style a text field
Focus and text fields
Handle changes to a text field
Retrieve the value of a text field | https://docs.flutter.dev/cookbook/forms/index.html |
851a93473d17-0 | Create an expandable FAB
Focus and text fields
Retrieve the value of a text field
Cookbook
Forms
Retrieve the value of a text field
1. Create a TextEditingController
2. Supply the TextEditingController to a TextField
3. Display the current value of the text field
Interactive example
In this recipe,
learn how to retrieve the text a user has entered into a text field
using the following steps:
Create a TextEditingController.
Supply the TextEditingController to a TextField.
Display the current value of the text field.
1. Create a TextEditingController
To retrieve the text a user has entered into a text field,
create a TextEditingController
and supply it to a TextField or TextFormField. | https://docs.flutter.dev/cookbook/forms/retrieve-input/index.html |
851a93473d17-1 | Important: Call dispose of the TextEditingController when
you’ve finished using it. This ensures that you discard any resources
used by the object.
2. Supply the TextEditingController to a TextField
Now that you have a TextEditingController, wire it up
to a text field using the controller property:
3. Display the current value of the text field
After supplying the TextEditingController to the text field,
begin reading values. Use the text()
method provided by the TextEditingController to retrieve the
String that the user has entered into the text field.
The following code displays an alert dialog with the current
value of the text field when the user taps a floating action button.
Interactive example
Create an expandable FAB
Focus and text fields | https://docs.flutter.dev/cookbook/forms/retrieve-input/index.html |
e14db9e7fb96-0 | Create and style a text field
Retrieve the value of a text field
Handle changes to a text field
Cookbook
Forms
Handle changes to a text field
1. Supply an onChanged() callback to a TextField or a TextFormField
2. Use a TextEditingController
Create a TextEditingController
Connect the TextEditingController to a text field
Create a function to print the latest value
Listen to the controller for changes
Interactive example
In some cases, it’s useful to run a callback function every time the text
in a text field changes. For example, you might want to build a search
screen with autocomplete functionality where you want to update the
results as the user types.
How do you run a callback function every time the text changes?
With Flutter, you have two options:
Supply an onChanged() callback to a TextField or a TextFormField. | https://docs.flutter.dev/cookbook/forms/text-field-changes/index.html |
e14db9e7fb96-1 | Supply an onChanged() callback to a TextField or a TextFormField.
Use a TextEditingController.
1. Supply an onChanged() callback to a TextField or a TextFormField
The simplest approach is to supply an onChanged() callback to a
TextField or a TextFormField.
Whenever the text changes, the callback is invoked.
In this example, print the current value of the text field to the
console every time the text changes.
2. Use a TextEditingController
A more powerful, but more elaborate approach, is to supply a
TextEditingController as the controller
property of the TextField or a TextFormField.
To be notified when the text changes, listen to the controller
using the addListener() method using the following steps:
Create a TextEditingController.
Connect the TextEditingController to a text field.
Create a function to print the latest value. | https://docs.flutter.dev/cookbook/forms/text-field-changes/index.html |
e14db9e7fb96-2 | Create a function to print the latest value.
Listen to the controller for changes.
Create a TextEditingController
Create a TextEditingController:
Note:
Remember to dispose of the TextEditingController when it’s no
longer needed. This ensures that you discard any resources used
by the object.
Connect the TextEditingController to a text field
Supply the TextEditingController to either a TextField
or a TextFormField. Once you wire these two classes together,
you can begin listening for changes to the text field.
Create a function to print the latest value
You need a function to run every time the text changes.
Create a method in the _MyCustomFormState class that prints
out the current value of the text field.
Listen to the controller for changes | https://docs.flutter.dev/cookbook/forms/text-field-changes/index.html |
e14db9e7fb96-3 | Listen to the controller for changes
Finally, listen to the TextEditingController and call the
_printLatestValue() method when the text changes. Use the
addListener() method for this purpose.
Begin listening for changes when the
_MyCustomFormState class is initialized,
and stop listening when the _MyCustomFormState is disposed.
Interactive example
Create and style a text field
Retrieve the value of a text field | https://docs.flutter.dev/cookbook/forms/text-field-changes/index.html |
14f96c16047e-0 | Build a form with validation
Handle changes to a text field
Create and style a text field
Cookbook
Forms
Create and style a text field
TextField
TextFormField
Interactive example
Text fields allow users to type text into an app.
They are used to build forms,
send messages, create search experiences, and more.
In this recipe, explore how to create and style text fields.
Flutter provides two text fields:
TextField and TextFormField.
TextField
TextField is the most commonly used text input widget.
By default, a TextField is decorated with an underline.
You can add a label, icon, inline hint text, and error text by supplying an
InputDecoration as the decoration
property of the TextField.
To remove the decoration entirely (including the
underline and the space reserved for the label),
set the decoration to null. | https://docs.flutter.dev/cookbook/forms/text-input/index.html |
14f96c16047e-1 | To retrieve the value when it changes,
see the Handle changes to a text field recipe.
TextFormField
TextFormField wraps a TextField and integrates it
with the enclosing Form.
This provides additional functionality,
such as validation and integration with other
FormField widgets.
Interactive example
For more information on input validation, see the
Building a form with validation recipe.
Build a form with validation
Handle changes to a text field | https://docs.flutter.dev/cookbook/forms/text-input/index.html |
e728004b0c49-0 | Drag a UI element
Create and style a text field
Build a form with validation
Cookbook
Forms
Build a form with validation
1. Create a Form with a GlobalKey
2. Add a TextFormField with validation logic
3. Create a button to validate and submit the form
How does this work?
Interactive example
Apps often require users to enter information into a text field.
For example, you might require users to log in with an email address
and password combination.
To make apps secure and easy to use, check whether the
information the user has provided is valid. If the user has correctly filled
out the form, process the information. If the user submits incorrect
information, display a friendly error message letting them know what went
wrong.
In this example, learn how to add validation to a form that has
a single text field using the following steps: | https://docs.flutter.dev/cookbook/forms/validation/index.html |
e728004b0c49-1 | Create a Form with a GlobalKey.
Add a TextFormField with validation logic.
Create a button to validate and submit the form.
1. Create a Form with a GlobalKey
First, create a Form.
The Form widget acts as a container for grouping
and validating multiple form fields.
When creating the form, provide a GlobalKey.
This uniquely identifies the Form,
and allows validation of the form in a later step.
Tip:
Using a GlobalKey is the recommended way to access a form.
However, if you have a more complex widget tree,
you can use the Form.of() method to
access the form within nested widgets.
2. Add a TextFormField with validation logic | https://docs.flutter.dev/cookbook/forms/validation/index.html |
e728004b0c49-2 | 2. Add a TextFormField with validation logic
Although the Form is in place,
it doesn’t have a way for users to enter text.
That’s the job of a TextFormField.
The TextFormField widget renders a material design text field
and can display validation errors when they occur.
Validate the input by providing a validator() function to the
TextFormField. If the user’s input isn’t valid,
the validator function returns a String containing
an error message.
If there are no errors, the validator must return null.
For this example, create a validator that ensures the
TextFormField isn’t empty. If it is empty,
return a friendly error message.
3. Create a button to validate and submit the form
Now that you have a form with a text field,
provide a button that the user can tap to submit the information. | https://docs.flutter.dev/cookbook/forms/validation/index.html |
e728004b0c49-3 | When the user attempts to submit the form, check if the form is valid.
If it is, display a success message.
If it isn’t (the text field has no content) display the error message.
How does this work?
To validate the form, use the _formKey created in
step 1. You can use the _formKey.currentState()
method to access the FormState,
which is automatically created by Flutter when building a Form.
Interactive example
Drag a UI element
Create and style a text field | https://docs.flutter.dev/cookbook/forms/validation/index.html |
7af096deb78c-0 | Handle taps
Display images from the internet
Implement swipe to dismiss
Cookbook
Gestures
Implement swipe to dismiss
1. Create a list of items
Create a data source
Convert the data source into a list
2. Wrap each item in a Dismissible widget
3. Provide “leave behind” indicators
Interactive example
The “swipe to dismiss” pattern is common in many mobile apps.
For example, when writing an email app,
you might want to allow a user to swipe away
email messages to delete them from a list.
Flutter makes this task easy by providing the
Dismissible widget.
Learn how to implement swipe to dismiss with the following steps:
Create a list of items.
Wrap each item in a Dismissible widget. | https://docs.flutter.dev/cookbook/gestures/dismissible/index.html |
7af096deb78c-1 | Wrap each item in a Dismissible widget.
Provide “leave behind” indicators.
1. Create a list of items
First, create a list of items. For detailed
instructions on how to create a list,
follow the Working with long lists recipe.
Create a data source
In this example,
you want 20 sample items to work with.
To keep it simple, generate a list of strings.
Convert the data source into a list
Display each item in the list on screen. Users won’t
be able to swipe these items away just yet.
2. Wrap each item in a Dismissible widget
In this step,
give users the ability to swipe an item off the list by using the
Dismissible widget. | https://docs.flutter.dev/cookbook/gestures/dismissible/index.html |
7af096deb78c-2 | After the user has swiped away the item,
remove the item from the list and display a snackbar.
In a real app, you might need to perform more complex logic,
such as removing the item from a web service or database.
Update the itemBuilder() function to return a Dismissible widget:
3. Provide “leave behind” indicators
As it stands,
the app allows users to swipe items off the list, but it doesn’t
give a visual indication of what happens when they do.
To provide a cue that items are removed,
display a “leave behind” indicator as they
swipe the item off the screen. In this case,
the indicator is a red background.
To add the indicator,
provide a background parameter to the Dismissible.
lib/{step2.dart (Dismissible) → main.dart (Dismissible)}
@@ -16,6 +16,8 @@ | https://docs.flutter.dev/cookbook/gestures/dismissible/index.html |
7af096deb78c-3 | @@ -16,6 +16,8 @@
16
16
ScaffoldMessenger.of(context)
17
17
.showSnackBar(SnackBar(content: Text('$item dismissed')));
18
18
},
19
+
// Show a red background as the item is swiped away.
20
+
background: Container(color: Colors.red),
19
21
child: ListTile(
20
22
title: Text(item),
21
23
),
Interactive example
Handle taps
Display images from the internet | https://docs.flutter.dev/cookbook/gestures/dismissible/index.html |
1a26ce5e03ad-0 | Add Material touch ripples
Implement swipe to dismiss
Handle taps
Cookbook
Gestures
Handle taps
Notes
Interactive example
You not only want to display information to users,
you want users to interact with your app.
Use the GestureDetector widget to respond
to fundamental actions, such as tapping and dragging.
Note:
To learn more, watch this short Widget of the Week video on the GestureDetector widget:
This recipe shows how to make a custom button that shows
a snackbar when tapped with the following steps:
Create the button.
Wrap it in a GestureDetector that an onTap() callback.
Notes
For information on adding the Material ripple effect to your
button, see the Add Material touch ripples recipe. | https://docs.flutter.dev/cookbook/gestures/handling-taps/index.html |
1a26ce5e03ad-1 | Although this example creates a custom button,
Flutter includes a handful of button implementations, such as:
ElevatedButton, TextButton, and
CupertinoButton.
Interactive example
Add Material touch ripples
Implement swipe to dismiss | https://docs.flutter.dev/cookbook/gestures/handling-taps/index.html |
e61a53daea2d-0 | Gestures
Cookbook
Gestures
Add Material touch ripples
Handle taps
Implement swipe to dismiss | https://docs.flutter.dev/cookbook/gestures/index.html |
13230da44f69-0 | Retrieve the value of a text field
Handle taps
Add Material touch ripples
Cookbook
Gestures
Add Material touch ripples
Interactive example
Widgets that follow the Material Design guidelines display
a ripple animation when tapped.
Flutter provides the InkWell
widget to perform this effect.
Create a ripple effect using the following steps:
Create a widget that supports tap.
Wrap it in an InkWell widget to manage tap callbacks and
ripple animations.
Interactive example
Retrieve the value of a text field
Handle taps | https://docs.flutter.dev/cookbook/gestures/ripples/index.html |
05ef46d0bafe-0 | Fade in images with a placeholder
Use lists
Work with cached images
Cookbook
Images
Work with cached images
Adding a placeholder
Complete example
In some cases, it’s handy to cache images as they’re downloaded from the
web, so they can be used offline. For this purpose,
use the cached_network_image package.
Note:
To learn more, watch this short Package of the Week video on the cached_network_image package:
In addition to caching, the cached_network_image
package also supports placeholders and fading images
in as they’re loaded.
Adding a placeholder
The cached_network_image package allows you to use any widget as a
placeholder. In this example, display a spinner while the image loads.
Complete example
Fade in images with a placeholder
Use lists | https://docs.flutter.dev/cookbook/images/cached-images/index.html |
836ed7deb43d-0 | Display images from the internet
Work with cached images
Fade in images with a placeholder
Cookbook
Images
Fade in images with a placeholder
In-Memory
Complete example
From asset bundle
Complete example
When displaying images using the default Image widget,
you might notice they simply pop onto the screen as they’re loaded.
This might feel visually jarring to your users.
Instead, wouldn’t it be nice to display a placeholder at first,
and images would fade in as they’re loaded? Use the
FadeInImage widget for exactly this purpose.
FadeInImage works with images of any type: in-memory, local assets,
or images from the internet.
In-Memory
In this example, use the transparent_image
package for a simple transparent placeholder.
Complete example
From asset bundle | https://docs.flutter.dev/cookbook/images/fading-in-images/index.html |
836ed7deb43d-1 | Complete example
From asset bundle
You can also consider using local assets for placeholders.
First, add the asset to the project’s pubspec.yaml file
(for more details, see Adding assets and images):
+ - assets/loading.gif
Then, use the FadeInImage.assetNetwork() constructor:
Complete example
Display images from the internet
Work with cached images | https://docs.flutter.dev/cookbook/images/fading-in-images/index.html |
e9bbcf82964e-0 | Images
Cookbook
Images
Display images from the internet
Fade in images with a placeholder
Work with cached images | https://docs.flutter.dev/cookbook/images/index.html |
2fd7977db626-0 | Implement swipe to dismiss
Fade in images with a placeholder
Display images from the internet
Cookbook
Images
Display images from the internet
Bonus: animated gifs
Placeholders and caching
Interactive example
Displaying images is fundamental for most mobile apps.
Flutter provides the Image widget to
display different types of images.
To work with images from a URL, use the
Image.network() constructor.
Bonus: animated gifs
One useful thing about the Image widget:
It supports animated gifs.
Placeholders and caching
The default Image.network constructor doesn’t handle more advanced
functionality, such as fading images in after loading, or caching images
to the device after they’re downloaded. To accomplish these tasks, see
the following recipes:
Fade in images with a placeholder | https://docs.flutter.dev/cookbook/images/network-image/index.html |
2fd7977db626-1 | Fade in images with a placeholder
Work with cached images
Interactive example
Implement swipe to dismiss
Fade in images with a placeholder | https://docs.flutter.dev/cookbook/images/network-image/index.html |
bc3a44873072-0 | Cookbook
Animation
Design
Effects
Forms
Gestures
Images
Lists
Maintenance
Navigation
Networking
Persistence
Plugins
Testing
Integration
Unit
Widget
This cookbook contains recipes that demonstrate how to solve common problems
while writing Flutter apps. Each recipe is self-contained and can be used as a
reference to help you build up an application.
Animation
Animate a page route transition
Animate a widget using a physics simulation
Animate the properties of a container
Fade a widget in and out
Design
Add a drawer to a screen
Display a snackbar
Export fonts from a package | https://docs.flutter.dev/cookbook/index.html |
bc3a44873072-1 | Display a snackbar
Export fonts from a package
Update the UI based on orientation
Use a custom font
Use themes to share colors and font styles
Work with tabs
Effects
Create a download button
Create a nested navigation flow
Create a photo filter carousel
Create a scrolling parallax effect
Create a shimmer loading effect
Create a staggered menu animation
Create a typing indicator
Create an expandable FAB
Create gradient chat bubbles
Drag a UI element
Forms
Build a form with validation
Create and style a text field
Focus and text fields
Handle changes to a text field
Retrieve the value of a text field
Gestures | https://docs.flutter.dev/cookbook/index.html |
bc3a44873072-2 | Retrieve the value of a text field
Gestures
Add Material touch ripples
Handle taps
Implement swipe to dismiss
Images
Display images from the internet
Fade in images with a placeholder
Work with cached images
Lists
Create a grid list
Create a horizontal list
Create lists with different types of items
Place a floating app bar above a list
Use lists
Work with long lists
Maintenance
Report errors to a service
Navigation
Animate a widget across screens
Navigate to a new screen and back
Navigate with named routes
Pass arguments to a named route
Set up app links for Android
Set up universal links for iOS | https://docs.flutter.dev/cookbook/index.html |
bc3a44873072-3 | Set up app links for Android
Set up universal links for iOS
Return data from a screen
Send data to a new screen
Networking
Fetch data from the internet
Make authenticated requests
Parse JSON in the background
Send data to the internet
Update data over the internet
Delete data on the internet
Work with WebSockets
Persistence
Persist data with SQLite
Read and write files
Store key-value data on disk
Plugins
Play and pause a video
Take a picture using the camera
Testing
Integration
An introduction to integration testing
Performance profiling
Unit
An introduction to unit testing
Mock dependencies using Mockito
Widget | https://docs.flutter.dev/cookbook/index.html |
bc3a44873072-4 | Mock dependencies using Mockito
Widget
An introduction to widget testing
Find widgets
Handle scrolling
Tap, drag, and enter text | https://docs.flutter.dev/cookbook/index.html |
50010c6b7544-0 | Work with cached images
Create a horizontal list
Use lists
Cookbook
Lists
Use lists
Create a ListView
Interactive example
Displaying lists of data is a fundamental pattern for mobile apps.
Flutter includes the ListView
widget to make working with lists a breeze.
Create a ListView
Using the standard ListView constructor is
perfect for lists that contain only a few items.
The built-in ListTile
widget is a way to give items a visual structure.
Interactive example
Work with cached images
Create a horizontal list | https://docs.flutter.dev/cookbook/lists/basic-list/index.html |
5c117b2fe6d0-0 | Create lists with different types of items
Work with long lists
Place a floating app bar above a list
Cookbook
Lists
Place a floating app bar above a list
1. Create a CustomScrollView
2. Use SliverAppBar to add a floating app bar
3. Add a list of items using a SliverList
Interactive example
To make it easier for users to view a list of items,
you might want to hide the app bar as the user scrolls down the list.
This is especially true if your app displays a “tall”
app bar that occupies a lot of vertical space.
Typically, you create an app bar by providing an appBar property to the
Scaffold widget. This creates a fixed app bar that always remains above
the body of the Scaffold. | https://docs.flutter.dev/cookbook/lists/floating-app-bar/index.html |
5c117b2fe6d0-1 | Moving the app bar from a Scaffold widget into a
CustomScrollView allows you to create an app bar
that scrolls offscreen as you scroll through a
list of items contained inside the CustomScrollView.
This recipe demonstrates how to use a CustomScrollView to display a list of
items with an app bar on top that scrolls offscreen as the user scrolls
down the list using the following steps:
Create a CustomScrollView.
Use SliverAppBar to add a floating app bar.
Add a list of items using a SliverList.
1. Create a CustomScrollView
To create a floating app bar, place the app bar inside a
CustomScrollView that also contains the list of items.
This synchronizes the scroll position of the app bar and the list of items.
You might think of the CustomScrollView widget as a ListView
that allows you to mix and match different types of scrollable lists
and widgets together. | https://docs.flutter.dev/cookbook/lists/floating-app-bar/index.html |
5c117b2fe6d0-2 | For this example, create a CustomScrollView that contains a
SliverAppBar and a SliverList. In addition, remove any app bars
that you provide to the Scaffold widget.
2. Use SliverAppBar to add a floating app bar
Next, add an app bar to the CustomScrollView.
Flutter provides the SliverAppBar widget which,
much like the normal AppBar widget,
uses the SliverAppBar to display a title,
tabs, images and more.
However, the SliverAppBar also gives you the ability to create a “floating”
app bar that scrolls offscreen as the user scrolls down the list.
Furthermore, you can configure the SliverAppBar to shrink and
expand as the user scrolls.
To create this effect:
Start with an app bar that displays only a title.
Set the floating property to true.
This allows users to quickly reveal the app bar when
they scroll up the list. | https://docs.flutter.dev/cookbook/lists/floating-app-bar/index.html |
5c117b2fe6d0-3 | Add a flexibleSpace widget that fills the available
expandedHeight.
Tip:
Play around with the
various properties you can pass to the SliverAppBar widget,
and use hot reload to see the results. For example, use an Image
widget for the flexibleSpace property to create a background image that
shrinks in size as it’s scrolled offscreen.
3. Add a list of items using a SliverList
Now that you have the app bar in place, add a list of items to the
CustomScrollView. You have two options: a SliverList
or a SliverGrid. If you need to display a list of items one after the other,
use the SliverList widget.
If you need to display a grid list, use the SliverGrid widget.
SliverChildDelegate, which provides a list
of widgets to
SliverChildBuilderDelegate
allows you to create a list of items that are built lazily as you scroll,
just like the | https://docs.flutter.dev/cookbook/lists/floating-app-bar/index.html |
5c117b2fe6d0-4 | Interactive example
Create lists with different types of items
Work with long lists | https://docs.flutter.dev/cookbook/lists/floating-app-bar/index.html |
8f2674c9ac1b-0 | Create a horizontal list
Create lists with different types of items
Create a grid list
Cookbook
Lists
Create a grid list
Interactive example
In some cases, you might want to display your items as a grid rather than
a normal list of items that come one after the next.
For this task, use the GridView widget.
The simplest way to get started using grids is by using the
GridView.count() constructor,
because it allows you to specify how many rows or columns you’d like.
To visualize how GridView works,
generate a list of 100 widgets that display their index in the list.
Interactive example
Create a horizontal list
Create lists with different types of items | https://docs.flutter.dev/cookbook/lists/grid-lists/index.html |
6db9d15dbd28-0 | Use lists
Create a grid list
Create a horizontal list
Cookbook
Lists
Create a horizontal list
Interactive example
You might want to create a list that scrolls
horizontally rather than vertically.
The ListView widget supports horizontal lists.
Use the standard ListView constructor, passing in a horizontal
scrollDirection, which overrides the default vertical direction.
Interactive example
Use lists
Create a grid list | https://docs.flutter.dev/cookbook/lists/horizontal-list/index.html |
b72eaba32151-0 | Lists
Cookbook
Lists
Create a grid list
Create a horizontal list
Create lists with different types of items
Place a floating app bar above a list
Use lists
Work with long lists | https://docs.flutter.dev/cookbook/lists/index.html |
cebb648bb1da-0 | Place a floating app bar above a list
Report errors to a service
Work with long lists
Cookbook
Lists
Work with long lists
1. Create a data source
2. Convert the data source into widgets
Interactive example
Children’s extent
The standard ListView constructor works well
for small lists. To work with lists that contain
a large number of items, it’s best to use the
ListView.builder constructor.
In contrast to the default ListView constructor, which requires
creating all items at once, the ListView.builder() constructor
creates items as they’re scrolled onto the screen.
1. Create a data source
First, you need a data source. For example, your data source
might be a list of messages, search results, or products in a store.
Most of the time, this data comes from the internet or a database. | https://docs.flutter.dev/cookbook/lists/long-lists/index.html |
cebb648bb1da-1 | For this example, generate a list of 10,000 Strings using the
List.generate constructor.
2. Convert the data source into widgets
To display the list of strings, render each String as a widget
using ListView.builder().
In this example, display each String on its own line.
Interactive example
Children’s extent
To specify each item’s extent, you can use either itemExtent or prototypeItem.
Specifying either is more efficient than letting the children determine their own extent
because the scrolling machinery can make use of the foreknowledge of the children’s
extent to save work, for example when the scroll position changes drastically.
Place a floating app bar above a list
Report errors to a service | https://docs.flutter.dev/cookbook/lists/long-lists/index.html |
ba32ebc3231f-0 | Create a grid list
Place a floating app bar above a list
Create lists with different types of items
Cookbook
Lists
Create lists with different types of items
1. Create a data source with different types of items
Types of items
Create a list of items
2. Convert the data source into a list of widgets
Interactive example
You might need to create lists that display different types of content.
For example, you might be working on a list that shows a heading
followed by a few items related to the heading, followed by another heading,
and so on.
Here’s how you can create such a structure with Flutter:
Create a data source with different types of items.
Convert the data source into a list of widgets.
1. Create a data source with different types of items
Types of items | https://docs.flutter.dev/cookbook/lists/mixed-list/index.html |
ba32ebc3231f-1 | Types of items
To represent different types of items in a list, define
a class for each type of item.
In this example, create an app that shows a header followed by five
messages. Therefore, create three classes: ListItem, HeadingItem,
and MessageItem.
Create a list of items
Most of the time, you would fetch data from the internet or a local
database and convert that data into a list of items.
For this example, generate a list of items to work with. The list
contains a header followed by five messages. Each message has one
of 3 types: ListItem, HeadingItem, or MessageItem.
2. Convert the data source into a list of widgets
To convert each item into a widget,
use the ListView.builder() constructor.
In general, provide a builder function that checks for what type
of item you’re dealing with, and returns the appropriate widget
for that type of item.
Interactive example | https://docs.flutter.dev/cookbook/lists/mixed-list/index.html |
ba32ebc3231f-2 | Interactive example
Create a grid list
Place a floating app bar above a list | https://docs.flutter.dev/cookbook/lists/mixed-list/index.html |
86d7fc6a8769-0 | Work with long lists
Animate a widget across screens
Report errors to a service
Cookbook
Maintenance
Report errors to a service
1. Get a DSN from Sentry
2. Import the Sentry package
3. Initialize the Sentry SDK
What does that give me?
4. Capture errors programatically
Learn more
Complete example
While one always tries to create apps that are free of bugs,
they’re sure to crop up from time to time.
Since buggy apps lead to unhappy users and customers,
it’s important to understand how often your users
experience bugs and where those bugs occur.
That way, you can prioritize the bugs with the
highest impact and work to fix them. | https://docs.flutter.dev/cookbook/maintenance/error-reporting/index.html |
86d7fc6a8769-1 | How can you determine how often your users experiences bugs?
Whenever an error occurs, create a report containing the
error that occurred and the associated stacktrace.
You can then send the report to an error tracking
service, such as Bugsnag, Fabric, Firebase Crashlytics, Rollbar, or Sentry.
The error tracking service aggregates all of the crashes your users
experience and groups them together. This allows you to know how often your
app fails and where the users run into trouble.
In this recipe, learn how to report errors to the
Sentry crash reporting service using
the following steps:
Get a DSN from Sentry.
Import the Flutter Sentry package
Initialize the Sentry SDK
Capture errors programmatically
1. Get a DSN from Sentry
Before reporting errors to Sentry, you need a “DSN” to uniquely identify
your app with the Sentry.io service. | https://docs.flutter.dev/cookbook/maintenance/error-reporting/index.html |
86d7fc6a8769-2 | To get a DSN, use the following steps:
Create an account with Sentry.
Log in to the account.
Create a new Flutter project.
Copy the code snippet that includes the DSN.
2. Import the Sentry package
Import the sentry_flutter package into the app.
The sentry package makes it easier to send
error reports to the Sentry error tracking service.
dependencies
sentry_flutter
<latest_version>
3. Initialize the Sentry SDK
Initialize the SDK to capture different unhandled errors automatically:
Alternatively, you can pass the DSN to Flutter using the dart-define tag:
What does that give me?
-dart-define
SENTRY_DSN
=https://[email protected]/example
What does that give me? | https://docs.flutter.dev/cookbook/maintenance/error-reporting/index.html |
86d7fc6a8769-3 | What does that give me?
This is all you need for Sentry to capture unhandled errors in Dart and native layers.
This includes Swift, Objective-C, C, and C++ on iOS, and Java, Kotlin, C, and C++ on Android.
4. Capture errors programatically
Besides the automatic error reporting that Sentry generates by
importing and initializing the SDK,
you can use the API to report errors to Sentry:
For more information, see the Sentry API docs on pub.dev.
Learn more
Extensive documentation about using the Sentry SDK can be found on Sentry’s site.
Complete example
To view a working example,
see the Sentry flutter example app.
Work with long lists
Animate a widget across screens | https://docs.flutter.dev/cookbook/maintenance/error-reporting/index.html |
63688096c27b-0 | Maintenance
Cookbook
Maintenance
Report errors to a service | https://docs.flutter.dev/cookbook/maintenance/index.html |
c092d5894025-0 | Report errors to a service
Navigate to a new screen and back
Animate a widget across screens
Cookbook
Navigation
Animate a widget across screens
1. Create two screens showing the same image
2. Add a Hero widget to the first screen
3. Add a Hero widget to the second screen
Interactive example
It’s often helpful to guide users through an app as they navigate from screen
to screen. A common technique to lead users through an app is to animate a
widget from one screen to the next. This creates a visual anchor connecting
the two screens.
Use the Hero widget
to animate a widget from one screen to the next.
This recipe uses the following steps:
Create two screens showing the same image.
Add a Hero widget to the first screen.
Add a Hero widget to the second screen. | https://docs.flutter.dev/cookbook/navigation/hero-animations/index.html |
c092d5894025-1 | Add a Hero widget to the second screen.
1. Create two screens showing the same image
In this example, display the same image on both screens.
Animate the image from the first screen to the second screen when
the user taps the image. For now, create the visual structure;
handle animations in the next steps.
Note:
This example builds upon the
Navigate to a new screen and back
and Handle taps recipes.
2. Add a Hero widget to the first screen
To connect the two screens together with an animation, wrap
the Image widget on both screens in a Hero widget.
The Hero widget requires two arguments:
An object that identifies the `Hero`.
It must be the same on both screens.
The widget to animate across screens.
3. Add a Hero widget to the second screen | https://docs.flutter.dev/cookbook/navigation/hero-animations/index.html |
c092d5894025-2 | 3. Add a Hero widget to the second screen
To complete the connection with the first screen,
wrap the Image on the second screen with a Hero
widget that has the same tag as the Hero in the first screen.
After applying the Hero widget to the second screen,
the animation between screens just works.
Note:
This code is identical to what you have on the first screen.
As a best practice, create a reusable widget instead of
repeating code. This example uses identical code for both
widgets, for simplicity.
Interactive example
Report errors to a service
Navigate to a new screen and back | https://docs.flutter.dev/cookbook/navigation/hero-animations/index.html |
f669fabee511-0 | Navigation
Cookbook
Navigation
Animate a widget across screens
Navigate to a new screen and back
Navigate with named routes
Pass arguments to a named route
Return data from a screen
Send data to a new screen
Set up app links for Android
Set up universal links for iOS | https://docs.flutter.dev/cookbook/navigation/index.html |
98f6e20a03d5-0 | Navigate to a new screen and back
Pass arguments to a named route
Navigate with named routes
Cookbook
Navigation
Navigate with named routes
1. Create two screens
2. Define the routes
3. Navigate to the second screen
4. Return to the first screen
Interactive example
Note:
Named routes are no longer recommended for most
applications. For more information, see
Limitations in the navigation overview page.
In the Navigate to a new screen and back recipe,
you learned how to navigate to a new screen by creating a new route and
pushing it to the Navigator.
However, if you need to navigate to the same screen in many parts
of your app, this approach can result in code duplication.
The solution is to define a named route,
and use the named route for navigation. | https://docs.flutter.dev/cookbook/navigation/named-routes/index.html |