id
stringlengths
14
17
text
stringlengths
23
1.11k
source
stringlengths
35
114
af4a10d2bc4a-5
For this discussion, the key primitive is the frame callbacks. Each time a frame needs to be shown on the screen, Flutter’s engine triggers a “begin frame” callback that the scheduler multiplexes to all the listeners registered using scheduleFrameCallback(). All these callbacks are given the official time stamp of the frame, in the form of a Duration from some arbitrary epoch. Since all the callbacks have the same time, any animations triggered from these callbacks will appear to be exactly synchronised even if they take a few milliseconds to be executed. Tickers The Ticker class hooks into the scheduler’s scheduleFrameCallback() mechanism to invoke a callback every tick. A Ticker can be started and stopped. When started, it returns a Future that will resolve when it is stopped. Each tick, the Ticker provides the callback with the duration since the first tick after it was started.
https://docs.flutter.dev/development/ui/animations/overview/index.html
af4a10d2bc4a-6
Because tickers always give their elapsed time relative to the first tick after they were started; tickers are all synchronised. If you start three tickers at different times between two ticks, they will all nonetheless be synchronised with the same starting time, and will subsequently tick in lockstep. Like people at a bus-stop, all the tickers wait for a regularly occurring event (the tick) to begin moving (counting time). Simulations The Simulation abstract class maps a relative time value (an elapsed time) to a double value, and has a notion of completion. In principle simulations are stateless but in practice some simulations (for example, BouncingScrollSimulation and ClampingScrollSimulation) change state irreversibly when queried. There are various concrete implementations of the Simulation class for different effects. Animatables The Animatable abstract class maps a double to a value of a particular type.
https://docs.flutter.dev/development/ui/animations/overview/index.html
af4a10d2bc4a-7
The Animatable abstract class maps a double to a value of a particular type. Animatable classes are stateless and immutable. Tweens The Tween<T> abstract class maps a double value nominally in the range 0.0-1.0 to a typed value (for example, a Color, or another double). It is an Animatable. It has a notion of an output type (T), a begin value and an end value of that type, and a way to interpolate (lerp) between the begin and end values for a given input value (the double nominally in the range 0.0-1.0). Tween classes are stateless and immutable. Composing animatables Passing an Animatable<double> (the parent) to an Animatable’s chain() method creates a new Animatable subclass that applies the parent’s mapping then the child’s mapping. Curves
https://docs.flutter.dev/development/ui/animations/overview/index.html
af4a10d2bc4a-8
Curves The Curve abstract class maps doubles nominally in the range 0.0-1.0 to doubles nominally in the range 0.0-1.0. Curve classes are stateless and immutable. Animations The Animation abstract class provides a value of a given type, a concept of animation direction and animation status, and a listener interface to register callbacks that get invoked when the value or status change. Some subclasses of Animation have values that never change (kAlwaysCompleteAnimation, kAlwaysDismissedAnimation, AlwaysStoppedAnimation); registering callbacks on these has no effect as the callbacks are never called. The Animation<double> variant is special because it can be used to represent a double nominally in the range 0.0-1.0, which is the input expected by Curve and Tween classes, as well as some further subclasses of Animation.
https://docs.flutter.dev/development/ui/animations/overview/index.html
af4a10d2bc4a-9
Some Animation subclasses are stateless, merely forwarding listeners to their parents. Some are very stateful. Composable animations Most Animation subclasses take an explicit “parent” Animation<double>. They are driven by that parent. The CurvedAnimation subclass takes an Animation<double> class (the parent) and a couple of Curve classes (the forward and reverse curves) as input, and uses the value of the parent as input to the curves to determine its output. CurvedAnimation is immutable and stateless. The ReverseAnimation subclass takes an Animation<double> class as its parent and reverses all the values of the animation. It assumes the parent is using a value nominally in the range 0.0-1.0 and returns a value in the range 1.0-0.0. The status and direction of the parent animation are also reversed. ReverseAnimation is immutable and stateless.
https://docs.flutter.dev/development/ui/animations/overview/index.html
af4a10d2bc4a-10
The ProxyAnimation subclass takes an Animation<double> class as its parent and merely forwards the current state of that parent. However, the parent is mutable. The TrainHoppingAnimation subclass takes two parents, and switches between them when their values cross. Animation controllers The AnimationController is a stateful Animation<double> that uses a Ticker to give itself life. It can be started and stopped. At each tick, it takes the time elapsed since it was started and passes it to a Simulation to obtain a value. That is then the value it reports. If the Simulation reports that at that time it has ended, then the controller stops itself. The animation controller can be given a lower and upper bound to animate between, and a duration. In the simple case (using forward() or reverse()), the animation controller simply does a linear interpolation from the lower bound to the upper bound (or vice versa, for the reverse direction) over the given duration.
https://docs.flutter.dev/development/ui/animations/overview/index.html
af4a10d2bc4a-11
When using repeat(), the animation controller uses a linear interpolation between the given bounds over the given duration, but does not stop. When using animateTo(), the animation controller does a linear interpolation over the given duration from the current value to the given target. If no duration is given to the method, the default duration of the controller and the range described by the controller’s lower bound and upper bound is used to determine the velocity of the animation. When using fling(), a Force is used to create a specific simulation which is then used to drive the controller. When using animateWith(), the given simulation is used to drive the controller. These methods all return the future that the Ticker provides and which will resolve when the controller next stops or changes simulation. Attaching animatables to animations
https://docs.flutter.dev/development/ui/animations/overview/index.html
af4a10d2bc4a-12
Attaching animatables to animations Passing an Animation<double> (the new parent) to an Animatable’s animate() method creates a new Animation subclass that acts like the Animatable but is driven from the given parent.
https://docs.flutter.dev/development/ui/animations/overview/index.html
3734ebc086fc-0
Staggered animations UI Animations Staggered Basic structure of a staggered animation Complete staggered animation Stateless widget: StaggerAnimation Stateful widget: StaggerDemo What you’ll learn A staggered animation consists of sequential or overlapping animations. To create a staggered animation, use multiple Animation objects. One AnimationController controls all of the Animations. Each Animation object specifies the animation during an Interval. For each property being animated, create a Tween. Terminology: If the concept of tweens or tweening is new to you, see the Animations in Flutter tutorial.
https://docs.flutter.dev/development/ui/animations/staggered-animations/index.html
3734ebc086fc-1
Staggered animations are a straightforward concept: visual changes happen as a series of operations, rather than all at once. The animation might be purely sequential, with one change occurring after the next, or it might partially or completely overlap. It might also have gaps, where no changes occur. This guide shows how to build a staggered animation in Flutter. Examples This guide explains the basic_staggered_animation example. You can also refer to a more complex example, staggered_pic_selection. basic_staggered_animation Shows a series of sequential and overlapping animations of a single widget. Tapping the screen begins an animation that changes opacity, size, shape, color, and padding. staggered_pic_selection
https://docs.flutter.dev/development/ui/animations/staggered-animations/index.html
3734ebc086fc-2
staggered_pic_selection Shows deleting an image from a list of images displayed in one of three sizes. This example uses two animation controllers: one for image selection/deselection, and one for image deletion. The selection/deselection animation is staggered. (To see this effect, you might need to increase the timeDilation value.) Select one of the largest images—it shrinks as it displays a checkmark inside a blue circle. Next, select one of the smallest images—the large image expands as the checkmark disappears. Before the large image has finished expanding, the small image shrinks to display its checkmark. This staggered behavior is similar to what you might see in Google Photos. The following video demonstrates the animation performed by basic_staggered_animation: In the video, you see the following animation of a single widget, which begins as a bordered blue square with slightly rounded corners. The square runs through changes in the following order: Fades in
https://docs.flutter.dev/development/ui/animations/staggered-animations/index.html
3734ebc086fc-3
Fades in Widens Becomes taller while moving upwards Transforms into a bordered circle Changes color to orange After running forward, the animation runs in reverse. New to Flutter? This page assumes you know how to create a layout using Flutter’s widgets. For more information, see Building Layouts in Flutter. Basic structure of a staggered animation What's the point? All of the animations are driven by the same AnimationController. Regardless of how long the animation lasts in real time, the controller’s values must be between 0.0 and 1.0, inclusive. Each animation has an Interval between 0.0 and 1.0, inclusive.
https://docs.flutter.dev/development/ui/animations/staggered-animations/index.html
3734ebc086fc-4
For each property that animates in an interval, create a Tween. The Tween specifies the start and end values for that property. The Tween produces an Animation object that is managed by the controller. The following diagram shows the Intervals used in the basic_staggered_animation example. You might notice the following characteristics: The opacity changes during the first 10% of the timeline. A tiny gap occurs between the change in opacity, and the change in width. Nothing animates during the last 25% of the timeline. Increasing the padding makes the widget appear to rise upward. Increasing the border radius to 0.5, transforms the square with rounded corners into a circle. The padding and height changes occur during the same exact interval, but they don’t have to. To set up the animation:
https://docs.flutter.dev/development/ui/animations/staggered-animations/index.html
3734ebc086fc-5
To set up the animation: Create an AnimationController that manages all of the Animations. Create a Tween for each property being animated. The Tween defines a range of values. The Tween’s animate method requires the parent controller, and produces an Animation for that property. Specify the interval on the Animation’s curve property. When the controlling animation’s value changes, the new animation’s value changes, triggering the UI to update. The following code creates a tween for the width property. It builds a CurvedAnimation, specifying an eased curve. See Curves for other available pre-defined animation curves. The begin and end values don’t have to be doubles. The following code builds the tween for the borderRadius property (which controls the roundness of the square’s corners), using BorderRadius.circular(). Complete staggered animation
https://docs.flutter.dev/development/ui/animations/staggered-animations/index.html
3734ebc086fc-6
Complete staggered animation Like all interactive widgets, the complete animation consists of a widget pair: a stateless and a stateful widget. The stateless widget specifies the Tweens, defines the Animation objects, and provides a build() function responsible for building the animating portion of the widget tree. The stateful widget creates the controller, plays the animation, and builds the non-animating portion of the widget tree. The animation begins when a tap is detected anywhere in the screen. Full code for basic_staggered_animation’s main.dart Stateless widget: StaggerAnimation AnimatedBuilder—a general purpose widget for building animations. The class StaggerAnimation extends StatelessWidget { StaggerAnimation({ Key key, this.controller }) :
https://docs.flutter.dev/development/ui/animations/staggered-animations/index.html
3734ebc086fc-7
// Each animation defined here transforms its value during the subset // of the controller's duration defined by the animation's interval. // For example the opacity animation transforms its value during // the first 10% of the controller's duration. opacity = Tween<double>( begin: 0.0, end: 1.0, ).animate( CurvedAnimation( parent: controller, curve: Interval( 0.0, 0.100, curve: Curves.ease, ), ), ), // ... Other tween definitions ... super(key: key); final AnimationController controller; final Animation<double> opacity; final Animation<double> width; final Animation<double> height; final Animation<EdgeInsets> padding;
https://docs.flutter.dev/development/ui/animations/staggered-animations/index.html
3734ebc086fc-8
final Animation<EdgeInsets> padding; final Animation<BorderRadius> borderRadius; final Animation<Color> color; // This function is called each time the controller "ticks" a new frame. // When it runs, all of the animation's values will have been // updated to reflect the controller's current value. Widget _buildAnimation(BuildContext context, Widget child) { return Container( padding: padding.value, alignment: Alignment.bottomCenter, child: Opacity( opacity: opacity.value, child: Container( width: width.value, height: height.value, decoration: BoxDecoration( color: color.value, border: Border.all( color: Colors.indigo[300], width: 3.0, ), borderRadius: borderRadius.value, ), ), ), ); }
https://docs.flutter.dev/development/ui/animations/staggered-animations/index.html
3734ebc086fc-9
@override Widget build(BuildContext context) { return AnimatedBuilder( builder: _buildAnimation, animation: controller, ); } } Stateful widget: StaggerDemo The stateful widget, StaggerDemo, creates the AnimationController (the one who rules them all), specifying a 2000 ms duration. It plays the animation, and builds the non-animating portion of the widget tree. The animation begins when a tap is detected in the screen. The animation runs forward, then backward. class StaggerDemo extends StatefulWidget { @override _StaggerDemoState createState() => _StaggerDemoState(); } class _StaggerDemoState extends State<StaggerDemo> with TickerProviderStateMixin { AnimationController _controller; @override void initState() { super.initState();
https://docs.flutter.dev/development/ui/animations/staggered-animations/index.html
3734ebc086fc-10
@override void initState() { super.initState(); _controller = AnimationController( duration: const Duration(milliseconds: 2000), vsync: this ); } // ...Boilerplate... Future<void> _playAnimation() async { try { await _controller.forward().orCancel; await _controller.reverse().orCancel; } on TickerCanceled { // the animation got canceled, probably because it was disposed of } } @override
https://docs.flutter.dev/development/ui/animations/staggered-animations/index.html
3734ebc086fc-11
@override Widget build(BuildContext context) { timeDilation = 10.0; // 1.0 is normal animation speed. return Scaffold( appBar: AppBar( title: const Text('Staggered Animation'), ), body: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { _playAnimation(); }, child: Center( child: Container( width: 300.0, height: 300.0, decoration: BoxDecoration( color: Colors.black.withOpacity(0.1), border: Border.all( color: Colors.black.withOpacity(0.5), ), ), child: StaggerAnimation( controller: _controller.view ), ), ), ), ); } }
https://docs.flutter.dev/development/ui/animations/staggered-animations/index.html
58eaf49a934e-0
Animations tutorial UI Animations Tutorial Essential animation concepts and classes Animation<double> Curved­Animation Animation­Controller Tween Tween.animate Animation notifications Animation examples Rendering animations Simplifying with Animated­Widget Monitoring the progress of the animation Refactoring with AnimatedBuilder Simultaneous animations Next steps What you’ll learn How to use the fundamental classes from the animation library to add animation to a widget. When to use AnimatedWidget vs. AnimatedBuilder.
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-1
When to use AnimatedWidget vs. AnimatedBuilder. This tutorial shows you how to build explicit animations in Flutter. After introducing some of the essential concepts, classes, and methods in the animation library, it walks you through 5 animation examples. The examples build on each other, introducing you to different aspects of the animation library. The Flutter SDK also provides built-in explicit animations, such as FadeTransition, SizeTransition, and SlideTransition. These simple animations are triggered by setting a beginning and ending point. They are simpler to implement than custom explicit animations, which are described here. Essential animation concepts and classes What's the point? Animation, a core class in Flutter’s animation library, interpolates the values used to guide an animation.
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-2
An Animation object knows the current state of an animation (for example, whether it’s started, stopped, or moving forward or in reverse), but doesn’t know anything about what appears onscreen. An AnimationController manages the Animation. A CurvedAnimation defines progression as a non-linear curve. A Tween interpolates between the range of data as used by the object being animated. For example, a Tween might define an interpolation from red to blue, or from 0 to 255. Use Listeners and StatusListeners to monitor animation state changes. The animation system in Flutter is based on typed Animation objects. Widgets can either incorporate these animations in their build functions directly by reading their current value and listening to their state changes or they can use the animations as the basis of more elaborate animations that they pass along to other widgets. Animation<double>
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-3
Animation<double> In Flutter, an Animation object knows nothing about what is onscreen. An Animation is an abstract class that understands its current value and its state (completed or dismissed). One of the more commonly used animation types is Animation<double>. An Animation object sequentially generates interpolated numbers between two values over a certain duration. The output of an Animation object might be linear, a curve, a step function, or any other mapping you can devise. Depending on how the Animation object is controlled, it could run in reverse, or even switch directions in the middle. Animations can also interpolate types other than double, such as Animation<Color> or Animation<Size>. An Animation object has state. Its current value is always available in the .value member. An Animation object knows nothing about rendering or build() functions. Curved­Animation
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-4
Curved­Animation A CurvedAnimation defines the animation’s progress as a non-linear curve. Note: The Curves class defines many commonly used curves, or you can create your own. For example: Browse the Curves documentation for a complete listing (with visual previews) of the Curves constants that ship with Flutter. CurvedAnimation and AnimationController (described in the next section) are both of type Animation<double>, so you can pass them interchangeably. The CurvedAnimation wraps the object it’s modifying—you don’t subclass AnimationController to implement a curve. Animation­Controller AnimationController is a special Animation object that generates a new value whenever the hardware is ready for a new frame. By default, an AnimationController linearly produces the numbers from 0.0 to 1.0 during a given duration. For example, this code creates an Animation object, but does not start it running:
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-5
RepaintBoundary. When creating an AnimationController, you pass it a vsync argument. The presence of vsync prevents offscreen animations from consuming unnecessary resources. You can use your stateful object as the vsync by adding SingleTickerProviderStateMixin to the class definition. You can see an example of this in animate1 on GitHub. Note: In some cases, a position might exceed the AnimationController’s 0.0-1.0 range. For example, the fling() function allows you to provide velocity, force, and position (via the Force object). The position can be anything and so can be outside of the 0.0 to 1.0 range.
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-6
A CurvedAnimation can also exceed the 0.0 to 1.0 range, even if the AnimationController doesn’t. Depending on the curve selected, the output of the CurvedAnimation can have a wider range than the input. For example, elastic curves such as Curves.elasticIn significantly overshoots or undershoots the default range. Tween By default, the AnimationController object ranges from 0.0 to 1.0. If you need a different range or a different data type, you can use a Tween to configure an animation to interpolate to a different range or data type. For example, the following Tween goes from -200.0 to 0.0: A Tween is a stateless object that takes only begin and end. The sole job of a Tween is to define a mapping from an input range to an output range. The input range is commonly 0.0 to 1.0, but that’s not a requirement.
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-7
A Tween object doesn’t store any state. Instead, it provides the evaluate(Animation<double> animation) method that uses the transform function to map the current value of the animation (between 0.0 and 1.0), to the actual animation value. The current value of the Animation object can be found in the .value method. The evaluate function also performs some housekeeping, such as ensuring that begin and end are returned when the animation values are 0.0 and 1.0, respectively. Tween.animate To use a Tween object, call animate() on the Tween, passing in the controller object. For example, the following code generates the integer values from 0 to 255 over the course of 500 ms. Note: The animate() method returns an Animation, not an Animatable. The following example shows a controller, a curve, and a Tween: Animation notifications
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-8
Animation notifications Animation object can have Monitoring the progress of the animation shows an example of Animation examples This section walks you through 5 animation examples. Each section provides a link to the source code for that example. Rendering animations What's the point? How to add basic animation to a widget using addListener() and setState(). Every time the Animation generates a new number, the addListener() function calls setState(). How to define an AnimationController with the required vsync parameter. Understanding the “..” syntax in “..addListener”, also known as Dart’s cascade notation. To make a class private, start its name with an underscore (_).
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-9
To make a class private, start its name with an underscore (_). So far you’ve learned how to generate a sequence of numbers over time. Nothing has been rendered to the screen. To render with an Animation object, store the Animation object as a member of your widget, then use its value to decide how to draw. Consider the following app that draws the Flutter logo without animation: App source: animate0 The following shows the same code modified to animate the logo to grow from nothing to full size. When defining an AnimationController, you must pass in a vsync object. The vsync parameter is described in the AnimationController section. The changes from the non-animated example are highlighted: {animate0 → animate1}/lib/main.dart @@ -9,16 +9,39 @@ 9 9 State<LogoApp> createState() => _LogoAppState();
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-10
State<LogoApp> createState() => _LogoAppState(); 10 10 11 class _LogoAppState extends State<LogoApp> { 11 + class _LogoAppState extends State<LogoApp> with SingleTickerProviderStateMixin { 12 + late Animation<double> animation; 13 + late AnimationController controller; 14 15 + @override 16 + void initState() { 17 + super.initState(); 18 + controller = 19
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-11
+ controller = 19 + AnimationController(duration: const Duration(seconds: 2), vsync: this); 20 + animation = Tween<double>(begin: 0, end: 300).animate(controller) 21 + ..addListener(() { 22 + setState(() { 23 + // The state that has changed here is the animation object’s value. 24 + }); 25 + }); 26 + controller.forward(); 27 + } 28 12 29
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-12
28 12 29 @override 13 30 Widget build(BuildContext context) { 14 31 return Center( 15 32 child: Container( 16 33 margin: const EdgeInsets.symmetric(vertical: 10), 17 height: 300, 18 width: 300, 34 + height: animation.value, 35 + width: animation.value, 19 36 child: const FlutterLogo(), 20 37 ),
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-13
20 37 ), 21 38 ); 22 39 40 41 + @override 42 + void dispose() { 43 + controller.dispose(); 44 + super.dispose(); 45 + } 23 46 App source: animate1 With these few changes, you’ve created your first animation in Flutter!
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-14
With these few changes, you’ve created your first animation in Flutter! Dart language tricks: You might not be familiar with Dart’s cascade notation—the two dots in ..addListener(). This syntax means that the addListener() method is called with the return value from animate(). Consider the following example: animation = Tween<double>(begin: 0, end: 300).animate(controller) ..addListener(() { // ··· }); This code is equivalent to: animation = Tween<double>(begin: 0, end: 300).animate(controller); animation.addListener(() { // ··· }); To learn more about cascades, check out Cascade notation in the Dart language documentation. Simplifying with Animated­Widget What's the point?
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-15
Simplifying with Animated­Widget What's the point? How to use the AnimatedWidget helper class (instead of addListener() and setState()) to create a widget that animates. Use AnimatedWidget to create a widget that performs a reusable animation. To separate the transition from the widget, use an AnimatedBuilder, as shown in the Refactoring with AnimatedBuilder section. Examples of AnimatedWidgets in the Flutter API: AnimatedBuilder, AnimatedModalBarrier, DecoratedBoxTransition, FadeTransition, PositionedTransition, RelativePositionedTransition, RotationTransition, ScaleTransition, SizeTransition, SlideTransition. The AnimatedWidget base class allows you to separate out the core widget code from the animation code. AnimatedWidget doesn’t need to maintain a State object to hold the animation. Add the following AnimatedLogo class:
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-16
lib/main.dart (AnimatedLogo) AnimatedLogo uses the current value of the animation when drawing itself. The LogoApp still manages the AnimationController and the Tween, and it passes the Animation object to AnimatedLogo: {animate1 → animate2}/lib/main.dart @@ -1,10 +1,28 @@ 1 1 import 'package:flutter/material.dart'; 2 2 void main() => runApp(const LogoApp()); + class AnimatedLogo extends AnimatedWidget { + const AnimatedLogo({super.key, required Animation<double> animation}) + : super(listenable: animation); + @override + Widget build(BuildContext context) {
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-17
+ Widget build(BuildContext context) { + final animation = listenable as Animation<double>; 10 + return Center( 11 + child: Container( 12 + margin: const EdgeInsets.symmetric(vertical: 10), 13 + height: animation.value, 14 + width: animation.value, 15 + child: const FlutterLogo(), 16 + ), 17 + ); 18 + } 19 + }
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-18
19 + } 20 3 21 class LogoApp extends StatefulWidget { 4 22 const LogoApp({super.key}); 5 23 @override 6 24 State<LogoApp> createState() => _LogoAppState(); 7 25 @@ -15,32 +33,18 @@ 15 33 @override 16 34 void initState() { 17 35 super.initState(); 18 36 controller = 19 37
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-19
controller = 19 37 AnimationController(duration: const Duration(seconds: 2), vsync: this); 20 animation = Tween<double>(begin: 0, end: 300).animate(controller) 21 ..addListener(() { 22 setState(() { 23 // The state that has changed here is the animation object’s value. 24 }); 25 }); 38 + animation = Tween<double>(begin: 0, end: 300).animate(controller); 26 39 controller.forward(); 27 40 28 41
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-20
27 40 28 41 @override 29 Widget build(BuildContext context) { 30 return Center( 31 child: Container( 32 margin: const EdgeInsets.symmetric(vertical: 10), 33 height: animation.value, 34 width: animation.value, 35 child: const FlutterLogo(), 36 ), 37 ); 38 } 42 + Widget build(BuildContext context) => AnimatedLogo(animation: animation);
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-21
39 43 @override 40 44 void dispose() { 41 45 controller.dispose(); 42 46 super.dispose(); 43 47 App source: animate2 Monitoring the progress of the animation What's the point? Use addStatusListener() for notifications of changes to the animation’s state, such as starting, stopping, or reversing direction. Run an animation in an infinite loop by reversing direction when the animation has either completed or returned to its starting state.
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-22
It’s often helpful to know when an animation changes state, such as finishing, moving forward, or reversing. You can get notifications for this with addStatusListener(). The following code modifies the previous example so that it listens for a state change and prints an update. The highlighted line shows the change: ..addStatusListener((status) => print('$status')); controller.forward(); } // ... } Running this code produces this output: AnimationStatus.forward AnimationStatus.completed Next, use addStatusListener() to reverse the animation at the beginning or the end. This creates a “breathing” effect: {animate2 → animate3}/lib/main.dart @@ -35,7 +35,15 @@ 35 35 void initState() { 36 36 super.initState();
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-23
36 36 super.initState(); 37 37 controller = 38 38 AnimationController(duration: const Duration(seconds: 2), vsync: this); 39 animation = Tween<double>(begin: 0, end: 300).animate(controller); 39 + animation = Tween<double>(begin: 0, end: 300).animate(controller) 40 + ..addStatusListener((status) { 41 + if (status == AnimationStatus.completed) { 42 + controller.reverse(); 43
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-24
+ controller.reverse(); 43 + } else if (status == AnimationStatus.dismissed) { 44 + controller.forward(); 45 + } 46 + }) 47 + ..addStatusListener((status) => print('$status')); 40 48 controller.forward(); 41 49 App source: animate3 Refactoring with AnimatedBuilder What's the point? An AnimatedBuilder understands how to render the transition. An AnimatedBuilder doesn’t know how to render the widget, nor does it manage the Animation object.
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-25
Use AnimatedBuilder to describe an animation as part of a build method for another widget. If you simply want to define a widget with a reusable animation, use an AnimatedWidget, as shown in the Simplifying with AnimatedWidget section. Examples of AnimatedBuilders in the Flutter API: BottomSheet, ExpansionTile, PopupMenu, ProgressIndicator, RefreshIndicator, Scaffold, SnackBar, TabBar, TextField. One problem with the code in the animate3 example, is that changing the animation required changing the widget that renders the logo. A better solution is to separate responsibilities into different classes: Render the logo Define the Animation object Render the transition The widget tree for the animate4 example looks like this: Starting from the bottom of the widget tree, the code for rendering the logo is straightforward:
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-26
Starting from the bottom of the widget tree, the code for rendering the logo is straightforward: One tricky point in the code below is that the child looks like it’s specified twice. What’s happening is that the outer reference of child is passed to AnimatedBuilder, which passes it to the anonymous closure, which then uses that object as its child. The net result is that the AnimatedBuilder is inserted in between the two widgets in the render tree. animate2 example. The {animate2 → animate4}/lib/main.dart @@ -1,27 +1,47 @@ 1 1 import 'package:flutter/material.dart'; 2 2 void main() => runApp(const LogoApp()); class AnimatedLogo extends AnimatedWidget { const AnimatedLogo({super.key, required Animation<double> animation})
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-27
const AnimatedLogo({super.key, required Animation<double> animation}) : super(listenable: animation); + class LogoWidget extends StatelessWidget { + const LogoWidget({super.key}); + // Leave out the height and width so it fills the animating parent + @override + Widget build(BuildContext context) { + return Container( 10 + margin: const EdgeInsets.symmetric(vertical: 10), 11 + child: const FlutterLogo(), 12 + ); 13 + } 14 + } 15
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-28
+ } 15 16 + class GrowTransition extends StatelessWidget { 17 + const GrowTransition( 18 + {required this.child, required this.animation, super.key}); 19 20 + final Widget child; 21 + final Animation<double> animation; 6 22 @override 7 23 Widget build(BuildContext context) { final animation = listenable as Animation<double>; 9 24 return Center( 10 child: Container( 11
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-29
child: Container( 11 margin: const EdgeInsets.symmetric(vertical: 10), 12 height: animation.value, 13 width: animation.value, 14 child: const FlutterLogo(), 25 + child: AnimatedBuilder( 26 + animation: animation, 27 + builder: (context, child) { 28 + return SizedBox( 29 + height: animation.value, 30 + width: animation.value, 31
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-30
+ width: animation.value, 31 + child: child, 32 + ); 33 + }, 34 + child: child, 15 35 ), 16 36 ); 17 37 18 38 19 39 class LogoApp extends StatefulWidget { 20 40 const LogoApp({super.key}); 21 41 @override 22 42 State<LogoApp> createState() => _LogoAppState();
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-31
State<LogoApp> createState() => _LogoAppState(); @@ -34,18 +54,23 @@ 34 54 @override 35 55 void initState() { 36 56 super.initState(); 37 57 controller = 38 58 AnimationController(duration: const Duration(seconds: 2), vsync: this); 39 59 animation = Tween<double>(begin: 0, end: 300).animate(controller); 40 60 controller.forward(); 41 61 42 62 @override 43
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-32
@override 43 Widget build(BuildContext context) => AnimatedLogo(animation: animation); 63 + Widget build(BuildContext context) { 64 + return GrowTransition( 65 + animation: animation, 66 + child: const LogoWidget(), 67 + ); 68 + } 44 69 @override 45 70 void dispose() { 46 71 controller.dispose(); 47 72 super.dispose(); 48 73
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-33
super.dispose(); 48 73 49 74 App source: animate4 Simultaneous animations What's the point? The Curves class defines an array of commonly used curves that you can use with a CurvedAnimation. In this section, you’ll build on the example from monitoring the progress of the animation (animate3), which used AnimatedWidget to animate in and out continuously. Consider the case where you want to animate in and out while the opacity animates from transparent to opaque. Note: This example shows how to use multiple tweens on the same animation controller, where each tween manages a different effect in the animation. It is for illustrative purposes only. If you were tweening opacity and size in production code, you’d probably use FadeTransition and SizeTransition instead.
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-34
Each tween manages an aspect of the animation. For example: You can get the size with sizeAnimation.value and the opacity with opacityAnimation.value, but the constructor for AnimatedWidget only takes a single Animation object. To solve this problem, the example creates its own Tween objects and explicitly calculates the values. Change AnimatedLogo to encapsulate its own Tween objects, and its build() method calls Tween.evaluate() on the parent’s animation object to calculate the required size and opacity values. The following code shows the changes with highlights: static final _opacityTween = Tween<double>(begin: 0.1, end: 1); static final _sizeTween = Tween<double>(begin: 0, end: 300); @override Widget build(BuildContext context) { final animation = listenable as Animation<double>; return Center( child: Opacity(
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-35
child: Opacity( opacity: _opacityTween.evaluate(animation), child: Container( margin: const EdgeInsets.symmetric(vertical: 10), height: _sizeTween.evaluate(animation), width: _sizeTween.evaluate(animation), child: const FlutterLogo(), ), ), ); } } class LogoApp extends StatefulWidget { const LogoApp({super.key}); @override State<LogoApp> createState() => _LogoAppState(); } class _LogoAppState extends State<LogoApp> with SingleTickerProviderStateMixin { late Animation<double> animation; late AnimationController controller;
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-36
@override void initState() { super.initState(); controller = AnimationController(duration: const Duration(seconds: 2), vsync: this); animation = CurvedAnimation(parent: controller, curve: Curves.easeIn) ..addStatusListener((status) { if (status == AnimationStatus.completed) { controller.reverse(); } else if (status == AnimationStatus.dismissed) { controller.forward(); } }); controller.forward(); } @override Widget build(BuildContext context) => AnimatedLogo(animation: animation); @override void dispose() { controller.dispose(); super.dispose(); } } App source: animate5 Next steps
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
58eaf49a934e-37
App source: animate5 Next steps This tutorial gives you a foundation for creating animations in Flutter using Tweens, but there are many other classes to explore. You might investigate the specialized Tween classes, animations specific to Material Design, ReverseAnimation, shared element transitions (also known as Hero animations), physics simulations and fling() methods. See the animations landing page for the latest available documents and examples.
https://docs.flutter.dev/development/ui/animations/tutorial/index.html
652a356a6113-0
Adding assets and images UI Assets and images Specifying assets Asset bundling Asset variants Loading assets Loading text assets Loading images Declaring resolution-aware image assets Loading images Asset images in package dependencies Bundling of package assets Sharing assets with the underlying platform Loading Flutter assets in Android Loading Flutter assets in iOS Loading iOS images in Flutter Platform assets Updating the app icon Android iOS Updating the launch screen Android iOS
https://docs.flutter.dev/development/ui/assets-and-images/index.html
652a356a6113-1
Updating the launch screen Android iOS Flutter apps can include both code and assets (sometimes called resources). An asset is a file that is bundled and deployed with your app, and is accessible at runtime. Common types of assets include static data (for example, JSON files), configuration files, icons, and images (JPEG, WebP, GIF, animated WebP/GIF, PNG, BMP, and WBMP). Specifying assets Flutter uses the pubspec.yaml file, located at the root of your project, to identify assets required by an app. Here is an example: flutter assets assets/my_icon.png assets/background.png To include all assets under a directory, specify the directory name with the / character at the end: flutter assets directory/
https://docs.flutter.dev/development/ui/assets-and-images/index.html
652a356a6113-2
flutter assets directory/ directory/subdirectory/ Note: Only files located directly in the directory are included unless there are files with the same name inside a subdirectory (see Asset Variants). To add files located in subdirectories, create an entry per directory. Asset bundling The assets subsection of the flutter section specifies files that should be included with the app. Each asset is identified by an explicit path (relative to the pubspec.yaml file) where the asset file is located. The order in which the assets are declared doesn’t matter. The actual directory name used (assets in first example or directory in the above example) doesn’t matter. During a build, Flutter places assets into a special archive called the asset bundle that apps read from at runtime. Asset variants
https://docs.flutter.dev/development/ui/assets-and-images/index.html
652a356a6113-3
Asset variants The build process supports the notion of asset variants: different versions of an asset that might be displayed in different contexts. When an asset’s path is specified in the assets section of pubspec.yaml, the build process looks for any files with the same name in adjacent subdirectories. Such files are then included in the asset bundle along with the specified asset. For example, if you have the following files in your application directory: And your pubspec.yaml file contains the following: flutter assets graphics/background.png Then both graphics/background.png and graphics/dark/background.png are included in your asset bundle. The former is considered the main asset, while the latter is considered a variant. If, on the other hand, the graphics directory is specified: flutter assets graphics/
https://docs.flutter.dev/development/ui/assets-and-images/index.html
652a356a6113-4
flutter assets graphics/ Then the graphics/my_icon.png, graphics/background.png and graphics/dark/background.png files are also included. Flutter uses asset variants when choosing resolution-appropriate images. In the future, this mechanism might be extended to include variants for different locales or regions, reading directions, and so on. Loading assets Your app can access its assets through an AssetBundle object. The two main methods on an asset bundle allow you to load a string/text asset (loadString()) or an image/binary asset (load()) out of the bundle, given a logical key. The logical key maps to the path to the asset specified in the pubspec.yaml file at build time. Loading text assets
https://docs.flutter.dev/development/ui/assets-and-images/index.html
652a356a6113-5
Loading text assets Each Flutter app has a rootBundle object for easy access to the main asset bundle. It is possible to load assets directly using the rootBundle global static from package:flutter/services.dart. However, it’s recommended to obtain the AssetBundle for the current BuildContext using DefaultAssetBundle, rather than the default asset bundle that was built with the app; this approach enables a parent widget to substitute a different AssetBundle at run time, which can be useful for localization or testing scenarios. Typically, you’ll use DefaultAssetBundle.of() to indirectly load an asset, for example a JSON file, from the app’s runtime rootBundle. Outside of a Widget context, or when a handle to an AssetBundle is not available, you can use rootBundle to directly load such assets. For example: Loading images Flutter can load resolution-appropriate images for the current device pixel ratio.
https://docs.flutter.dev/development/ui/assets-and-images/index.html
652a356a6113-6
Flutter can load resolution-appropriate images for the current device pixel ratio. Declaring resolution-aware image assets AssetImage understands how to map a logical requested asset onto one that most closely matches the current device pixel ratio. In order for this mapping to work, assets should be arranged according to a particular directory structure: Where M and N are numeric identifiers that correspond to the nominal resolution of the images contained within. In other words, they specify the device pixel ratio that the images are intended for. The main asset is assumed to correspond to a resolution of 1.0. For example, consider the following asset layout for an image named my_icon.png: On devices with a device pixel ratio of 1.8, the asset .../2.0x/my_icon.png is chosen. For a device pixel ratio of 2.7, the asset .../3.0x/my_icon.png is chosen.
https://docs.flutter.dev/development/ui/assets-and-images/index.html
652a356a6113-7
If the width and height of the rendered image are not specified on the Image widget, the nominal resolution is used to scale the asset so that it occupies the same amount of screen space as the main asset would have, just with a higher resolution. That is, if .../my_icon.png is 72px by 72px, then .../3.0x/my_icon.png should be 216px by 216px; but they both render into 72px by 72px (in logical pixels), if width and height are not specified. Each entry in the asset section of the pubspec.yaml should correspond to a real file, with the exception of the main asset entry. If the main asset entry doesn’t correspond to a real file, then the asset with the lowest resolution is used as the fallback for devices with device pixel ratios below that resolution. The entry should still be included in the pubspec.yaml manifest, however. Loading images
https://docs.flutter.dev/development/ui/assets-and-images/index.html
652a356a6113-8
Loading images To load an image, use the AssetImage class in a widget’s build() method. For example, your app can load the background image from the asset declarations above: Anything using the default asset bundle inherits resolution awareness when loading images. (If you work with some of the lower level classes, like ImageStream or ImageCache, you’ll also notice parameters related to scale.) Device pixel ratio depends on MediaQueryData.size which requires to have either a MaterialApp or CupertinoApp as an ancestor of your AssetImage. Asset images in package dependencies To load an image from a package dependency, the package argument must be provided to AssetImage. For instance, suppose your application depends on a package called my_icons, which has the following directory structure: To load the image, use:
https://docs.flutter.dev/development/ui/assets-and-images/index.html
652a356a6113-9
To load the image, use: Assets used by the package itself should also be fetched using the package argument as above. Bundling of package assets If the desired asset is specified in the pubspec.yaml file of the package, it’s bundled automatically with the application. In particular, assets used by the package itself must be specified in its pubspec.yaml. A package can also choose to have assets in its lib/ folder that are not specified in its pubspec.yaml file. In this case, for those images to be bundled, the application has to specify which ones to include in its pubspec.yaml. For instance, a package named fancy_backgrounds could have the following files: To include, say, the first image, the pubspec.yaml of the application should specify it in the assets section: flutter assets packages/fancy_backgrounds/backgrounds/background1.png
https://docs.flutter.dev/development/ui/assets-and-images/index.html
652a356a6113-10
packages/fancy_backgrounds/backgrounds/background1.png The lib/ is implied, so it should not be included in the asset path. If you are developing a package, to load an asset within the package, specify it in the ‘pubspec.yaml’ of the package: flutter assets assets/images/ To load the image within your package, use: return const AssetImage 'packages/fancy_backgrounds/backgrounds/background1.png' ); Sharing assets with the underlying platform Flutter assets are readily available to platform code using the AssetManager on Android and NSBundle on iOS. Loading Flutter assets in Android AssetManager API. The lookup key used in, for instance openFd, is obtained from
https://docs.flutter.dev/development/ui/assets-and-images/index.html
652a356a6113-11
openFd, is obtained from PluginRegistry.Registrar or FlutterView. As an example, suppose you have specified the following in your pubspec.yaml flutter assets icons/heart.png This reflects the following structure in your Flutter app. To access icons/heart.png from your Java plugin code, do the following: AssetManager assetManager registrar context (). getAssets (); String key registrar lookupKeyForAsset "icons/heart.png" ); AssetFileDescriptor fd assetManager openFd key
https://docs.flutter.dev/development/ui/assets-and-images/index.html
652a356a6113-12
assetManager openFd key ); Loading Flutter assets in iOS mainBundle. The lookup key used in, for instance pathForResource:ofType:, is obtained from FlutterPluginRegistrar, or FlutterViewController. As an example, suppose you have the Flutter setting from above. To access icons/heart.png from your Objective-C plugin code you would do the following: To access icons/heart.png from your Swift app you would do the following: let key controller lookupKey forAsset "icons/heart.png" let mainBundle Bundle main let path mainBundle
https://docs.flutter.dev/development/ui/assets-and-images/index.html
652a356a6113-13
let path mainBundle path forResource key ofType nil For a more complete example, see the implementation of the Flutter video_player plugin on pub.dev. The ios_platform_images plugin on pub.dev wraps up this logic in a convenient category. You fetch an image as follows: Objective-C: Swift: UIImage flutterImageNamed "icons/heart.png" Loading iOS images in Flutter When implementing Flutter by adding it to an existing iOS app, you might have images hosted in iOS that you want to use in Flutter. To accomplish that, use the ios_platform_images plugin available on pub.dev. Platform assets
https://docs.flutter.dev/development/ui/assets-and-images/index.html
652a356a6113-14
Platform assets There are other occasions to work with assets in the platform projects directly. Below are two common cases where assets are used before the Flutter framework is loaded and running. Updating the app icon Updating a Flutter application’s launch icon works the same way as updating launch icons in native Android or iOS applications. Android In your Flutter project’s root directory, navigate to .../android/app/src/main/res. The various bitmap resource folders such as mipmap-hdpi already contain placeholder images named ic_launcher.png. Replace them with your desired assets respecting the recommended icon size per screen density as indicated by the Android Developer Guide. iOS
https://docs.flutter.dev/development/ui/assets-and-images/index.html
652a356a6113-15
iOS In your Flutter project’s root directory, navigate to .../ios/Runner. The Assets.xcassets/AppIcon.appiconset directory already contains placeholder images. Replace them with the appropriately sized images as indicated by their filename as dictated by the Apple Human Interface Guidelines. Keep the original file names. Updating the launch screen Flutter also uses native platform mechanisms to draw transitional launch screens to your Flutter app while the Flutter framework loads. This launch screen persists until Flutter renders the first frame of your application. runApp() in the window.render() in response to window.onDrawFrame), the launch screen persists forever. Android
https://docs.flutter.dev/development/ui/assets-and-images/index.html
652a356a6113-16
Android To add a launch screen (also known as “splash screen”) to your Flutter application, navigate to .../android/app/src/main. In res/drawable/launch_background.xml, use this layer list drawable XML to customize the look of your launch screen. The existing template provides an example of adding an image to the middle of a white splash screen in commented code. You can uncomment it or use other drawables to achieve the intended effect. For more details, see Adding a splash screen to your Android app. iOS You can also fully customize your launch screen storyboard in Xcode by opening .../ios/Runner.xcworkspace. Navigate to Runner/Runner in the Project Navigator and drop in images by opening Assets.xcassets or do any customization using the Interface Builder in LaunchScreen.storyboard. For more details, see Adding a splash screen to your iOS app.
https://docs.flutter.dev/development/ui/assets-and-images/index.html
090d0552a853-0
User interface UI Topics: Introduction to widgets Building layouts Adding interactivity Assets and images Material Design Navigation & routing Animations Advanced UI Widget catalog
https://docs.flutter.dev/development/ui/index.html
2febaadb6ee7-0
Adding interactivity to your Flutter app UI Adding interactivity Stateful and stateless widgets Creating a stateful widget Step 0: Get ready Step 1: Decide which object manages the widget’s state Step 2: Subclass StatefulWidget Step 3: Subclass State Step 4: Plug the stateful widget into the widget tree Problems? Managing state The widget manages its own state The parent widget manages the widget’s state A mix-and-match approach Other interactive widgets Standard widgets Material Components Resources What you’ll learn How to respond to taps. How to create a custom widget. The difference between stateless and stateful widgets.
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-1
The difference between stateless and stateful widgets. How do you modify your app to make it react to user input? In this tutorial, you’ll add interactivity to an app that contains only non-interactive widgets. Specifically, you’ll modify an icon to make it tappable by creating a custom stateful widget that manages two stateless widgets. The building layouts tutorial showed you how to create the layout for the following screenshot. When the app first launches, the star is solid red, indicating that this lake has previously been favorited. The number next to the star indicates that 41 people have favorited this lake. After completing this tutorial, tapping the star removes its favorited status, replacing the solid star with an outline and decreasing the count. Tapping again favorites the lake, drawing a solid star and increasing the count.
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-2
To accomplish this, you’ll create a single custom widget that includes both the star and the count, which are themselves widgets. Tapping the star changes state for both widgets, so the same widget should manage both. You can get right to touching the code in Step 2: Subclass StatefulWidget. If you want to try different ways of managing state, skip to Managing state. Stateful and stateless widgets A widget is either stateful or stateless. If a widget can change—when a user interacts with it, for example—it’s stateful. A stateless widget never changes. Icon, IconButton, and Text are examples of stateless widgets. Stateless widgets subclass StatelessWidget. Checkbox, Radio, Slider, InkWell, Form, and
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-3
InkWell, Form, and TextField are examples of stateful widgets. Stateful widgets subclass StatefulWidget. A widget’s state is stored in a State object, separating the widget’s state from its appearance. The state consists of values that can change, like a slider’s current value or whether a checkbox is checked. When the widget’s state changes, the state object calls setState(), telling the framework to redraw the widget. Creating a stateful widget What's the point? A stateful widget is implemented by two classes: a subclass of StatefulWidget and a subclass of State. The state class contains the widget’s mutable state and the widget’s build() method. When the widget’s state changes, the state object calls setState(), telling the framework to redraw the widget.
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-4
In this section, you’ll create a custom stateful widget. You’ll replace two stateless widgets—the solid red star and the numeric count next to it—with a single custom stateful widget that manages a row with two children widgets: an IconButton and Text. Implementing a custom stateful widget requires creating two classes: A subclass of StatefulWidget that defines the widget. A subclass of State that contains the state for that widget and defines the widget’s build() method. This section shows you how to build a stateful widget, called FavoriteWidget, for the lakes app. After setting up, your first step is choosing how state is managed for FavoriteWidget. Step 0: Get ready If you’ve already built the app in the building layouts tutorial (step 6), skip to the next section. Make sure you’ve set up your environment. Create a new Flutter app.
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-5
Create a new Flutter app. Replace the lib/main.dart file with main.dart. Replace the pubspec.yaml file with pubspec.yaml. Create an images directory in your project, and add lake.jpg. Once you have a connected and enabled device, or you’ve launched the iOS simulator (part of the Flutter install) or the Android emulator (part of the Android Studio install), you are good to go! Step 1: Decide which object manages the widget’s state A widget’s state can be managed in several ways, but in our example the widget itself, FavoriteWidget, will manage its own state. In this example, toggling the star is an isolated action that doesn’t affect the parent widget or the rest of the UI, so the widget can handle its state internally. Learn more about the separation of widget and state, and how state might be managed, in Managing state.
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-6
Step 2: Subclass StatefulWidget lib/main.dart (FavoriteWidget) Note: Members or classes that start with an underscore (_) are private. For more information, see Libraries and imports, a section in the Dart language documentation. Step 3: Subclass State The _FavoriteWidgetState class stores the mutable data that can change over the lifetime of the widget. When the app first launches, the UI displays a solid red star, indicating that the lake has “favorite” status, along with 41 likes. These values are stored in the _isFavorited and _favoriteCount fields: lib/main.dart (_FavoriteWidgetState fields) bool _isFavorited = true; int _favoriteCount = 41; // ··· } IconButton (instead of
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-7
// ··· } IconButton (instead of lib/main.dart (_FavoriteWidgetState build) build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.min, children: [ Container( padding: const EdgeInsets.all(0), child: IconButton( padding: const EdgeInsets.all(0), alignment: Alignment.centerRight, icon: (_isFavorited ? const Icon(Icons.star) : const Icon(Icons.star_border)), color: Colors.red[500], onPressed: _toggleFavorite, ), ), SizedBox( width: 18, child: SizedBox( child: Text('$_favoriteCount'), ), ), ], ); } }
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-8
Tip: Placing the Text in a SizedBox and setting its width prevents a discernible “jump” when the text changes between the values of 40 and 41 — a jump would otherwise occur because those values have different widths. The _toggleFavorite() method, which is called when the IconButton is pressed, calls setState(). Calling setState() is critical, because this tells the framework that the widget’s state has changed and that the widget should be redrawn. The function argument to setState() toggles the UI between these two states: A star icon and the number 41 A star_border icon and the number 40 Step 4: Plug the stateful widget into the widget tree Add your custom stateful widget to the widget tree in the app’s build() method. First, locate the code that creates the Icon and Text, and delete it. In the same location, create the stateful widget:
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-9
layout/lakes/{step6 → interactive}/lib/main.dart @@ -10,2 +5,2 @@ 10 5 class MyApp extends StatelessWidget { 11 6 const MyApp({super.key}); @@ -40,11 +35,7 @@ 40 35 ], 41 36 ), 42 37 ), 43 Icon( 44 Icons.star, 45 color: Colors.red[500], 46 ), 47 const Text('41'), 38
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-10
const Text('41'), 38 + const FavoriteWidget(), 48 39 ], 49 40 ), 50 41 ); That’s it! When you hot reload the app, the star icon should now respond to taps. Problems? If you can’t get your code to run, look in your IDE for possible errors. Debugging Flutter apps might help. If you still can’t find the problem, check your code against the interactive lakes example on GitHub. lib/main.dart pubspec.yaml lakes.jpg If you still have questions, refer to any one of the developer community channels.
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-11
If you still have questions, refer to any one of the developer community channels. The rest of this page covers several ways a widget’s state can be managed, and lists other available interactive widgets. Managing state What's the point? There are different approaches for managing state. You, as the widget designer, choose which approach to use. If in doubt, start by managing state in the parent widget. Who manages the stateful widget’s state? The widget itself? The parent widget? Both? Another object? The answer is… it depends. There are several valid ways to make your widget interactive. You, as the widget designer, make the decision based on how you expect your widget to be used. Here are the most common ways to manage state: The widget manages its own state The parent manages the widget’s state A mix-and-match approach
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-12
A mix-and-match approach How do you decide which approach to use? The following principles should help you decide: If the state in question is user data, for example the checked or unchecked mode of a checkbox, or the position of a slider, then the state is best managed by the parent widget. If the state in question is aesthetic, for example an animation, then the state is best managed by the widget itself. If in doubt, start by managing state in the parent widget. We’ll give examples of the different ways of managing state by creating three simple examples: TapboxA, TapboxB, and TapboxC. The examples all work similarly—each creates a container that, when tapped, toggles between a green or grey box. The _active boolean determines the color: green for active or grey for inactive. These examples use GestureDetector to capture activity on the Container.
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-13
These examples use GestureDetector to capture activity on the Container. The widget manages its own state Sometimes it makes the most sense for the widget to manage its state internally. For example, ListView automatically scrolls when its content exceeds the render box. Most developers using ListView don’t want to manage ListView’s scrolling behavior, so ListView itself manages its scroll offset. The _TapboxAState class: Manages state for TapboxA. Defines the _active boolean which determines the box’s current color. Defines the _handleTap() function, which updates _active when the box is tapped and calls the setState() function to update the UI. Implements all interactive behavior for the widget. The parent widget manages the widget’s state
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-14
The parent widget manages the widget’s state Often it makes the most sense for the parent widget to manage the state and tell its child widget when to update. For example, IconButton allows you to treat an icon as a tappable button. IconButton is a stateless widget because we decided that the parent widget needs to know whether the button has been tapped, so it can take appropriate action. In the following example, TapboxB exports its state to its parent through a callback. Because TapboxB doesn’t manage any state, it subclasses StatelessWidget. The ParentWidgetState class: Manages the _active state for TapboxB. Implements _handleTapboxChanged(), the method called when the box is tapped. When the state changes, calls setState() to update the UI. The TapboxB class: Extends StatelessWidget because all state is handled by its parent.
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-15
Extends StatelessWidget because all state is handled by its parent. When a tap is detected, it notifies the parent. A mix-and-match approach For some widgets, a mix-and-match approach makes the most sense. In this scenario, the stateful widget manages some of the state, and the parent widget manages other aspects of the state. The _ParentWidgetState object: Manages the _active state. Implements _handleTapboxChanged(), the method called when the box is tapped. Calls setState() to update the UI when a tap occurs and the _active state changes. The _TapboxCState object: Manages the _highlight state.
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-16
Manages the _highlight state. The GestureDetector listens to all tap events. As the user taps down, it adds the highlight (implemented as a dark green border). As the user releases the tap, it removes the highlight. Calls setState() to update the UI on tap down, tap up, or tap cancel, and the _highlight state changes. On a tap event, passes that state change to the parent widget to take appropriate action using the widget property. An alternate implementation might have exported the highlight state to the parent while keeping the active state internal, but if you asked someone to use that tap box, they’d probably complain that it doesn’t make much sense. The developer cares whether the box is active. The developer probably doesn’t care how the highlighting is managed, and prefers that the tap box handles those details. Other interactive widgets
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-17
Other interactive widgets Flutter offers a variety of buttons and similar interactive widgets. Most of these widgets implement the Material Design guidelines, which define a set of components with an opinionated UI. GestureDetector to build interactivity into any custom widget. You can find examples of Managing state. Learn more about the Handle taps, a recipe in the Flutter cookbook. Tip: Flutter also provides a set of iOS-style widgets called Cupertino. When you need interactivity, it’s easiest to use one of the prefabricated widgets. Here’s a partial list: Standard widgets Form FormField Material Components Checkbox DropdownButton TextButton FloatingActionButton IconButton
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-18
TextButton FloatingActionButton IconButton Radio ElevatedButton Slider Switch TextField Resources The following resources might help when adding interactivity to your app. Gestures, a section in the Flutter cookbook. Handling gestures, a section in Introduction to widgets How to create a button and make it respond to input. Gestures in Flutter A description of Flutter’s gesture mechanism. Flutter API documentation Reference documentation for all of the Flutter libraries. running app, repo Demo app showcasing many Material components and other Flutter features. Flutter’s Layered Design (video)
https://docs.flutter.dev/development/ui/interactive/index.html
2febaadb6ee7-19
Flutter’s Layered Design (video) This video includes information about state and stateless widgets. Presented by Google engineer, Ian Hickson.
https://docs.flutter.dev/development/ui/interactive/index.html
44306f44f88c-0
Creating responsive and adaptive apps UI Layout Responsive and adaptive The difference between an adaptive and a responsive app Creating a responsive Flutter app Other resources Creating an adaptive Flutter app Other resources One of Flutter’s primary goals is to create a framework that allows you to develop apps from a single codebase that look and feel great on any platform. This means that your app may appear on screens of many different sizes, from a watch, to a foldable phone with two screens, to a high def monitor. Two terms that describe concepts for this scenario are adaptive and responsive. Ideally, you’d want your app to be both but what, exactly, does this mean? These terms are similar, but they are not the same. The difference between an adaptive and a responsive app
https://docs.flutter.dev/development/ui/layout/adaptive-responsive/index.html
44306f44f88c-1
The difference between an adaptive and a responsive app Adaptive and responsive can be viewed as separate dimensions of an app: you can have an adaptive app that is not responsive, or vice versa. And, of course, an app can be both, or neither. Typically, a responsive app has had its layout tuned for the available screen size. Often this means (for example), re-laying out the UI if the user resizes the window, or changes the device’s orientation. This is especially necessary when the same app can run on a variety of devices, from a watch, phone, tablet, to a laptop or desktop computer.
https://docs.flutter.dev/development/ui/layout/adaptive-responsive/index.html
44306f44f88c-2
Adapting an app to run on different device types, such as mobile and desktop, requires dealing with mouse and keyboard input, as well as touch input. It also means there are different expectations about the app’s visual density, how component selection works (cascading menus vs bottom sheets, for example), using platform-specific features (such as top-level windows), and more. Creating a responsive Flutter app Flutter allows you to create apps that self-adapt to the device’s screen size and orientation. There are two basic approaches to creating Flutter apps with responsive design: LayoutBuilder class
https://docs.flutter.dev/development/ui/layout/adaptive-responsive/index.html
44306f44f88c-3
LayoutBuilder class From its builder property, you get a BoxConstraints object. Examine the constraint’s properties to decide what to display. For example, if your maxWidth is greater than your width breakpoint, return a Scaffold object with a row that has a list on the left. If it’s narrower, return a Scaffold object with a drawer containing that list. You can also adjust your display based on the device’s height, the aspect ratio, or some other property. When the constraints change (for example, the user rotates the phone, or puts your app into a tile UI in Nougat), the build function runs. MediaQuery.of() method in your build functions This gives you the size, orientation, etc, of your current app. This is more useful if you want to make decisions based on the complete context rather than on just the size of your particular widget. Again, if you use this, then your build function automatically runs if the user somehow changes the app’s size.
https://docs.flutter.dev/development/ui/layout/adaptive-responsive/index.html