I have an animated container, which starts at width and height 0, and then gets changed to 300 each, after a setState, which I call at initState. But It doesn't seem to animate. Here's the code-
import 'package:flutter/material.dart';
class ChooseCardWidget extends StatefulWidget {
const ChooseCardWidget({Key? key}) : super(key: key);
@override
State<ChooseCardWidget> createState() => ChooseCardWidgetState();
}
class ChooseCardWidgetState extends State<ChooseCardWidget> {
double height = 0;
double width = 0;
final double roundedValue = 20;
@override
void initState() {
super.initState();
startAnimation();
}
void startAnimation() {
setState(() {
height = 300;
width = 300;
});
}
@override
Widget build(BuildContext context) {
return AnimatedContainer(
duration: Duration(seconds: 10),
height: height,
width: width,
decoration: ShapeDecoration(
shadows: const [
BoxShadow(color: Colors.grey, blurRadius: 20, spreadRadius: 5)
],
color: Colors.purple,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(roundedValue),
),
),
);
}
}
It just starts off as being 300 in width and height. How do I fix this? Thanks!
CodePudding user response:
Try this
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: YourClass(),
),
);
}
}
class YourClass extends StatefulWidget {
@override
_YourClassState createState() => _YourClassState();
}
class _YourClassState extends State<YourClass> {
double loginWidth = 40.0;
@override
Widget build(BuildContext context) {
return Center(
child: PageView(
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
RaisedButton (
child: Text('Animate!'),
onPressed: () {
setState(() {
loginWidth = 250.0;
});
},
),
AnimatedContainer (
duration: Duration (seconds: 1),
width: loginWidth,
height: 40,
color: Colors.red,
),
],
)
],
),
);
}
}
This will perfectly work
CodePudding user response:
You are calling startAnimation()
directly inside initState
, means it will get height=300
and width=300
on 1st build.
You can use addPostFrameCallback
to animate this, it will set height and width to 300 after 1st frame is build.
@override
void initState() {
super.initState();
WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
startAnimation();
});
}
Also, you can use
Future.delayed(Duration.zero, () {
startAnimation();
});