id
stringlengths 14
17
| text
stringlengths 23
1.11k
| source
stringlengths 35
114
|
---|---|---|
770dd48484f7-1 | Flutter is different from other frameworks because its UI
is built in code, not (for example) in an XML file or similar.
Widgets are the basic building blocks of a Flutter UI.
As you progress through this codelab,
you’ll learn that almost everything in Flutter is a widget.
A widget is an immutable object that describes a specific part of a UI.
You’ll also learn that Flutter widgets are composable, meaning
that you can combine existing widgets to make more sophisticated widgets.
At the end of this codelab,
you’ll get to apply what you’ve learned
into building a Flutter UI that displays a business card.
Estimated time to complete this codelab: 45-60 minutes.
Row and Column classes
Example: Creating a Column
The following example displays the differences between
a Row and Column.
1. Click the Run button. | https://docs.flutter.dev/codelabs/layout-basics/index.html |
770dd48484f7-2 | 1. Click the Run button.
2. In the code, change the Row to a Column, and run again.
Axis size and alignment
So far, the BlueBox widgets have been squished together
(either to the left or at the top of the UI Output).
You can change how the BlueBox widgets are spaced
out using the axis size and alignment properties.
mainAxisSize property
Row and Column occupy all of the space on their main axes.
If the combined width of their children is
less than the total space on their main axes,
their children are laid out with extra space.
Row and Column only occupy enough space on their main axes
for their children. Their children are laid out without extra space
and at the middle of their main axes. | https://docs.flutter.dev/codelabs/layout-basics/index.html |
770dd48484f7-3 | Tip:
MainAxisSize.max is the mainAxisSize property’s default value.
If you don’t specify another value,
the default value is used,
as shown in the previous example.
Example: Modifying axis size
The following example explicitly sets mainAxisSize
to its default value, MainAxisSize.max.
1. Click the Run button.
2. Change MainAxisSize.max to MainAxisSize.min,
and run again.
mainAxisAlignment property
Positions children near the beginning of the main axis.
(Left for Row, top for Column)
Positions children near the end of the main axis.
(Right for Row, bottom for Column)
Positions children at the middle of the main axis.
Divides the extra space evenly between children.
Divides the extra space evenly between children
and before and after the children. | https://docs.flutter.dev/codelabs/layout-basics/index.html |
770dd48484f7-4 | Divides the extra space evenly between children
and before and after the children.
Similar to MainAxisAlignment.spaceEvenly,
but reduces half of the space before the first
child and after the last child
to half of the width between the children.
Example: Modifying main axis alignment
The following example explicitly sets
mainAxisAlignment to its default value,
MainAxisAlignment.start.
1. Click the Run button.
2. Change MainAxisAlignment.start to
MainAxisAlignment.end, and run again.
Tip:
Before moving to the next section,
change MainAxisAlignment.end to another value.
crossAxisAlignment property
Positions children near the start of the cross axis. (Top for Row, Left for Column)
Positions children near the end of the cross axis. (Bottom for Row, Right for Column) | https://docs.flutter.dev/codelabs/layout-basics/index.html |
770dd48484f7-5 | Positions children at the middle of the cross axis. (Middle for Row, Center for Column)
Stretches children across the cross axis.
(Top-to-bottom for Row, left-to-right for Column)
Aligns children by their character baselines.
(Text class only, and requires that the
textBaseline property is set to
TextBaseline.alphabetic. See the
Text widget section for an example.)
Example: Modifying cross axis alignment
The following example explicitly sets crossAxisAlignment
to its default value, CrossAxisAlignment.center.
To demonstrate cross axis alignment,
mainAxisAlignment is set to
MainAxisAlignment.spaceAround,
and Row now contains a BiggerBlueBox widget
that is taller than the BlueBox widgets.
1. Click the Run button.
2. Change CrossAxisAlignment.center to
CrossAxisAlignment.start, and run again. | https://docs.flutter.dev/codelabs/layout-basics/index.html |
770dd48484f7-6 | Tip:
Before moving to the next section,
change CrossAxisAlignment.start to another value.
Flexible widget
Compares itself against other flex
properties before determining what fraction of the
total remaining space each Flexible widget receives.
Determines whether a Flexible widget
fills all of its extra space.
Example: Changing fit properties
The following example demonstrates the fit property,
which can have one of two values:
The widget’s preferred size is used. (Default)
Forces the widget to fill all of its extra space.
In this example, change the fit properties to
make the Flexible widgets fill the extra space.
1. Click the Run button.
2. Change both fit values to FlexFit.tight,
and run again.
Example: Testing flex values | https://docs.flutter.dev/codelabs/layout-basics/index.html |
770dd48484f7-7 | Example: Testing flex values
When flex properties are compared against one another,
the ratio between their flex values determines
what fraction of the total remaining space each
Flexible widget receives.
remainingSpace
flex
totalOfAllFlexValues
In this example, the sum of the flex values (2),
determines that both Flexible widgets receive
half of the total remaining space.
The BlueBox widget (or fixed-size widget)
remains the same size.
Tip:
Before moving to the next example,
try changing the flex properties to other values,
such as 2 and 1.
Expanded widget
Similar to Flexible, the Expanded widget can
wrap a widget and force the widget to fill extra space.
Example: Filling extra space
The following example demonstrates how the
Expanded widget forces its child widget to
fill extra space. | https://docs.flutter.dev/codelabs/layout-basics/index.html |
770dd48484f7-8 | 1. Click the Run button.
2. Wrap the second BlueBox widget in an Expanded widget.
For example:
Expanded
child:
BlueBox
(),),
3. Select the Format button to properly format the code,
and run again.
SizedBox widget
Example: Resizing a widget
The following example wraps the middle BlueBox widget inside of a
SizedBox widget and sets the BlueBox’s width to 100 logical pixels.
1. Click the Run button.
2. Add a height property equal to 100 logical pixels
inside the SizedBox widget, and run again.
Example: Creating space | https://docs.flutter.dev/codelabs/layout-basics/index.html |
770dd48484f7-9 | Example: Creating space
The following example contains three BlueBox widgets
and one SizedBox widget that separates the first
and second BlueBox widgets. The SizedBox widget
contains a width property equal to 50 logical pixels.
1. Click the Run button.
2. Create more space by adding another
SizedBox widget (25 logical pixels wide)
between the second and third BlueBox widgets,
and run again.
Spacer widget
Similar to SizedBox, the Spacer widget also
can create space between widgets.
Example: Creating more space
The following example separates the first two
BlueBox widgets using a Spacer widget with
a flex value of 1.
1. Click the Run button.
2. Add another Spacer widget (also with a flex value of 1)
between the second and third BlueBox widgets. | https://docs.flutter.dev/codelabs/layout-basics/index.html |
770dd48484f7-10 | Text widget
The Text widget displays text and can be configured
for different fonts, sizes, and colors.
Example: Aligning text
The following example displays “Hey!” three times,
but at different font sizes and in different colors.
Row specifies the crossAxisAlignment
and textBaseline properties.
1. Click the Run button.
2. Change CrossAxisAlignment.center to
CrossAxisAlignment.baseline, and run again.
Icon widget
The Icon widget displays a graphical symbol
that represents an aspect of the UI.
Flutter is preloaded with icon packages for
Material and Cupertino applications.
Example: Creating an Icon
The following example displays the widget Icons.widget
from the Material Icon library in red and blue.
1. Click the Run button.
2. Add another Icon from the
Material Icon library
with a size of 50. | https://docs.flutter.dev/codelabs/layout-basics/index.html |
770dd48484f7-11 | 3. Give the Icon a color of Colors.amber from the
Material Color palette, and run again.
Image widget
The Image widget displays an image.
You either can reference images using a URL,
or you can include images inside your app package.
Since DartPad can’t package an image,
the following example uses an image from the network.
Example: Displaying an image
The following example displays an image that’s
stored remotely on GitHub.
The Image.network method takes a string
parameter that contains an image’s URL.
In this example, Image.network contains a non-working URL.
1. Click the Run button.
2. Change the non-working URL to the actual URL:
https://raw.githubusercontent.com/flutter/website/main/examples/layout/sizing/images/pic1.jpg | https://docs.flutter.dev/codelabs/layout-basics/index.html |
770dd48484f7-12 | 3. Then change pic1.jpg to pic2.jpg or pic3.jpg,
and run again.
Putting it all together
You’re almost at the end of this codelab.
If you’d like to test your knowledge of the
techniques that you’ve learned, why not apply
those skills into building a Flutter UI that
displays a business card!
You’ll break down Flutter’s layout into parts,
which is how you’d create a Flutter UI in the real world.
In Part 1,
you’ll implement a Column that contains the name and title.
Then you’ll wrap the Column in a Row that contains the icon,
which is positioned to the left of the name and title.
Part 2, you’ll wrap the
In Part 3, you’ll finish building
the business card display by adding four more icons,
which are positioned below the contact information.
Part 1 | https://docs.flutter.dev/codelabs/layout-basics/index.html |
770dd48484f7-13 | Part 1
Exercise: Create the name and title
Implement a Column that contains two text widgets:
The first Text widget has the name Flutter McFlutter and
the style property set to Theme.of(context).textTheme.headlineSmall.
The second Text widget contains the title Experienced App Developer.
For the Column,
set mainAxisSize to MainAxisSize.min
and crossAxisAlignment to CrossAxisAlignment.start.
Exercise: Wrap the Column in a Row
Wrap the Column you implemented in a
Row that contains the following widgets:
An Icon widget set to Icons.account_circle
and with a size of 50 pixels.
A Padding widget that creates a space of 8
pixels around the Icon widget.
To do this, you can specify const EdgeInsets.all(8.0)
for the padding property. | https://docs.flutter.dev/codelabs/layout-basics/index.html |
770dd48484f7-14 | The Row should look like this:
Row
children:
Padding
padding:
const
EdgeInsets
all
8.0
),
child:
Icon
Icons
account_circle
size:
50
),
),
Column
...
),
// <--- The Column you first implemented
],
);
Part 2
Exercise: Tweak the layout
A SizedBox widget with a height of 8.
An empty Row where you’ll add the contact information in
a later step.
A second SizedBox widget with a height of 16. | https://docs.flutter.dev/codelabs/layout-basics/index.html |
770dd48484f7-15 | A second SizedBox widget with a height of 16.
A second empty Row where you’ll add
four icons (Part 3).
The Column’s list of widgets should be formatted as follows,
so the contact information and icons are displayed below the
name and title:
],
),
// <--- Closing parenthesis for the Row
SizedBox
(),
Row
(),
// First empty Row
SizedBox
(),
Row
(),
// Second empty Row
],
);
// <--- Closing parenthesis for the Column that wraps the Row
Exercise: Enter contact information
Enter two Text widgets inside the first empty Row : | https://docs.flutter.dev/codelabs/layout-basics/index.html |
770dd48484f7-16 | Enter two Text widgets inside the first empty Row :
The first Text widget contains the address 123 Main Street.
The second Text widget contains the phone number (415) 555-0198.
For the first empty Row,
set the mainAxisAlignment property to
MainAxisAlignment.spaceBetween.
Part 3
Exercise: Add four icons
Enter the following Icon widgets inside the second empty Row:
Icons.accessibility
Icons.timer
Icons.phone_android
Icons.phone_iphone
For the second empty Row,
set the mainAxisAlignment property to
MainAxisAlignment.spaceAround.
What’s next? | https://docs.flutter.dev/codelabs/layout-basics/index.html |
770dd48484f7-17 | What’s next?
Congratulations, you’ve finished this codelab!
If you’d like to know more about Flutter,
here are a few suggestions for resources worth exploring:
Learn more about layouts in Flutter by
visiting the Building layouts page.
Check out the sample apps.
Visit Flutter’s YouTube channel,
where you can watch a variety videos from
videos that focus on individual widgets
to videos of developers building apps.
You can download Flutter from the install page. | https://docs.flutter.dev/codelabs/layout-basics/index.html |
e3783a92f014-0 | Using Flutter in China
Configuring Flutter to use a mirror site
Community-run mirror sites
The Flutter community has made a Simplified Chinese version of the
Flutter website available at
https://flutter.cn.
If you’d like to install Flutter using an
installation bundle,
you can replace the domain of the original URL with a trusted mirror
to speed it up. For example:
Original URL:
https://storage.googleapis.com/flutter_infra_release/releases/stable/windows/flutter_windows_3.3.0-stable.zip
Mirrored URL:
https://storage.flutter-io.cn/flutter_infra_release/releases/stable/windows/flutter_windows_3.3.0-stable.zip
You must also set two environment variables to upgrade Flutter and use the pub
package repository in China. Instructions are below. | https://docs.flutter.dev/community/china/index.html |
e3783a92f014-1 | Important:
Use mirror sites only if you trust the provider.
The Flutter team cannot verify their reliability or security.
Configuring Flutter to use a mirror site
If you’re installing or using Flutter in China, it may be helpful to use
a trustworthy local mirror site that hosts Flutter’s dependencies.
To instruct the Flutter tool to use an alternate storage location,
you need to set two environment variables, PUB_HOSTED_URL and
FLUTTER_STORAGE_BASE_URL, before running the flutter command.
Taking macOS or Linux as an example, here are the first few steps in
the setup process for using a mirror site. Run the following in a Bash
shell from the directory where you wish to store your local Flutter clone:
export
PUB_HOSTED_URL
=https://pub.flutter-io.cn
export
FLUTTER_STORAGE_BASE_URL | https://docs.flutter.dev/community/china/index.html |
e3783a92f014-2 | export
FLUTTER_STORAGE_BASE_URL
=https://storage.flutter-io.cn
git clone
b dev https://github.com/flutter/flutter.git
export
PATH
$PWD
/flutter/bin:
$PATH
cd ./flutter
flutter doctor
After these steps, you should be able to continue
setting up Flutter normally.
From here on, packages fetched by flutter pub get are
downloaded from flutter-io.cn in any shell where PUB_HOSTED_URL
and FLUTTER_STORAGE_BASE_URL are set. | https://docs.flutter.dev/community/china/index.html |
e3783a92f014-3 | The flutter-io.cn server is a provisional mirror for Flutter
dependencies and packages maintained by GDG China.
The Flutter team cannot guarantee long-term availability of this service.
You’re free to use other mirrors if they become available. If you’re
interested in setting up your own mirror in China, contact
flutter-dev@googlegroups.com
for assistance.
Community-run mirror sites
Shanghai Jiao Tong University Linux User Group
FLUTTER_STORAGE_BASE_URL: https://mirror.sjtu.edu.cn/
PUB_HOSTED_URL: https://mirror.sjtu.edu.cn/dart-pub/ | https://docs.flutter.dev/community/china/index.html |
59721f97162f-0 | Animate a widget using a physics simulation
Fade a widget in and out
Animate the properties of a container
Cookbook
Animation
Animate the properties of a container
1. Create a StatefulWidget with default properties
2. Build an AnimatedContainer using the properties
3. Start the animation by rebuilding with new properties
Interactive example
The Container class provides a convenient way
to create a widget with specific properties:
width, height, background color, padding, borders, and more.
Simple animations often involve changing these properties over time.
For example,
you might want to animate the background color from grey to green to
indicate that an item has been selected by the user. | https://docs.flutter.dev/cookbook/animation/animated-container/index.html |
59721f97162f-1 | To animate these properties,
Flutter provides the AnimatedContainer widget.
Like the Container widget, AnimatedContainer allows you to define
the width, height, background colors, and more. However, when the
AnimatedContainer is rebuilt with new properties, it automatically
animates between the old and new values. In Flutter, these types of
animations are known as “implicit animations.”
This recipe describes how to use an AnimatedContainer to animate the size,
background color, and border radius when the user taps a button
using the following steps:
Create a StatefulWidget with default properties.
Build an AnimatedContainer using the properties.
Start the animation by rebuilding with new properties.
1. Create a StatefulWidget with default properties
To start, create StatefulWidget and State classes.
Use the custom State class to define the properties that change over
time. In this example, that includes the width, height, color, and border
radius. You can also define the default value of each property. | https://docs.flutter.dev/cookbook/animation/animated-container/index.html |
59721f97162f-2 | These properties belong to a custom State class so they
can be updated when the user taps a button.
2. Build an AnimatedContainer using the properties
Next, build the AnimatedContainer using the properties defined in the
previous step. Furthermore, provide a duration that defines how long
the animation should run.
3. Start the animation by rebuilding with new properties
Finally, start the animation by rebuilding the
AnimatedContainer with the new properties.
How to trigger a rebuild?
Use the setState() method.
Add a button to the app. When the user taps the button, update
the properties with a new width, height, background color and border radius
inside a call to setState().
A real app typically transitions between fixed values (for example,
from a grey to a green background). For this app,
generate new values each time the user taps the button.
Interactive example
Animate a widget using a physics simulation | https://docs.flutter.dev/cookbook/animation/animated-container/index.html |
59721f97162f-3 | Interactive example
Animate a widget using a physics simulation
Fade a widget in and out | https://docs.flutter.dev/cookbook/animation/animated-container/index.html |
1295cc44d657-0 | Animation
Cookbook
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 | https://docs.flutter.dev/cookbook/animation/index.html |
5d3b34bf6dd4-0 | Animate the properties of a container
Add a drawer to a screen
Fade a widget in and out
Cookbook
Animation
Fade a widget in and out
1. Create a box to fade in and out
2. Define a StatefulWidget
3. Display a button that toggles the visibility
4. Fade the box in and out
Interactive example
UI developers often need to show and hide elements on screen.
However, quickly popping elements on and off the screen can
feel jarring to end users. Instead,
fade elements in and out with an opacity animation to create
a smooth experience.
The AnimatedOpacity widget makes it easy to perform opacity
animations. This recipe uses the following steps:
Create a box to fade in and out.
Define a StatefulWidget. | https://docs.flutter.dev/cookbook/animation/opacity-animation/index.html |
5d3b34bf6dd4-1 | Define a StatefulWidget.
Display a button that toggles the visibility.
Fade the box in and out.
1. Create a box to fade in and out
First, create something to fade in and out. For this example,
draw a green box on screen.
2. Define a StatefulWidget
Now that you have a green box to animate,
you need a way to know whether the box should be visible.
To accomplish this, use a StatefulWidget.
A StatefulWidget is a class that creates a State object.
The State object holds some data about the app and provides a way to
update that data. When updating the data,
you can also ask Flutter to rebuild the UI with those changes.
In this case, you have one piece of data:
a boolean representing whether the button is visible. | https://docs.flutter.dev/cookbook/animation/opacity-animation/index.html |
5d3b34bf6dd4-2 | To construct a StatefulWidget, create two classes: A
StatefulWidget and a corresponding State class.
Pro tip: The Flutter plugins for Android Studio and VSCode include
the stful snippet to quickly generate this code.
3. Display a button that toggles the visibility
Now that you have some data to determine whether the green box
should be visible, you need a way to update that data.
In this example, if the box is visible, hide it.
If the box is hidden, show it.
To handle this, display a button. When a user presses the button,
flip the boolean from true to false, or false to true.
Make this change using setState(),
which is a method on the State class.
This tells Flutter to rebuild the widget.
For more information on working with user input,
see the Gestures section of the cookbook.
4. Fade the box in and out | https://docs.flutter.dev/cookbook/animation/opacity-animation/index.html |
5d3b34bf6dd4-3 | 4. Fade the box in and out
You have a green box on screen and a button to toggle the visibility
to true or false. How to fade the box in and out? With an
AnimatedOpacity widget.
The AnimatedOpacity widget requires three arguments:
opacity: A value from 0.0 (invisible) to 1.0 (fully visible).
duration: How long the animation should take to complete.
child: The widget to animate. In this case, the green box.
Interactive example
Animate the properties of a container
Add a drawer to a screen | https://docs.flutter.dev/cookbook/animation/opacity-animation/index.html |
edd81e24fde3-0 | Animate a widget using a physics simulation
Animate a page route transition
Cookbook
Animation
Animate a page route transition
1. Set up a PageRouteBuilder
2. Create a Tween
3. Use an AnimatedWidget
4. Use a CurveTween
5. Combine the two Tweens
Interactive example
A design language, such as Material, defines standard behaviors when
transitioning between routes (or screens). Sometimes, though, a custom
transition between screens can make an app more unique. To help,
PageRouteBuilder provides an Animation object.
This Animation can be used with Tween and
Curve objects to customize the transition animation.
This recipe shows how to transition between
routes by animating the new route into view from
the bottom of the screen.
To create a custom page route transition, this recipe uses the following steps: | https://docs.flutter.dev/cookbook/animation/page-route-animation/index.html |
edd81e24fde3-1 | To create a custom page route transition, this recipe uses the following steps:
Set up a PageRouteBuilder
Create a Tween
Add an AnimatedWidget
Use a CurveTween
Combine the two Tweens
1. Set up a PageRouteBuilder
To start, use a PageRouteBuilder to create a Route.
PageRouteBuilder has two callbacks, one to build the content of the route
(pageBuilder), and one to build the route’s transition (transitionsBuilder).
Note:
The child parameter in transitionsBuilder is the widget returned from
pageBuilder. The pageBuilder function is only called the first time the
route is built. The framework can avoid extra work because child stays the
same throughout the transition.
The following example creates two routes: a home route with a “Go!” button, and
a second route titled “Page 2”.
2. Create a Tween | https://docs.flutter.dev/cookbook/animation/page-route-animation/index.html |
edd81e24fde3-2 | 2. Create a Tween
To make the new page animate in from the bottom, it should animate from
Offset(0,1) to Offset(0, 0) (usually defined using the Offset.zero
constructor). In this case, the Offset is a 2D vector for the
‘FractionalTranslation’ widget.
Setting the dy argument to 1 represents a vertical translation one
full height of the page.
The transitionsBuilder callback has an animation parameter. It’s an
Animation<double> that produces values between 0 and 1. Convert the
Animation into an Animation using a Tween:
3. Use an AnimatedWidget
Flutter has a set of widgets extending AnimatedWidget
that rebuild themselves when the value of the animation changes. For instance,
SlideTransition takes an Animation<Offset> and translates its child (using a
FractionalTranslation widget) whenever the value of the animation changes. | https://docs.flutter.dev/cookbook/animation/page-route-animation/index.html |
edd81e24fde3-3 | AnimatedWidget Return a SlideTransition
with the Animation<Offset> and the child widget:
4. Use a CurveTween
Flutter provides a selection of easing curves that
adjust the rate of the animation over time.
The Curves class
provides a predefined set of commonly used curves.
For example, Curves.easeOut
makes the animation start quickly and end slowly.
To use a Curve, create a new CurveTween
and pass it a Curve:
This new Tween still produces values from 0 to 1. In the next step, it will be
combined the Tween<Offset> from step 2.
5. Combine the two Tweens
To combine the tweens,
use chain():
Then use this tween by passing it to animation.drive(). This creates a new
Animation<Offset> that can be given to the SlideTransition widget: | https://docs.flutter.dev/cookbook/animation/page-route-animation/index.html |
edd81e24fde3-4 | This new Tween (or Animatable) produces Offset values by first evaluating the
CurveTween, then evaluating the Tween<Offset>. When the animation runs, the
values are computed in this order:
The animation (provided to the transitionsBuilder callback) produces values
from 0 to 1.
The CurveTween maps those values to new values between 0 and 1 based on its
curve.
The Tween<Offset> maps the double values to Offset values.
Another way to create an Animation<Offset> with an easing curve is to use a
CurvedAnimation:
Interactive example
Animate a widget using a physics simulation | https://docs.flutter.dev/cookbook/animation/page-route-animation/index.html |
d50b441773ec-0 | Animate a page route transition
Animate the properties of a container
Animate a widget using a physics simulation
Cookbook
Animation
Animate a widget using a physics simulation
Step 1: Set up an animation controller
Step 2: Move the widget using gestures
Step 3: Animate the widget
Step 4: Calculate the velocity to simulate a springing motion
Interactive Example
Physics simulations can make app interactions feel realistic and interactive.
For example, you might want to animate a widget to act as if it were attached to
a spring or falling with gravity.
This recipe demonstrates how to move a widget from a dragged point back to the
center using a spring simulation.
This recipe uses these steps:
Set up an animation controller
Move the widget using gestures
Animate the widget | https://docs.flutter.dev/cookbook/animation/physics-simulation/index.html |
d50b441773ec-1 | Move the widget using gestures
Animate the widget
Calculate the velocity to simulate a springing motion
Step 1: Set up an animation controller
Start with a stateful widget called DraggableCard:
SingleTickerProviderStateMixin.
Then construct an
AnimationController in
TickerProvider.
lib/{starter.dart → step1.dart}
@@ -29,14 +29,20 @@
29
29
State<DraggableCard> createState() => _DraggableCardState();
30
30
31
class _DraggableCardState extends State<DraggableCard> {
31
+
class _DraggableCardState extends State<DraggableCard>
32 | https://docs.flutter.dev/cookbook/animation/physics-simulation/index.html |
d50b441773ec-2 | 32
+
with SingleTickerProviderStateMixin {
33
+
late AnimationController _controller;
34
32
35
@override
33
36
void initState() {
34
37
super.initState();
38
+
_controller =
39
+
AnimationController(vsync: this, duration: const Duration(seconds: 1));
35
40
36
41
@override
37
42
void dispose() {
43
+
_controller.dispose(); | https://docs.flutter.dev/cookbook/animation/physics-simulation/index.html |
d50b441773ec-3 | 43
+
_controller.dispose();
38
44
super.dispose();
39
45
Step 2: Move the widget using gestures
Make the widget move when it’s dragged, and add an Alignment field to the
_DraggableCardState class:
lib/{step1.dart (alignment) → step2.dart (alignment)}
@@ -1,3 +1,4 @@
1
1
class _DraggableCardState extends State<DraggableCard>
2
2
with SingleTickerProviderStateMixin {
3
3
late AnimationController _controller;
+
Alignment _dragAlignment = Alignment.center;
GestureDetector that handles the | https://docs.flutter.dev/cookbook/animation/physics-simulation/index.html |
d50b441773ec-4 | GestureDetector that handles the
MediaQuery to get the
size of the widget, and divide by 2. (This converts units of “pixels dragged” to
coordinates that
Align uses.) Then, set the
lib/{step1.dart (build) → step2.dart (build)}
@@ -1,8 +1,22 @@
1
1
@override
2
2
Widget build(BuildContext context) {
return Align(
child: Card(
child: widget.child,
+
var size = MediaQuery.of(context).size;
+
return GestureDetector(
+
onPanDown: (details) {},
+
onPanUpdate: (details) {
+
setState(() { | https://docs.flutter.dev/cookbook/animation/physics-simulation/index.html |
d50b441773ec-5 | +
setState(() {
+
_dragAlignment += Alignment(
+
details.delta.dx / (size.width / 2),
10
+
details.delta.dy / (size.height / 2),
11
+
);
12
+
});
13
+
},
14
+
onPanEnd: (details) {},
15
+
child: Align(
16
+
alignment: _dragAlignment,
17
+
child: Card(
18
+
child: widget.child, | https://docs.flutter.dev/cookbook/animation/physics-simulation/index.html |
d50b441773ec-6 | 18
+
child: widget.child,
19
+
),
6
20
),
7
21
);
8
22
Step 3: Animate the widget
When the widget is released, it should spring back to the center.
Add an Animation<Alignment> field and an _runAnimation method. This
method defines a Tween that interpolates between the point the widget was
dragged to, to the point in the center.
lib/{step2.dart (animation) → step3.dart (animation)}
@@ -1,4 +1,5 @@
1
1
class _DraggableCardState extends State<DraggableCard>
2
2
with SingleTickerProviderStateMixin { | https://docs.flutter.dev/cookbook/animation/physics-simulation/index.html |
d50b441773ec-7 | 2
2
with SingleTickerProviderStateMixin {
3
3
late AnimationController _controller;
+
late Animation<Alignment> _animation;
4
5
Alignment _dragAlignment = Alignment.center;
Next, update _dragAlignment when the AnimationController produces a
value:
lib/{step2.dart (initState) → step3.dart (initState)}
@@ -3,4 +3,9 @@
3
3
super.initState();
4
4
_controller =
5
5
AnimationController(vsync: this, duration: const Duration(seconds: 1));
+
_controller.addListener(() {
+
setState(() { | https://docs.flutter.dev/cookbook/animation/physics-simulation/index.html |
d50b441773ec-8 | +
setState(() {
+
_dragAlignment = _animation.value;
+
});
10
+
});
6
11
Next, make the Align widget use the _dragAlignment field:
Finally, update the GestureDetector to manage the animation controller:
lib/{step2.dart (gesture) → step3.dart (gesture)}
@@ -1,5 +1,7 @@
1
1
return GestureDetector(
onPanDown: (details) {},
+
onPanDown: (details) {
+
_controller.stop();
+
},
3
5
onPanUpdate: (details) {
4
6 | https://docs.flutter.dev/cookbook/animation/physics-simulation/index.html |
d50b441773ec-9 | onPanUpdate: (details) {
4
6
setState(() {
5
7
_dragAlignment += Alignment(
@@ -8,7 +10,9 @@
8
10
);
9
11
});
10
12
},
11
onPanEnd: (details) {},
13
+
onPanEnd: (details) {
14
+
_runAnimation();
15
+
},
12
16
child: Align(
13
17
alignment: _dragAlignment, | https://docs.flutter.dev/cookbook/animation/physics-simulation/index.html |
d50b441773ec-10 | 13
17
alignment: _dragAlignment,
14
18
child: Card(
Step 4: Calculate the velocity to simulate a springing motion
The last step is to do a little math, to calculate the velocity of the widget
after it’s finished being dragged. This is so that the widget realistically
continues at that speed before being snapped back. (The _runAnimation method
already sets the direction by setting the animation’s start and end alignment.)
First, import the physics package: | https://docs.flutter.dev/cookbook/animation/physics-simulation/index.html |
d50b441773ec-11 | First, import the physics package:
The onPanEnd callback provides a DragEndDetails object. This object
provides the velocity of the pointer when it stopped contacting the screen. The
velocity is in pixels per second, but the Align widget doesn’t use pixels. It
uses coordinate values between [-1.0, -1.0] and [1.0, 1.0], where [0.0, 0.0]
represents the center. The size calculated in step 2 is used to convert pixels
to coordinate values in this range.
Finally, AnimationController has an animateWith() method that can be given a
SpringSimulation:
Don’t forget to call _runAnimation() with the velocity and size:
Note:
Now that the animation controller uses a simulation it’s duration argument
is no longer required.
Interactive Example
Animate a page route transition
Animate the properties of a container | https://docs.flutter.dev/cookbook/animation/physics-simulation/index.html |
3dd6cf292a00-0 | Fade a widget in and out
Display a snackbar
Add a drawer to a screen
Cookbook
Design
Add a drawer to a screen
1. Create a Scaffold
2. Add a drawer
3. Populate the drawer with items
4. Close the drawer programmatically
Interactive example
In apps that use Material Design,
there are two primary options for navigation: tabs and drawers.
When there is insufficient space to support tabs,
drawers provide a handy alternative.
In Flutter, use the Drawer widget in combination with a
Scaffold to create a layout with a Material Design drawer.
This recipe uses the following steps:
Create a Scaffold.
Add a drawer.
Populate the drawer with items. | https://docs.flutter.dev/cookbook/design/drawer/index.html |
3dd6cf292a00-1 | Add a drawer.
Populate the drawer with items.
Close the drawer programmatically.
1. Create a Scaffold
To add a drawer to the app, wrap it in a Scaffold widget.
The Scaffold widget provides a consistent visual structure to apps that
follow the Material Design Guidelines.
It also supports special Material Design
components, such as Drawers, AppBars, and SnackBars.
In this example, create a Scaffold with a drawer:
2. Add a drawer
Now add a drawer to the Scaffold. A drawer can be any widget,
but it’s often best to use the Drawer widget from the
material library,
which adheres to the Material Design spec.
3. Populate the drawer with items | https://docs.flutter.dev/cookbook/design/drawer/index.html |
3dd6cf292a00-2 | 3. Populate the drawer with items
Now that you have a Drawer in place, add content to it.
For this example, use a ListView.
While you could use a Column widget,
ListView is handy because it allows users to scroll
through the drawer if the
content takes more space than the screen supports.
Populate the ListView with a DrawerHeader
and two ListTile widgets.
For more information on working with Lists,
see the list recipes.
4. Close the drawer programmatically
After a user taps an item, you might want to close the drawer.
You can do this by using the Navigator.
When a user opens the drawer, Flutter adds the drawer to the navigation
stack. Therefore, to close the drawer, call Navigator.pop(context).
Interactive example
Fade a widget in and out
Display a snackbar | https://docs.flutter.dev/cookbook/design/drawer/index.html |
b0995cd6c3a2-0 | Update the UI based on orientation
Use themes to share colors and font styles
Use a custom font
Cookbook
Design
Use a custom font
1. Import the font files
Supported font formats
2. Declare the font in the pubspec
pubspec.yaml option definitions
3. Set a font as the default
4. Use the font in a specific widget
TextStyle
Complete example
Fonts
pubspec.yaml
main.dart
Although Android and iOS offer high quality system fonts,
one of the most common requests from designers is for custom fonts.
For example, you might have a custom-built font from a designer,
or perhaps you downloaded a font from Google Fonts. | https://docs.flutter.dev/cookbook/design/fonts/index.html |
b0995cd6c3a2-1 | Note:
Check out the google_fonts package for direct access
to over 1,000 open-sourced font families.
Note:
For another approach to using custom fonts,
especially if you want to re-use one font over multiple projects,
see Export fonts from a package.
Flutter works with custom fonts and you can apply a custom
font across an entire app or to individual widgets.
This recipe creates an app that uses custom fonts with
the following steps:
Import the font files.
Declare the font in the pubspec.
Set a font as the default.
Use a font in a specific widget.
1. Import the font files
To work with a font, import the font files into the project.
It’s common practice to put font files in a fonts or assets
folder at the root of a Flutter project. | https://docs.flutter.dev/cookbook/design/fonts/index.html |
b0995cd6c3a2-2 | For example, to import the Raleway and Roboto Mono font
files into a project, the folder structure might look like this:
Supported font formats
Flutter supports the following font formats:
.ttc
.ttf
.otf
Flutter does not support .woff and .woff2 fonts for all platforms.
2. Declare the font in the pubspec
Once you’ve identified a font, tell Flutter where to find it.
You can do this by including a font definition in the pubspec.yaml file.
flutter
fonts
family
Raleway
fonts
asset
fonts/Raleway-Regular.ttf
asset
fonts/Raleway-Italic.ttf
style
italic
family | https://docs.flutter.dev/cookbook/design/fonts/index.html |
b0995cd6c3a2-3 | style
italic
family
RobotoMono
fonts
asset
fonts/RobotoMono-Regular.ttf
asset
fonts/RobotoMono-Bold.ttf
weight
700
pubspec.yaml option definitions
The family determines the name of the font, which you use in the
fontFamily property of a TextStyle object.
The asset is a path to the font file,
relative to the pubspec.yaml file.
These files contain the outlines for the glyphs in the font.
When building the app,
these files are included in the app’s asset bundle.
A single font can reference many different files with different
outline weights and styles: | https://docs.flutter.dev/cookbook/design/fonts/index.html |
b0995cd6c3a2-4 | A single font can reference many different files with different
outline weights and styles:
The weight property specifies the weight of the outlines in
the file as an integer multiple of 100, between 100 and 900.
These values correspond to the FontWeight and can be used in the
fontWeight property of a TextStyle object.
For example, if you want to use the RobotoMono-Bold font defined above,
you would set fontWeight to FontWeight.w700 in your TextStyle.
Note that defining the weight property does not
override the actual weight of the font. You would not be able to
access RobotoMono-Bold with FontWeight.w100, even if its weight
was set to 100. | https://docs.flutter.dev/cookbook/design/fonts/index.html |
b0995cd6c3a2-5 | The style property specifies whether the outlines in the file are
italic or normal.
These values correspond to the FontStyle and can be used in the
fontStyle property of a TextStyle object.
For example, if you want to use the Raleway-Italic font defined above,
you would set fontStyle to FontStyle.italic in your TextStyle.
Note that defining the style property does not
override the actual style of the font; You would not be able to
access Raleway-Italic with FontStyle.normal, even if its style
was set to normal.
3. Set a font as the default
You have two options for how to apply fonts to text: as the default font
or only within specific widgets.
To use a font as the default, set the fontFamily property
as part of the app’s theme. The value provided to
fontFamily must match the family
name declared in the pubspec.yaml. | https://docs.flutter.dev/cookbook/design/fonts/index.html |
b0995cd6c3a2-6 | For more information on themes,
see the Using Themes to share colors and font styles recipe.
4. Use the font in a specific widget
If you want to apply the font to a specific widget,
such as a Text widget,
provide a TextStyle to the widget.
In this example, apply the RobotoMono font to a single Text widget.
Once again, the fontFamily must match the family name declared in the
pubspec.yaml.
TextStyle
If a TextStyle object specifies a weight
or style for which there is no exact font file,
the engine uses one of the more generic files
for the font and attempts to extrapolate outlines
for the requested weight and style.
Complete example
Fonts
The Raleway and RobotoMono fonts were downloaded from
Google Fonts.
pubspec.yaml
name
custom_fonts
description | https://docs.flutter.dev/cookbook/design/fonts/index.html |
b0995cd6c3a2-7 | name
custom_fonts
description
An example of how to use custom fonts with Flutter
dependencies
flutter
sdk
flutter
dev_dependencies
flutter_test
sdk
flutter
flutter
fonts
family
Raleway
fonts
asset
fonts/Raleway-Regular.ttf
asset
fonts/Raleway-Italic.ttf
style
italic
family
RobotoMono
fonts
asset
fonts/RobotoMono-Regular.ttf
asset
fonts/RobotoMono-Bold.ttf
weight | https://docs.flutter.dev/cookbook/design/fonts/index.html |
b0995cd6c3a2-8 | fonts/RobotoMono-Bold.ttf
weight
700
uses-material-design
true
main.dart
Update the UI based on orientation
Use themes to share colors and font styles | https://docs.flutter.dev/cookbook/design/fonts/index.html |
e160c5218499-0 | Design
Cookbook
Design
Add a drawer to a screen
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 | https://docs.flutter.dev/cookbook/design/index.html |
e20ae02519c9-0 | Export fonts from a package
Use a custom font
Update the UI based on orientation
Cookbook
Design
Update the UI based on orientation
1. Build a GridView with two columns
2. Use an OrientationBuilder to change the number of columns
Interactive example
In some situations,
you want to update the display of an app when the user
rotates the screen from portrait mode to landscape mode. For example,
the app might show one item after the next in portrait mode,
yet put those same items side-by-side in landscape mode.
In Flutter, you can build different layouts depending
on a given Orientation.
In this example, build a list that displays two columns in
portrait mode and three columns in landscape mode using the
following steps:
Build a GridView with two columns.
Use an OrientationBuilder to change the number of columns. | https://docs.flutter.dev/cookbook/design/orientation/index.html |
e20ae02519c9-1 | Use an OrientationBuilder to change the number of columns.
1. Build a GridView with two columns
First, create a list of items to work with.
Rather than using a normal list,
create a list that displays items in a grid.
For now, create a grid with two columns.
To learn more about working with GridViews,
see the Creating a grid list recipe.
2. Use an OrientationBuilder to change the number of columns
To determine the app’s current Orientation, use the
OrientationBuilder widget.
The OrientationBuilder calculates the current Orientation by
comparing the width and height available to the parent widget,
and rebuilds when the size of the parent changes.
Using the Orientation, build a list that displays two columns in portrait
mode, or three columns in landscape mode. | https://docs.flutter.dev/cookbook/design/orientation/index.html |
e20ae02519c9-2 | Note:
If you’re interested in the orientation of the screen,
rather than the amount of space available to the parent,
use MediaQuery.of(context).orientation instead of an
OrientationBuilder widget.
Interactive example
Export fonts from a package
Use a custom font | https://docs.flutter.dev/cookbook/design/orientation/index.html |
1b44b7ec3972-0 | Display a snackbar
Update the UI based on orientation
Export fonts from a package
Cookbook
Design
Export fonts from a package
1. Add a font to a package
2. Add the package and fonts to the app
Add the package to the app
Declare the font assets
3. Use the font
Complete example
Fonts
pubspec.yaml
main.dart
Rather than declaring a font as part of an app,
you can declare a font as part of a separate package.
This is a convenient way to share the same font across
several different projects,
or for coders publishing their packages to pub.dev.
This recipe uses the following steps:
Add a font to a package.
Add the package and font to the app.
Use the font. | https://docs.flutter.dev/cookbook/design/package-fonts/index.html |
1b44b7ec3972-1 | Add the package and font to the app.
Use the font.
Note:
Check out the google_fonts package for direct access
to almost 1000 open-sourced font families.
1. Add a font to a package
To export a font from a package, you need to import the font files into the
lib folder of the package project. You can place font files directly in the
lib folder or in a subdirectory, such as lib/fonts.
In this example, assume you’ve got a Flutter library called
awesome_package with fonts living in a lib/fonts folder.
2. Add the package and fonts to the app
Now you can use the fonts in the package by
updating the pubspec.yaml in the app’s root directory.
Add the package to the app
dependencies
awesome_package
<latest_version>
Declare the font assets | https://docs.flutter.dev/cookbook/design/package-fonts/index.html |
1b44b7ec3972-2 | <latest_version>
Declare the font assets
Now that you’ve imported the package, tell Flutter where to
find the fonts from the awesome_package.
To declare package fonts, prefix the path to the font with
packages/awesome_package.
This tells Flutter to look in the lib folder
of the package for the font.
flutter
fonts
family
Raleway
fonts
asset
packages/awesome_package/fonts/Raleway-Regular.ttf
asset
packages/awesome_package/fonts/Raleway-Italic.ttf
style
italic
3. Use the font
Use a TextStyle to change the appearance of text.
To use package fonts, declare which font you’d like to use and
which package the font belongs to.
Complete example | https://docs.flutter.dev/cookbook/design/package-fonts/index.html |
1b44b7ec3972-3 | Complete example
Fonts
The Raleway and RobotoMono fonts were downloaded from
Google Fonts.
pubspec.yaml
name
package_fonts
description
An example of how to use package fonts with Flutter
dependencies
awesome_package
flutter
sdk
flutter
dev_dependencies
flutter_test
sdk
flutter
flutter
fonts
family
Raleway
fonts
asset
packages/awesome_package/fonts/Raleway-Regular.ttf
asset
packages/awesome_package/fonts/Raleway-Italic.ttf
style
italic | https://docs.flutter.dev/cookbook/design/package-fonts/index.html |
1b44b7ec3972-4 | style
italic
uses-material-design
true
main.dart
Display a snackbar
Update the UI based on orientation | https://docs.flutter.dev/cookbook/design/package-fonts/index.html |
aa5b1b9aeab9-0 | Add a drawer to a screen
Export fonts from a package
Display a snackbar
Cookbook
Design
Display a snackbar
1. Create a Scaffold
2. Display a SnackBar
3. Provide an optional action
Interactive example
It can be useful to briefly inform your users when certain actions
take place. For example, when a user swipes away a message in a list,
you might want to inform them that the message has been deleted.
You might even want to give them an option to undo the action.
In Material Design, this is the job of a SnackBar.
This recipe implements a snackbar using the following steps:
Create a Scaffold.
Display a SnackBar.
Provide an optional action.
1. Create a Scaffold | https://docs.flutter.dev/cookbook/design/snackbars/index.html |
aa5b1b9aeab9-1 | 1. Create a Scaffold
When creating apps that follow the Material Design guidelines,
give your apps a consistent visual structure.
In this example, display the SnackBar at the bottom of the screen,
without overlapping other important
widgets, such as the FloatingActionButton.
The Scaffold widget, from the material library,
creates this visual structure and ensures that important
widgets don’t overlap.
2. Display a SnackBar
With the Scaffold in place, display a SnackBar.
First, create a SnackBar, then display it using ScaffoldMessenger.
Note:
To learn more, watch this short Widget of the Week video on the ScaffoldMessenger widget:
3. Provide an optional action | https://docs.flutter.dev/cookbook/design/snackbars/index.html |
aa5b1b9aeab9-2 | 3. Provide an optional action
You might want to provide an action to the user when
the SnackBar is displayed.
For example, if the user accidentally deletes a message,
they might use an optional action in the SnackBar to recover
the message.
Here’s an example of providing
an additional action to the SnackBar widget:
Interactive example
Note:
In this example, the SnackBar displays when a user taps a button.
For more information on working with user input,
see the Gestures section of the cookbook.
Add a drawer to a screen
Export fonts from a package | https://docs.flutter.dev/cookbook/design/snackbars/index.html |
61deba6fea6d-0 | Use themes to share colors and font styles
Create a download button
Work with tabs
Cookbook
Design
Work with tabs
1. Create a TabController
2. Create the tabs
3. Create content for each tab
Interactive example
Working with tabs is a common pattern in apps that follow the
Material Design guidelines.
Flutter includes a convenient way to create tab layouts as part of
the material library.
Note:
To create tabs in a Cupertino app, see the
Building a Cupertino app with Flutter codelab.
This recipe creates a tabbed example using the following steps;
Create a TabController.
Create the tabs.
Create content for each tab.
1. Create a TabController | https://docs.flutter.dev/cookbook/design/tabs/index.html |
61deba6fea6d-1 | Create content for each tab.
1. Create a TabController
For tabs to work, you need to keep the selected tab and content
sections in sync.
This is the job of the TabController.
Either create a TabController manually,
or automatically by using a DefaultTabController widget.
Using DefaultTabController is the simplest option, since it
creates a TabController and makes it available to all descendant widgets.
2. Create the tabs
When a tab is selected, it needs to display content.
You can create tabs using the TabBar widget.
In this example, create a TabBar with three
Tab widgets and place it within an AppBar.
By default, the TabBar looks up the widget tree for the nearest
DefaultTabController. If you’re manually creating a TabController,
pass it to the TabBar.
3. Create content for each tab | https://docs.flutter.dev/cookbook/design/tabs/index.html |
61deba6fea6d-2 | 3. Create content for each tab
Now that you have tabs, display content when a tab is selected.
For this purpose, use the TabBarView widget.
Note:
Order is important and must correspond to the order of the tabs in the
TabBar.
Interactive example
Use themes to share colors and font styles
Create a download button | https://docs.flutter.dev/cookbook/design/tabs/index.html |
b0159abcb281-0 | Use a custom font
Work with tabs
Use themes to share colors and font styles
Cookbook
Design
Themes
Creating an app theme
Themes for part of an application
Creating unique ThemeData
Extending the parent theme
Using a Theme
Interactive example
To share colors and font styles throughout an app, use themes.
You can either define app-wide themes, or use Theme widgets
that define the colors and font styles for a particular part
of the application. In fact,
app-wide themes are just Theme widgets created at
the root of an app by the MaterialApp.
After defining a Theme, use it within your own widgets. Flutter’s
Material widgets also use your Theme to set the background
colors and font styles for AppBars, Buttons, Checkboxes, and more.
Creating an app theme | https://docs.flutter.dev/cookbook/design/themes/index.html |
b0159abcb281-1 | Creating an app theme
To share a Theme across an entire app, provide a
ThemeData to the MaterialApp constructor.
If no theme is provided, Flutter creates a default theme for you.
See the ThemeData documentation to see all of
the colors and fonts you can define.
Themes for part of an application
To override the app-wide theme in part of an application,
wrap a section of the app in a Theme widget.
There are two ways to approach this: creating a unique ThemeData,
or extending the parent theme.
Note:
To learn more, watch this short Widget of the Week video on the Theme widget:
Creating unique ThemeData
If you don’t want to inherit any application colors or font styles,
create a ThemeData() instance and pass that to the Theme widget.
Extending the parent theme | https://docs.flutter.dev/cookbook/design/themes/index.html |
b0159abcb281-2 | Extending the parent theme
Rather than overriding everything, it often makes sense to extend the parent
theme. You can handle this by using the copyWith() method.
Using a Theme
Now that you’ve defined a theme, use it within the widgets’ build()
methods by using the Theme.of(context) method.
The Theme.of(context) method looks up the widget tree and returns
the nearest Theme in the tree. If you have a standalone
Theme defined above your widget, that’s returned.
If not, the app’s theme is returned.
In fact, the FloatingActionButton uses this technique to find the
accentColor.
Interactive example
Use a custom font
Work with tabs | https://docs.flutter.dev/cookbook/design/themes/index.html |
f957251ff109-0 | Work with tabs
Create a nested navigation flow
Create a download button
Cookbook
Effects
Create a download button
Define a new stateless widget
Define the button’s possible visual states
Display the button shape
Display the button text
Display a spinner while fetching download
Display the progress and a stop button while downloading
Add button tap callbacks
Interactive example
Apps are filled with buttons that execute long-running behaviors.
For example, a button might trigger a download,
which starts a download process, receives data over time,
and then provides access to the downloaded asset.
It’s helpful to show the user the progress of a
long-running process, and the button itself is a good place
to provide this feedback. In this recipe,
you’ll build a download button that transitions through
multiple visual states, based on the status of an app download. | https://docs.flutter.dev/cookbook/effects/download-button/index.html |
f957251ff109-1 | The following animation shows the app’s behavior:
Define a new stateless widget
Your button widget needs to change its appearance over time.
Therefore, you need to implement your button with a custom
stateless widget.
Define a new stateless widget called DownloadButton.
Define the button’s possible visual states
The download button’s visual presentation is based on a
given download status. Define the possible states of
the download, and then update DownloadButton to accept
a DownloadStatus and a Duration for how long the button
should take to animate from one status to another.
Display the button shape
The download button changes its shape based on the download
status. The button displays a grey, rounded rectangle during
the notDownloaded and downloaded states.
The button displays a transparent circle during the
fetchingDownload and downloading states.
Based on the current DownloadStatus,
build an AnimatedContainer with a
ShapeDecoration that displays a rounded
rectangle or a circle. | https://docs.flutter.dev/cookbook/effects/download-button/index.html |
f957251ff109-2 | documentation
or in a dedicated video in the Flutter
YouTube channel.
For now, the AnimatedContainer child is just a SizedBox because we will come back at it in another step.
You might wonder why you need a ShapeDecoration
widget for a transparent circle, given that it’s invisible.
The purpose of the invisible circle is to orchestrate
the desired animation. The AnimatedContainer begins with a rounded
rectangle. When the DownloadStatus changes to fetchingDownload,
the AnimatedContainer needs to animate from a rounded rectangle
to a circle, and then fade out as the animation takes place.
The only way to implement this animation is to define both
the beginning shape of a rounded rectangle and the
ending shape of a circle. But, you don’t want the final
circle to be visible, so you make it transparent,
which causes an animated fade-out.
Display the button text
The DownloadButton displays GET during the
notDownloaded phase, OPEN during the downloaded
phase, and no text in between. | https://docs.flutter.dev/cookbook/effects/download-button/index.html |
f957251ff109-3 | Add widgets to display text during each download phase,
and animate the text’s opacity in between. Add the text
widget tree as a child of the AnimatedContainer in the
button wrapper widget.
Display a spinner while fetching download
During the fetchingDownload phase, the DownloadButton
displays a radial spinner. This spinner fades in from
the notDownloaded phase and fades out to
the fetchingDownload phase.
Implement a radial spinner that sits on top of the button
shape and fades in and out at the appropriate times.
We have removed the ButtonShapeWidget’s constructor to keep the
focus on its build method and the Stack widget we’ve added.
Display the progress and a stop button while downloading | https://docs.flutter.dev/cookbook/effects/download-button/index.html |
f957251ff109-4 | Display the progress and a stop button while downloading
After the fetchingDownload phase is the downloading phase.
During the downloading phase, the DownloadButton
replaces the radial progress spinner with a growing
radial progress bar. The DownloadButton also displays a stop
button icon so that the user can cancel an in-progress download.
Add a progress property to the DownloadButton widget,
and then update the progress display to switch to a radial
progress bar during the downloading phase.
Next, add a stop button icon at the center of the
radial progress bar.
Add button tap callbacks
The last detail that your DownloadButton needs is the
button behavior. The button must do things when the user taps it.
Add widget properties for callbacks to start a download,
cancel a download, and open a download.
Finally, wrap DownloadButton’s existing widget tree
with a GestureDetector widget, and forward the
tap event to the corresponding callback property. | https://docs.flutter.dev/cookbook/effects/download-button/index.html |
f957251ff109-5 | Congratulations! You have a button that changes its display
depending on which phase the button is in: not downloaded,
fetching download, downloading, and downloaded.
Now, the user can tap to start a download, tap to cancel an
in-progress download, and tap to open a completed download.
Interactive example
Run the app:
Click the GET button to kick off a
simulated download.
The button changes to a progress indicator
to simulate an in-progress download.
When the simulated download is complete, the
button transitions to OPEN, to indicate
that the app is ready for the user
to open the downloaded asset.
Work with tabs
Create a nested navigation flow | https://docs.flutter.dev/cookbook/effects/download-button/index.html |
d8b85c53c7c2-0 | Create gradient chat bubbles
Build a form with validation
Drag a UI element
Cookbook
Effects
Drag a UI element
Press and drag
Drop the draggable
Add a menu item to a cart
Interactive example
Drag and drop is a common mobile app interaction.
As the user long presses (sometimes called touch & hold)
on a widget, another widget appears beneath the
user’s finger, and the user drags the widget to a
final location and releases it.
In this recipe, you’ll build a drag-and-drop interaction
where the user long presses on a choice of food,
and then drags that food to the picture of the customer who
is paying for it.
The following animation shows the app’s behavior: | https://docs.flutter.dev/cookbook/effects/drag-a-widget/index.html |
d8b85c53c7c2-1 | The following animation shows the app’s behavior:
This recipe begins with a prebuilt list of menu items and
a row of customers.
The first step is to recognize a long press
and display a draggable photo of a menu item.
Press and drag
Flutter provides a widget called LongPressDraggable
that provides the exact behavior that you need to begin
a drag-and-drop interaction. A LongPressDraggable
widget recognizes when a long press occurs and then
displays a new widget near the user’s finger.
As the user drags, the widget follows the user’s finger.
LongPressDraggable gives you full control over the
widget that the user drags.
Each menu list item is displayed with a custom
MenuListItem widget.
Wrap the MenuListItem widget with a LongPressDraggable widget. | https://docs.flutter.dev/cookbook/effects/drag-a-widget/index.html |
d8b85c53c7c2-2 | Wrap the MenuListItem widget with a LongPressDraggable widget.
In this case, when the user long presses on the
MenuListItem widget, the LongPressDraggable
widget displays a DraggingListItem.
This DraggingListItem displays a photo of the
selected food item, centered beneath
the user’s finger.
The dragAnchorStrategy property is set to
pointerDragAnchorStrategy.
This property value instructs LongPressDraggable
to base the DraggableListItem’s position on the
user’s finger. As the user moves a finger,
the DraggableListItem moves with it.
Dragging and dropping is of little use if no information
is transmitted when the item is dropped.
For this reason, LongPressDraggable takes a data parameter.
In this case, the type of data is Item,
which holds information about the
food menu item that the user pressed on. | https://docs.flutter.dev/cookbook/effects/drag-a-widget/index.html |
d8b85c53c7c2-3 | The data associated with a LongPressDraggable
is sent to a special widget called DragTarget,
where the user releases the drag gesture.
You’ll implement the drop behavior next.
Drop the draggable
The user can drop a LongPressDraggable wherever they choose,
but dropping the draggable has no effect unless it’s dropped
on top of a DragTarget. When the user drops a draggable on
top of a DragTarget widget, the DragTarget widget
can either accept or reject the data from the draggable.
In this recipe, the user should drop a menu item on a
CustomerCart widget to add the menu item to the user’s cart.
Wrap the CustomerCart widget with a DragTarget widget.
The DragTarget displays your existing widget and
also coordinates with LongPressDraggable to recognize
when the user drags a draggable on top of the DragTarget.
The DragTarget also recognizes when the user drops
a draggable on top of the DragTarget widget. | https://docs.flutter.dev/cookbook/effects/drag-a-widget/index.html |
d8b85c53c7c2-4 | When the user drops a draggable on the DragTarget widget,
the onAccept callback is invoked. This is when you get
to decide whether or not to accept the data that was dropped.
In this case, the item is always accepted and processed.
You might choose to inspect the incoming item to make a
different decision.
Notice that the type of item dropped on DragTarget
must match the type of the item dragged from LongPressDraggable.
If the types are not compatible, then
the onAccept method isn’t invoked.
With a DragTarget widget configured to accept your
desired data, you can now transmit data from one part
of your UI to another by dragging and dropping.
In the next step,
you update the customer’s cart with the dropped menu item.
Add a menu item to a cart
Each customer is represented by a Customer object,
which maintains a cart of items and a price total. | https://docs.flutter.dev/cookbook/effects/drag-a-widget/index.html |
d8b85c53c7c2-5 | The CustomerCart widget displays the customer’s photo,
name, total, and item count based on a Customer instance.
To update a customer’s cart when a menu item is dropped,
add the dropped item to the associated Customer object.
The _itemDroppedOnCustomerCart method is invoked in
onAccept() when the user drops a menu item on a
CustomerCart widget. By adding the dropped item to the
customer object, and invoking setState() to cause a
layout update, the UI refreshes with the new customer’s
price total and item count.
Congratulations! You have a drag-and-drop interaction
that adds food items to a customer’s shopping cart.
Interactive example
Run the app:
Scroll through the food items.
Press and hold on one with your
finger or click and hold with the
mouse.
While holding, the food item’s image
will appear above the list. | https://docs.flutter.dev/cookbook/effects/drag-a-widget/index.html |
d8b85c53c7c2-6 | While holding, the food item’s image
will appear above the list.
Drag the image and drop it on one of the
people at the bottom of the screen.
The text under the image updates to
reflect the charge for that person.
You can continue to add food items
and watch the charges accumulate.
Create gradient chat bubbles
Build a form with validation | https://docs.flutter.dev/cookbook/effects/drag-a-widget/index.html |
a9e96c33aff5-0 | Create a typing indicator
Create gradient chat bubbles
Create an expandable FAB
Cookbook
Effects
Create an expandable FAB
Create an ExpandableFab widget
FAB cross-fade
Create an ActionButton widget
Expand and collapse the action buttons
Interactive example
A Floating Action Button (FAB) is a round button that
floats near the bottom right of a content area.
This button represents the primary action for the
corresponding content, but sometimes, there is no primary action.
Instead, there are a few critical actions that the user might take.
In this case, you could create an expandable FAB like the one shown
in the following figure. When pressed, this expandable FAB spawns
multiple, other action buttons. Each button corresponds to one of
those critical actions.
The following animation shows the app’s behavior: | https://docs.flutter.dev/cookbook/effects/expandable-fab/index.html |
a9e96c33aff5-1 | The following animation shows the app’s behavior:
Create an ExpandableFab widget
Start by creating a new stateful widget called ExpandableFab.
This widget displays the primary FAB and coordinates the expansion
and collapse of the other action buttons. The widget takes
in parameters for whether or not the ExpandedFab begins in
the expanded position, what the maximum distance of each action button is,
and a list of children. You’ll use the list later to provide
the other action buttons.
FAB cross-fade
The ExpandableFab displays a blue edit button when collapsed
and a white close button when expanded. When expanding and collapsing,
these two buttons scale and fade between one another.
Implement the expand and collapse cross-fade between the two different FABs.
The open button sits on top of the close button within a Stack,
allowing for the visual appearance of a cross-fade as the top button
appears and disappears. | https://docs.flutter.dev/cookbook/effects/expandable-fab/index.html |
a9e96c33aff5-2 | To achieve the cross-fade animation, the open button uses an
AnimatedContainer with a scale transform and an AnimatedOpacity.
The open button scales down and fades out when the ExpandableFab
goes from collapsed to expanded. Then, the open button scales up
and fades in when the ExpandableFab goes from expanded to collapsed.
You’ll notice that the open button is wrapped with an
IgnorePointer widget. This is because the open button always exists,
even when it’s transparent. Without the IgnorePointer,
the open button always receives the tap event,
even when the close button is visible.
Create an ActionButton widget
Each of the buttons that expand from the ExpandableFab
have the same design. They’re blue circles with white icons.
More precisely, the button background color is the ColorScheme.secondary
color, and the icon color is ColorScheme.onSecondary.
Define a new stateless widget called ActionButton to display
these round buttons. | https://docs.flutter.dev/cookbook/effects/expandable-fab/index.html |
a9e96c33aff5-3 | Define a new stateless widget called ActionButton to display
these round buttons.
Pass a few instances of this new ActionButton widget into your
ExpandableFab.
Expand and collapse the action buttons
The child ActionButtons should fly out from under the open
FAB when expanded. Then, the child ActionButtons should
fly back under the open FAB when collapsed.
This motion requires explicit (x,y) positioning of each
ActionButton and an Animation to choreograph changes to
those (x,y) positions over time.
Introduce an AnimationController and an Animation to
control the rate at which the various ActionButtons expand and collapse.
Next, introduce a new stateless widget called _ExpandingActionButton,
and configure this widget to animate and position an individual ActionButton. The ActionButton is provided as a generic Widget called child.
Finally, use the new _ExpandingActionButton widget
within the ExpandableFab to complete the exercise. | https://docs.flutter.dev/cookbook/effects/expandable-fab/index.html |
a9e96c33aff5-4 | Congratulations! You now have an expandable FAB.
Interactive example
Run the app:
Click the FAB in the lower-right corner,
represented with an Edit icon.
It fans out to 3 buttons and is itself replaced by
a close button, represented by an X.
Click the close button to see the expanded
buttons fly back to the original FAB and
the X is replaced by the Edit icon.
Expand the FAB again, and click on any
of the 3 satellite buttons to see a dialog
representing that button’s action.
Create a typing indicator
Create gradient chat bubbles | https://docs.flutter.dev/cookbook/effects/expandable-fab/index.html |
046373897162-0 | Create an expandable FAB
Drag a UI element
Create gradient chat bubbles
Cookbook
Effects
Create gradient chat bubbles
Understand the challenge
Replace original background widget
Create a custom painter
Provide access to scrolling information
Paint a full-screen bubble gradient
Recap
Traditional chat apps display messages in chat bubbles
with solid color backgrounds. Modern chat apps display
chat bubbles with gradients that are based
on the bubbles’ position on the screen.
In this recipe, you’ll modernize the chat UI by implementing
gradient backgrounds for the chat bubbles.
The following animation shows the app’s behavior:
Understand the challenge | https://docs.flutter.dev/cookbook/effects/gradient-bubbles/index.html |
046373897162-1 | The following animation shows the app’s behavior:
Understand the challenge
The traditional chat bubble solution probably uses a
DecoratedBox or a similar widget to paint a rounded
rectangle behind each chat message. That approach is
great for a solid color or even for a gradient that
repeats in every chat bubble. However, modern,
full-screen, gradient bubble backgrounds require
a different approach. The full-screen gradient,
combined with bubbles scrolling up and down the screen,
requires an approach that allows you to make painting
decisions based on layout information. | https://docs.flutter.dev/cookbook/effects/gradient-bubbles/index.html |
046373897162-2 | Each bubble’s gradient requires knowledge of the
bubble’s location on the screen. This means that
the painting behavior requires access to layout information.
Such painting behavior isn’t possible with typical widgets
because widgets like Container and DecoratedBox
make decisions about background colors before layout occurs,
not after. In this case, because you require custom painting
behavior, but you don’t require custom layout behavior
or custom hit test behavior, a CustomPainter is
a great choice to get the job done.
Note:
In cases where you need control over the child layout,
but you don’t need control over the painting or hit testing,
consider using a Flow widget.
In cases where you need control over the layout,
painting, and hit testing,
consider defining a custom RenderBox.
Replace original background widget | https://docs.flutter.dev/cookbook/effects/gradient-bubbles/index.html |
046373897162-3 | Replace original background widget
Replace the widget responsible for drawing the
background with a new stateless widget called
BubbleBackground. Include a colors property to
represent the full-screen gradient that should be
applied to the bubble.
Create a custom painter
Provide access to scrolling information
Paint a full-screen bubble gradient
Congratulations! You now have a modern, chat bubble UI.
Note:
The recipe doesn’t yet work on the web because
Flutter doesn’t yet support Paint shaders.
InheritedWidget documentation
for more information about these types of dependencies.
Recap | https://docs.flutter.dev/cookbook/effects/gradient-bubbles/index.html |
046373897162-4 | Recap
The fundamental challenge when painting based on the
scroll position, or the screen position in general,
is that the painting behavior must occur after the
layout phase is complete. CustomPaint is a unique
widget that allows you to execute custom painting
behaviors after the layout phase is complete.
If you execute the painting behaviors after the layout phase,
then you can base your painting decisions on the layout
information, such as the position of the CustomPaint
widget within a Scrollable or within the screen.
Note:
This recipe doesn’t provide an interactive DartPad because
Paint shaders 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 “Gradient Bubbles”
example under the “cookbook” directory.
Create an expandable FAB
Drag a UI element | https://docs.flutter.dev/cookbook/effects/gradient-bubbles/index.html |