so I found myself doing the following without knowing actually why we should or should not do it.
let's say we have StatefulWidget
:
class ExampleWidget extends StatefulWidget {
const ExampleWidget({super.key});
@override
State<ExampleWidget> createState() => ExampleStateWidget();
}
class ExampleStateWidget extends State<ExampleWidget> with TickerProviderStateMixin {
late AnimationController _controller;
@override
void initState() {
_controller = AnimationController(vsync: this, duration: Duration(microseconds: 300));
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container();
}
}
why we should declare the the _controller
inside the initState()
, and not initialize it directly like this:
class ExampleWidget extends StatefulWidget {
const ExampleWidget({super.key});
@override
State<ExampleWidget> createState() => ExampleStateWidget();
}
class ExampleStateWidget extends State<ExampleWidget> with TickerProviderStateMixin {
AnimationController _controller = AnimationController(vsync: this, duration: Duration(microseconds: 300));
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container();
}
}
what's the big difference between the two, I'm using the initState()
but not knowing why exactly.