Laggy SizeTransition Animation in Flutter Column? - flutter

I'm trying to animate a panel coming up from the bottom of the screen. My setup is to have a column with two Containers, then animate the size of the lower Container to get a "sliding up" panel effect. The panel shouldn't be on top of the other so I can't use a stack.
Anyway, the problem is using the SizeTransition. I create an AnimationController to control the sizeFactor of the SizeTransition. The problem is that using any Curves in the animation makes it horribly laggy and I don't know why. Obviously, there must be a way to make this run smoothly but I'm at a loss. Here is a minimal example of what I mean:
class WelcomePage extends StatefulWidget {
#override
_WelcomePageState createState() => _WelcomePageState();
}
class _WelcomePageState extends State<WelcomePage>
with SingleTickerProviderStateMixin {
AnimationController _controller;
#override
void initState() {
_controller = AnimationController(
vsync: this,
duration: Duration(milliseconds: 500),
);
// Setting to curve: Curves.linear here makes it run smoothly but anything else brings us to choppy town
_controller.animateTo(210.0, curve: Curves.ease);
super.initState();
}
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Expanded(child: Container(color: Colors.blue)),
SizeTransition(
sizeFactor: _controller,
child: Container(
height: 200,
color: Colors.green,
))
],
);
}
}

Related

how to make icon and text translation animation on flutter

how to make this animation on flutter
icon and text
the default state is the icon is shown and the text is disappears
when click the icon: the icon goes up and text goes under icon and appears
otherwise the icon goes in center and the text disappears
like this video
https://i.imgur.com/S0LXr3o.mp4
https://drive.google.com/file/d/1nwpgjOM_6TUaaVaSdsIZp0oYi4CdWSMR/view?usp=sharing
you can use AnimationController and AnimationBuilder combined with Stack + Positioned
or you can even use the Transform Widget with the same concept!
I've write an example to make the animation
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
class AnimationExerciseScreen extends StatefulWidget {
const AnimationExerciseScreen({Key? key}) : super(key: key);
#override
_AnimationExerciseScreenState createState() =>
_AnimationExerciseScreenState();
}
class _AnimationExerciseScreenState extends State<AnimationExerciseScreen>
with SingleTickerProviderStateMixin {
#override
void initState() {
super.initState();
animationController = AnimationController(
vsync: this,
duration: Duration(seconds: 3),
);
animationController.forward();
}
#override
void dispose() {
animationController.dispose();
super.dispose();
}
late final AnimationController animationController;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
height: 100,
child: AnimatedBuilder(
animation: animationController,
builder: (context, child) => Stack(
children: [
Positioned(
top: 0 + (40 * animationController.value),
child: Icon(Icons.cloud),
),
Positioned(
bottom: 0 + (40 * animationController.value),
child: Opacity(
opacity: 1 - animationController.value,
child: Text('Cloud'),
),
),
],
),
),
),
],
),
),
);
}
}
video link:
https://imgur.com/RJg5PWw
Explanation:
the animation controller has a value of 0 to 1 with the type of double, which will represent the amount percentage of the animation
in the above example, I'm using 3 seconds duration of the animation controller so the animation will be visible to our eyes easily, so I use animationController.forward to play the animation at the initState
note: the placement of the animation is not optimized for performance, this example is just for example to understand how the animation works
if you want to optimize the animation, you can put your widget to child attribute of the AnimationBuilder for more info you can read them here and here and here and so much more! you can explore tons of articles to improve your flutter app's performance!

Creating a widget upon clicking a button in flutter using animation

I'm new to flutter I have a search field and upon clicking, it should expand to another input field. I have done it but the widget gets re-created upon clicking the search filed.
As you can see, I want these fields to open up nicely with animation so that it looks good. Do you have any suggestions?
You can wrap the second TextField in a AnimatedContainer (or in a SizeTransition, but you will have to use a AnimationController).
If you use a AnimatedContainer you can simply change the height of the widget by a bool and the widget will animate itself. Eg:
AnimatedContainer(
width: MediaQuery.of(context).size.width,
height: showSecondField ? 40 : 0,
child: ...
)
or with the SizeTransition:
class YourWidget extends State<...> with SingleTickerProviderStateMixin {
AnimationController _controller;
Animation<double> _anim;
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 200),
);
final CurvedAnimation curve = CurvedAnimation(parent: _controller, curve: Curves.fastOutSlowIn);
_anim = Tween<double>(begin: 0.0, end: 1.0).animate(curve);
}
#override
Widget build(BuildContext context) {
return SizeTransition(
sizeFactor: _anim,
child: TextField()
);
}
}
And you can open or close with: _controller.forward() and _controller.reverse()

Flutter loader: resize and rotate at the same time

I'm new to Flutter and would like to make a customized loader, but can't find a solution. When a user clicks on a button and some operation begins, I'd like to show a customized widget (basically a loader, notifying a user that operation has begun) that pops up to the center of the screen and grows in size (from 0x0 to 300x300), while it is rotating at the same time. When it reaches maximum size (300x300), I want it to shrink back to the size of 0x0 and hide/disappear, while rotating as well.
This animation should take 2 seconds. If after 2 seconds the operation is not completed, I'd like to start over with the animation.
You can create your own animations very easily. Using Animation and AnimationController you can do basically anything that you can think of.
Check out this video if you want to dig deeper into Animations with Flutter to make Complex UIs
To achieve what you are asking, you can build your Loading Indicator using a stateless widget.
Here is an interactive example
class MyLoadingIndicator extends StatefulWidget {
final Widget child;
const MyLoadingIndicator({
#required this.child,
Key key,
}) : super(key: key);
#override
_MyLoadingIndicatorState createState() => _MyLoadingIndicatorState();
}
class _MyLoadingIndicatorState extends State<MyLoadingIndicator> with TickerProviderStateMixin {
AnimationController rotateController;
Animation<double> rotateAnimation;
AnimationController scaleController;
Animation<double> scaleAnimation;
#override
void initState() {
super.initState();
rotateController = AnimationController(
duration: const Duration(seconds: 1),
reverseDuration: const Duration(seconds: 1),
vsync: this,
);
rotateAnimation = CurvedAnimation(parent: rotateController, curve: Curves.linear);
rotateController.repeat(
min: 0,
max: 1,
period: Duration(seconds: 2),
);
scaleController = AnimationController(
duration: const Duration(seconds: 1),
reverseDuration: const Duration(seconds: 1),
vsync: this,
);
scaleAnimation = CurvedAnimation(parent: scaleController, curve: Curves.linear);
scaleController.repeat(
min: 0,
max: 1,
period: Duration(seconds: 2),
reverse: true,
);
}
#override
void dispose() {
rotateController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return RotationTransition(
turns: rotateAnimation,
child: ScaleTransition(
scale: scaleAnimation,
child: Container(
height: 300,
width: 300,
color: Colors.red,
child: widget.child,
),
),
);
}
}

Flutter SlideTransition begin with Offset OFF SCREEN

My app is a simple Column with 3 Text widgets wrapped in SlideTransitions. My goal is for the app to load with nothing on the screen, and then animate these Text widgets from the bottom (off screen) up into the screen (settling in the middle).
return Column(
children: <Widget>[
SlideTransition(
position:_curve1,
child: Text('Hello 1')
),
SlideTransition(
position:_curve1,
child: Text('Hello 2')
),
SlideTransition(
position:_curve1,
child: Text('Hello 3')
),
]
);
The problem is that when defining the animation, you have to specify their initial Offset.
#override
void initState(){
...
Offset beginningOffset = Offset(0.0,20.0);
_curve1 = Tween<Offset>(begin: beginningOffset, end: Offset.zero).animate(
CurvedAnimation(
parent: _animationController,
curve: Curves.easeInOut)));
...
}
Here you can see that beginningOffset is specified as Offset(0.0, 20.0) which does successfully position the widgets off screen. But what happens if I suddenly run this on a tablet? Since Offset is defined as units of the height of the widget, then this is obviously not a good way to position a widget off screen.
Since the animation is defined in "initState()" ... I see no way to use something like MediaQuery.of(context) ... since we don't have context there.
In native iOS this would be simple. Within "viewDidLoad" you would get the frame from self.view. You'd position each text field at the edge of the frame explicitly. You'd then animate a constraint change, positioning them where you want them. Why must this be so hard in Flutter?
I find it especially curious that this exact scenario (starting an animation just off screen) is totally not covered in any of the examples I could find. For instance:
https://github.com/flutter/website/blob/master/examples/_animation/basic_staggered_animation/main.dart
Seems like almost every type of animation is featured here EXCEPT an explicit off screen animation on load... Perhaps I'm just missing something.
EDIT: ThePeanut has solved it! Check his "Second Update".
You might want to try using the addPostFrameCallback method in your initState.
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_){
// Schedule code execution once after the frame has rendered
print(MediaQuery.of(context).size.toString());
});
}
Flutter Api Docs Link
OR you can also use a Future for this:
#override
void initState() {
super.initState();
new Future.delayed(Duration.zero, () {
// Schedule a zero-delay future to be executed
print(MediaQuery.of(context).size.toString());
});
}
Hope this helps.
UPDATED
A bit of a unusual way to do it, but it really does the thing you need.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
Animation<Offset> animation;
AnimationController animationController;
#override
void initState() {
super.initState();
animationController = AnimationController(
vsync: this,
duration: Duration(seconds: 2),
);
animation = Tween<Offset>(
begin: Offset(0.0, 1.0),
end: Offset(0.0, 0.0),
).animate(CurvedAnimation(
parent: animationController,
curve: Curves.fastLinearToSlowEaseIn,
));
Future<void>.delayed(Duration(seconds: 1), () {
animationController.forward();
});
}
#override
void dispose() {
// Don't forget to dispose the animation controller on class destruction
animationController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Stack(
alignment: Alignment.center,
fit: StackFit.expand,
children: <Widget>[
SlideTransition(
position: animation,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircleAvatar(
backgroundImage: NetworkImage(
'https://pbs.twimg.com/media/DpeOMc3XgAIMyx_.jpg',
),
radius: 50.0,
),
],
),
),
],
),
);
}
}
It works this way:
1. We create a Stack of items with options to expand any child inside it.
2. Wrap each slide you want to display in to a Column with center alignment of children. The Column will take 100% of the size of the Stack.
3. Set the beginning Offset for animation to Offset(0.0, 1.0).
Keep in mind that dx and dy in Offset are not pixels or something like that, but the ratio of Widget's width or height. For example: if your widget's width is 100.0 and you put 0.25 as dx - it will result in moving your child to the right by 25.0 points.
So setting offset to (0.0, 1.0) will move the Column offscreen to the bottom by it's 100% height (this is how many page transitions work in Flutter).
4. Animate the Column back to it's original position after a 1 second delay.
SECOND UPDATE
This code calculates the offset based on the screen size and widget size.
PS. There might be a better way of doing this that I don't know of.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Page(),
);
}
}
class Page extends StatefulWidget {
#override
State<StatefulWidget> createState() => _PageState();
}
class _PageState extends State<Page> with SingleTickerProviderStateMixin {
// Set the initial position to something that will be offscreen for sure
Tween<Offset> tween = Tween<Offset>(
begin: Offset(0.0, 10000.0),
end: Offset(0.0, 0.0),
);
Animation<Offset> animation;
AnimationController animationController;
GlobalKey _widgetKey = GlobalKey();
#override
void initState() {
super.initState();
// initialize animation controller and the animation itself
animationController = AnimationController(
vsync: this,
duration: Duration(seconds: 2),
);
animation = tween.animate(animationController);
Future<void>.delayed(Duration(seconds: 1), () {
// Get the screen size
final Size screenSize = MediaQuery.of(context).size;
// Get render box of the widget
final RenderBox widgetRenderBox =
_widgetKey.currentContext.findRenderObject();
// Get widget's size
final Size widgetSize = widgetRenderBox.size;
// Calculate the dy offset.
// We divide the screen height by 2 because the initial position of the widget is centered.
// Ceil the value, so we get a position that is a bit lower the bottom edge of the screen.
final double offset = (screenSize.height / 2 / widgetSize.height).ceilToDouble();
// Re-set the tween and animation
tween = Tween<Offset>(
begin: Offset(0.0, offset),
end: Offset(0.0, 0.0),
);
animation = tween.animate(animationController);
// Call set state to re-render the widget with the new position.
this.setState((){
// Animate it.
animationController.forward();
});
});
}
#override
void dispose() {
// Don't forget to dispose the animation controller on class destruction
animationController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Stack(
alignment: Alignment.center,
fit: StackFit.loose,
children: <Widget>[
SlideTransition(
position: animation,
child: CircleAvatar(
key: _widgetKey,
backgroundImage: NetworkImage(
'https://pbs.twimg.com/media/DpeOMc3XgAIMyx_.jpg',
),
radius: 50.0,
),
),
],
);
}
}
I found this solution, to have the exact value of off-screen.
Screen size / 2 / widget size + half of 1 offset
Without the half offset, only half of the widget is off-screen.
final widgetHeight = 190;
final offsetScreen = MediaQueryData.fromWindow(WidgetsBinding.instance!.window).size.height / 2 / widgetHeight + 0.5;

How to slow down a fling animation in Flutter?

I was playing with the fling animation based on the grid demo in Flutter Gallery. I made the example below work, but the animation plays very fast. I could barely see it unless I slow it down by using timeDilation. Changing the value of velocity doesn't seem to have much effect. Should I look at something else? Thanks!
import 'package:flutter/animation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart' show timeDilation;
const kLogoUrl =
"https://raw.githubusercontent.com/dart-lang/logos/master/logos_and_wordmarks/dart-logo.png";
class LogoWidget extends StatelessWidget {
// Leave out the height and width so it fills the animating parent
build(BuildContext context) {
return new Container(
margin: new EdgeInsets.symmetric(vertical: 10.0),
child: new Image.network(kLogoUrl));
}
}
class TranslateTransition extends StatelessWidget {
TranslateTransition({this.child, this.animation});
Widget child;
Animation<Offset> animation;
Widget build(BuildContext context) {
return new AnimatedBuilder(
animation: animation,
builder: (BuildContext context, Widget child) {
return new Center(
child: new Transform(
transform: new Matrix4.identity()
..translate(animation.value.dx, animation.value.dy),
child: new Container(
height: 100.0,
width: 100.0,
child: child,
),
),
);
},
child: child);
}
}
class LogoApp extends StatefulWidget {
LogoAppState createState() => new LogoAppState();
}
class LogoAppState extends State<LogoApp> with TickerProviderStateMixin {
Animation<Offset> _flingAnimation;
AnimationController _controller;
initState() {
super.initState();
timeDilation = 5.0;
_controller = new AnimationController(
vsync: this,
);
_flingAnimation = new Tween<Offset>(
begin: new Offset(-150.0, -150.0),
end: new Offset(150.0, 150.0),
)
.animate(_controller);
_controller
..value = 0.0
..fling(velocity: 0.1)
..addListener(() {
// print(_flingAnimation.value);
});
}
Widget build(BuildContext context) {
return new TranslateTransition(
child: new LogoWidget(), animation: _flingAnimation);
}
#override
dispose() {
_controller.dispose();
}
}
void main() {
runApp(new LogoApp());
}
fling uses a SpringSimulation with default parameters, one of which is the spring constant. Even if you start with velocity zero, a spring will spring at a speed determined by the spring constant. So what's happening is that you're going from 0.0 to 1.0 with a pretty tight critically-damped string.
Also, because you're using a NetworkImage, you don't see anything because the image takes longer to load than the animation takes to run.
If you replace LogoWidget with FlutterLogo, you'll see what's happening better.
If you want it to go slower, you can use animateWith instead of fling to pass it a specific SpringSimulation with your own custom parameters.
The existence of fling is a bit of a historical accident. It's designed to be used primarily with AnimationControllers with a lowerBound and upperBound given in pixels, rather than over the 0.0...1.0 default range.