2

I see people usually initialize the controller like this, initializing it in initState() method.

 late VideoPlayerController _videoPlayerController;

 @override
 void initState() {
   super.initState();
   _videoPlayerController = VideoPlayerController.network(
        "https://assets.mixkit.co/videos/preview/mixkit-spinning-around-the-earth-29351-large.mp4");
 }

but then I realize if I just put the controller like this without initState()just put the controller after the variables with late in before the variables, everything works fine. So what is the difference?

class _VideoDetailScreenState extends State<VideoDetailScreen>{

  late VideoPlayerController _videoPlayerController = VideoPlayerController.network(
              "https://assets.mixkit.co/videos/preview/mixkit-spinning-around-the-earth-29351-large.mp4");
PrzemekTom
  • 1,328
  • 1
  • 13
  • 34
CCP
  • 886
  • 1
  • 10
  • 30
  • This is a direct duplicate of [why we should initialize the variables in InitState and not initialize them directly with declaration](https://stackoverflow.com/q/74416861/). Also see [why we should initialize the variables in InitState and not initialize them directly with declaration](https://stackoverflow.com/q/52066976/). – jamesdlin Nov 16 '22 at 02:58

1 Answers1

2

As from the official documentation:

The framework calls initState. Subclasses of State should override initState to perform one-time initialization that depends on the BuildContext or the widget, which are available as the context and widget properties, respectively, when the initState method is called.

Gwhyyy
  • 7,554
  • 3
  • 8
  • 35
  • so what is the difference ? because it both works fine – CCP Nov 16 '22 at 02:46
  • it's a method of the lifecycle of the StatefulWidget, it will be executed just once, you should consider using it Because when the widget rebuilds, it could initiate again with the fixed value you give, it's state must change not getting the initial value – Gwhyyy Nov 16 '22 at 03:06
  • the big difference will be shown when using as example an AnimatedList widget – Gwhyyy Nov 16 '22 at 03:07