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;
Related
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!
Basically I have a widget and a floatingActionButton, i want to make that widget move whenever i press the button, i managed to make it teleport to a random location, but i want it animated.
I would like my widget to animate going from his current location to a new location when pressing the button.
Also the randomNumber() function is a function that picks a random number between a minimum and a maximum.
randomNumber(min,max);
class _homePageState extends State<homePage> with SingleTickerProviderStateMixin{
late final AnimationController _animationController = AnimationController(
vsync: this,
duration: Duration(seconds: 1),
)..forward();
#override
void initState() {
super.initState();
}
double beginX = randomNumber(-1, 1);
double beginY = randomNumber(-1, 1);
double endX = randomNumber(-1, 1);
double endY = randomNumber(-1, 1);
#override
void dispose() {
_animationController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
late final Animation<Offset> _animation = Tween<Offset>(
begin: Offset(beginX, beginY),
end: Offset(endX, endY),
).animate(_animationController);
return Scaffold(
body: Center(
child: SlideTransition(
child: Container(
height: 100,
width: 100,
color: Colors.red,
),
position: _animation,
)
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
beginX = endX; // here i wanted the widget's old end position to become it's new begin position
beginY = endY;
endX = randomNumber(-1, 1);
endY = randomNumber(-1, 1);
_animationController..forward();
});
},
),
);
}
}
you could set up your own animations and do it that way, nut it would be a lot simpeler to just use a Stack and an AnimatedPositioned then you'd just have to update some random position values and rebuild the widget.
the docs have all the info
I have a container upon which I'm detecting gestures so that I can scroll through an image that I'm creating with custom painter, like so
class CustomScroller extends StatefulWidget {
#override
_CustomScrollerState createState() => _CustomScrollerState();
}
class _CustomScrollerState extends State<CustomScroller>
with SingleTickerProviderStateMixin {
AnimationController _controller;
double dx = 0;
Offset velocity = Offset(0, 0);
double currentLocation = 0;
#override
void initState() {
_controller =
AnimationController(vsync: this, duration: Duration(seconds: 1));
super.initState();
}
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
double width = MediaQuery.of(context).size.width;
return GestureDetector(
onHorizontalDragUpdate: (DragUpdateDetails dragUpdate) {
dx = dragUpdate.delta.dx;
currentLocation =
currentLocation + (dx * 10000) / (width * _absoluteRatio);
setState(() {});
},
onHorizontalDragEnd: (DragEndDetails dragUpdate) {
velocity = dragUpdate.velocity.pixelsPerSecond;
//_runAnimation(velocity, size);
},
child: Container(
width: width,
height: 50,
child: Stack(
children: <Widget>[
CustomPaint(
painter: NewScrollerPainter(1, true, currentLocation),
size: Size.fromWidth(width)),
],
),
),
);
}
}
I've written some code so that on a drag the pointer's dx value is used to calculate currentLocation, which is used by the customPainter 'NewScrollerPaint' to determine what area it needs to paint.
I essentially want a fling animation, whereby releasing from a drag with a velocity, the custom painter 'NewScrollerPainter' will continue to scroll until it is out of momentum. I believe this requires the value of currentLocation to be calculated from the velocity, and then returned for NewScrollerPainter to be updated, but I've spent a few hours looking through Flutter's animation docs and playing around with open source code but I'm still not sure how I would go about doing this. Could anyone shed some light onto this issue?
class CustomScroller extends StatefulWidget {
#override
_CustomScrollerState createState() => _CustomScrollerState();
}
class _CustomScrollerState extends State<CustomScroller>
with SingleTickerProviderStateMixin {
AnimationController _controller;
#override
void initState() {
_controller =
AnimationController(vsync: this, duration: Duration(seconds: 1));
super.initState();
}
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
return GestureDetector(
onHorizontalDragUpdate: (DragUpdateDetails dragUpdate) {
_controller.value += dragUpdate.primaryDelta / width;
},
onHorizontalDragEnd: (DragEndDetails dragEnd) {
final double flingVelocity = dragEnd.primaryVelocity / width;
const spring = SpringDescription(
mass: 30,
stiffness: 1,
damping: 1,
);
final simulation = SpringSimulation(spring, _controller.value, 0, flingVelocity); //if you want to use a spring simulation returning to the origin
final friction = FrictionSimulation(1.5, _controller.value, -(flingVelocity.abs())); //if you want to use a friction simulation returning to the origin
//_controller.animateWith(friction);
//_controller.animateWith(simulation);
_controller.fling(velocity: -(flingVelocity.abs())); //a regular fling based on the velocity you were dragging your widget
},
child: Stack(
children: [
SlideTransition(
position: Tween<Offset>(begin: Offset.zero, end: const Offset(1, 0))
.animate(_controller),
child: Align(
alignment: Alignment.centerLeft,
child: CustomPaint(
painter: NewScrollerPainter(),
size: Size.fromWidth(width),
child: SizedBox(width: width, height: 50)
),
)
)
]
)
);
}
}
I see you are trying to move in the X axis only (you're usign onHorizontalDragUpdate and End) so you can use the values primaryDelta and primaryVelocity, that already gives you the calculations of the position and velocity in the primary axis (horizontal in this case).
In onHorizontalDragUpdate you mve the controller value adding itself the position of the dragging (positive you're moving away of the place you first tapped, negative you're moving back, 0 you haven't moved or dragged).
In onHorizontalDragEnd you calculate the velocity with primaryVelocity and the same logic (positive you're moving away, negative you're returning, 0 there is no velocity, bascially you stopped moving before your drag ended). You can use simulations or just the fling method and pass the velocity you have (positive you want to end the animation, negative you velocity you want to dismiss it and 0 you don't want to move).
At the end the only thing you need to do is wrap your widget you cant to move with the controller in a SlideTransition with a Tween animated by the controller beggining at zero and end where you want to end it (in my case I want to move it from left to right)
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,
))
],
);
}
}
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.