How do I animate a container when the page is initializing; - flutter

class _MaintenanceState extends State<Maintenance> {
Function below is supposed to initialise the animation
#override
void initState() {
super.initState();
_animate();
}
var loginWidth = 0.0;
Curve _curve = Curves.fastOutSlowIn;
_animate() {
setState(() {
loginWidth == 0.0 ? loginWidth = 130 : loginWidth = 0.0;
});
}
I tried placing the width of the animated container in the
initState but it still doesn't animate.
AnimatedContainer(
duration: Duration(seconds: 1),
width: loginWidth,
height: 60.0,
decoration: BoxDecoration(
color: Colors.green[600],
borderRadius: BorderRadius.circular(20.0),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Text("Add \nProject"),
)),
Spacer(),
Image(
image: AssetImage(
"assets/images/add_icon.png",
),
),
],
),
),
),
Any suggestions would be much appreciated

There are several things you have to consider to animate.
use AnimationController to track the currentstate of animation, to set the duration till which you want to animate and other several properties if you want to add in animation.
if you are using animation you have to use SingleTickerProviderStateMixin or MultiTickerProviderStateMixin mixin in your class.
I am sharing my GitHub project link in which I used a simple animation you can refer to it.

Related

Flutter - Detect when finger enter in a container

In my interface I have a row of containers like this
.
The idea is that when I pass my finger on these containers, the one under my finger gets bigger (and other changes but that's not the point).
I know how to use GestureDetector and get it bigger when I tap on the container with "onTap". But if you keep your finger down and drag it to another container nothing change. Idealy I'd like to be able to detect when the user pass his finger hover a container while touching the screen.
Appreciate if someone can advise. Thank you in advance!
You can use onVerticalDragUpdate on GestureDetector.
class DraUILien extends StatefulWidget {
const DraUILien({super.key});
#override
State<DraUILien> createState() => _DraUILienState();
}
class _DraUILienState extends State<DraUILien> {
int? activeIndex;
final double containerWidth = 30;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: GestureDetector(
onVerticalDragUpdate: (details) {
activeIndex =
details.localPosition.dx ~/ (containerWidth + 16); //16 padding
setState(() {});
},
child: SizedBox(
height: 200,
child: Row(
children: List.generate(
10,
(index) => Padding(
padding: const EdgeInsets.all(8.0),
child: AnimatedContainer(
duration: Duration(milliseconds: 300),
color: index == activeIndex ? Colors.blue : Colors.grey,
width: containerWidth,
height: index == activeIndex ? 200 : 100,
),
),
),
),
),
)),
);
}
}
Play with the logic for more customization. If you need onTap functionality try including onPanDown

Why isn't my Flutter animated checkmark working?

I'm trying to replicate the following animation from dribble.com:
I've gotten the ScaleTransition to work but the SizeTransition does not. What am I doing wrong or what don't I understand?
When I only swap out the SizeTransition with a FadeTransition (and keep the same controllers & animations), the animations both run. When I move the Center widget from being a child of the SizeTransition to the parent the animation runs.
However it is not properly centered.
import 'package:flutter/material.dart';
class AnimatedCheck extends StatefulWidget {
#override
_AnimatedCheckState createState() => _AnimatedCheckState();
}
class _AnimatedCheckState extends State<AnimatedCheck> with TickerProviderStateMixin {
late AnimationController scaleController = AnimationController(duration: const Duration(milliseconds: 800), vsync: this);
late Animation<double> scaleAnimation = CurvedAnimation(parent: scaleController, curve: Curves.elasticOut);
late AnimationController checkController = AnimationController(duration: const Duration(milliseconds: 400), vsync: this);
late Animation<double> checkAnimation = CurvedAnimation(parent: checkController, curve: Curves.linear);
#override
void initState() {
super.initState();
scaleController.addStatusListener((status) {
if (status == AnimationStatus.completed) {
checkController.forward();
}
});
scaleController.forward();
}
#override
void dispose() {
scaleController.dispose();
checkController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
double circleSize = 140;
double iconSize = 108;
return ScaleTransition(
scale: scaleAnimation,
child: Container(
height: circleSize,
width: circleSize,
decoration: BoxDecoration(
color: Colors.green,
shape: BoxShape.circle,
),
child: SizeTransition(
sizeFactor: checkAnimation,
axis: Axis.horizontal,
axisAlignment: -1,
child: Center(
child: Icon(Icons.check, color: Colors.white, size: iconSize)
)
),
),
);
}
}
When you move the Center to the outside, it doesn't center the children of it's children, just puts it's child in the center of the area it occupies. Try setting the Container alignment using alignment: Alignment.center, inside of the Container. Please let me know if it doesn't work and I'll replicate the code to figure out the problem is.
Edit: This is because there is space around the visual check you see, the SizeTransition doesn't know this so it animates from the edge of the Icon which causes the visual bug you see. I'd recommend you use a tool like Rive (rive.app) to accomplish what you want, alternatively, you can use another animation or use some clunky workaround like animating the position while the size transition occurs so that it appears to be centered.
Hi if this is an issue for you, I figured out how both animations will be triggerd.
See code below.
Stack(
children: [
Center(
child: ScaleTransition(
scale: scaleAnimation,
child: Container(
height: circleSize,
width: circleSize,
decoration: BoxDecoration(
color: kApprovedColor,
shape: BoxShape.circle,
),
),
),
),
SizeTransition(
sizeFactor: checkAnimation,
axis: Axis.horizontal,
axisAlignment: -1,
child: Center(
child: Icon(Icons.check, color: Colors.white, size: iconSize),
),
),
],
),
Flutter's documentation has an explanation:
Like most widgets, SizeTransition will conform to the constraints it
is given, so be sure to put it in a context where it can change size.
For instance, if you place it into a Container with a fixed size, then
the SizeTransition will not be able to change size, and will appear to
do nothing.
Thank you. Now I know what I'm doing wrong.

Flutter "Catch up" animation on drag

I'm currently building a flutter app where a user can drag a circle around the screen. I use a Listener widget to get the current pointer position, then use a transform widget to position it accordingly.
class _DraggingExample extends State<VelocityAnimations>{
var offset = Offset(0, 0);
#override
Widget build(BuildContext context) {
return Scaffold(
// I get pointer-events here.
body: Listener(
onPointerMove: (e) {
setState(() {
// - 50 to center the container
offset = e.localPosition - Offset(50, 50);
});
},
behavior: HitTestBehavior.opaque,
child: SizedBox.expand(
child: Stack(
children: [
Center(child: Text('Hello, World!')),
// I transform the container here.
Transform.translate(
offset: offset,
child: Container(
width: 100,
height: 100,
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(50),
),
),
)
],
),
),
),
);
}
}
It works perfectly. But it's very bland. It would be much nicer if when I move my pointer/finger, the container gradually catches up to the finger. The effect I'm looking for can be seen in this codepen. Here, the black circle gradually catches up with the mouse as you move it along.
I've tried using a Physics Simulation and plain animations, but I can't figure out how to do it.
You can try to use AnimatedPositioned which animates its position implicitly.
The animation can be configured with duration and Curves as you want.
AnimatedPositioned(
left: offset.dx,
top: offset.dy,
curve: Curves.easeOutCirc,
duration: Duration(milliseconds: 400),
child: Container(
// ...
),
),

Flutter: How to make a custom animated Drop Down Menu?

I'm trying to make a custom drop-down menu in Flutter that is just a simple button that on tap shows a scrollable row of products. I've attached some images that better show what I'm referring to. I tried to use an IconButton and an AnimatedContainer but I can't seem to get it working. I was hoping someone would have a better idea on how to do something like this.
Here is my code so far by the way:
class ModelsDropdown extends StatefulWidget {
final List<Phone> phones;
ModelsDropdown({#required this.phones});
#override
_ModelsDropdownState createState() => _ModelsDropdownState();
}
class _ModelsDropdownState extends State<ModelsDropdown> {
bool _droppedDown;
#override
void initState() {
_droppedDown = false;
super.initState();
}
#override
Widget build(BuildContext context) {
return AnimatedContainer(
duration: Duration(milliseconds: 300),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(100.0),
border: Border.all(width: 2.0)
),
width: 32.0,
height: 32.0,
child: Column(
children: [
IconButton(
padding: const EdgeInsets.only(right: 0.0),
icon: Icon(
_droppedDown ? Icons.expand_more : Icons.expand_less
),
color: Colors.black,
onPressed: () {
setState(() {
_droppedDown = !_droppedDown;
});
}
),
_droppedDown ?
Container(
width: MediaQuery.of(context).size.width,
height: 300.0,
color: Colors.orangeAccent,
) :
SizedBox.shrink()
],
),
);
}
}
With the container at the bottom, it doesn't even work. I get an overflow error. Any help is very much appreciated. Thanks a lot, everyone.
I Think you should Change The Below Container with an AnimatedCrossFade.
Animated Cross Fade Has Two Child First and Second ...
https://api.flutter.dev/flutter/widgets/AnimatedCrossFade-class.html
Dont set Height for Your Child ... its Works Perfectly...
AnimatedCrossFade(
duration: const Duration(seconds: 3),
firstChild: Container(), // When you don't want to show menu..
secondChild: menu,
crossFadeState: _first ? CrossFadeState.showFirst : CrossFadeState.showSecond,
)
with this method you don't need Animated Container at top ... remove that.(return Column)...
with Animated cross Fade You don't need to Know The Height of widget and its for works dynamic Heights
-------------- if You Want to use Your Code and Use Fixed Height ----------------
width: _droppedDown ? YourWidth : 32.0,
height: _droppedDown ? 300 : 32.0,

Flutter AnimatedSwitcher jumps between children

I am trying to implement some custom design in an expasion panel list. Therefore, I wanted to create some kind of animation that animates smoothly from one view (e.g. header) to another view (e.g. full info of the tile) that has other dimensions (obviously, full info will be higher than just the header). This is quite easy to implement with an AnimatedContainer. However, I would need the height of the header widget and the full info widget in order to animate between these two heigths. As these values differ between tiles (other info -> maybe other height) and tracking height via global keys is not my preferred solution, I decided to use the much simpler AnimatedSwitcher instead. However, the behavior of my AnimatedSwitcher is quite strange. At first, the other tiles in the ListView (in my example the button) move down instantly and subsequently the tile expands. Has anyone an idea of how I could implement some code in order to achieve the same animation that I would get from AnimatedContainer(button/other tiles moving down simultaniously with the tile expanding)? Thanks in advance for any advice. Here is my code:
class MyPage extends State {
List _items;
int pos;
#override
void initState() {
pos = 0;
_items = [
Container(
color: Colors.white,
width: 30,
key: UniqueKey(),
child: Column(
children: <Widget>[Text('1'), Text('2')], //example that should visualise different heights
),
),
Container(
width: 30,
color: Colors.white,
key: UniqueKey(),
child: Column(
children: <Widget>[Text('1'), Text('2'), Text('44534'), Text('534534')],
),
)
];
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
padding: EdgeInsets.only(top: 100),
children: <Widget>[
AnimatedSwitcher(
duration: Duration(seconds: 1),
transitionBuilder: (child, animation) => ScaleTransition(
child: child,
scale: animation,
),
child: _items[pos],
),
RaisedButton(
child: Text('change'),
onPressed: pos == 0
? () {
setState(() => pos = 1);
}
: () {
setState(() => pos = 0);
})
],
),
);
}
}
The solution was quite simple. Just found out that there exists an AnimatedSize Widget that finds out the size of its children automatically.
I stumbled on this post and since I had a similar problem I decided to create a tutorial here on how to mix AnimatedSwitcher and AnimatedSize to solve this issue. Animations do not happen at the same time but the advantage is that you have full control on the animation provided to the switcher.
I ended up doing this in the end (please note that I'm using BlocBuilder and that AnimatedSizeWidget is a basic implementation of AnimatedSize:
AnimatedSizeWidget(
duration: const Duration(milliseconds: 250),
child: BlocBuilder<SwapCubit, bool>(
builder: (context, state) {
return AnimatedSwitcher(
duration: const Duration(milliseconds: 1000),
child: state
? Icon(Icons.face, size: 80, key: Key("80"))
: Icon(Icons.face, size: 160, key: Key("160")),
);
},
),
),
var isWidgetA = true;
final Widget widgetA = Container(
key: const ValueKey(1),
color: Colors.red,
width: 100,
height: 100,
);
final Widget widgetB = Container(
key: const ValueKey(2),
color: Colors.green,
width: 50,
height: 50,
);
...
AnimatedSwitcher(
duration: const Duration(milliseconds: 500),
transitionBuilder: (Widget child, Animation<double> animation) {
return SizeTransition(
sizeFactor: animation,
child: ScaleTransition(
child: child,
scale: animation,
alignment: Alignment.center,
),
);
},
child: isWidgetA
? widgetA
: widgetB,
),