Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between initializing controller in initState and a field

Tags:

flutter

dart

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");
like image 404
CCP Avatar asked Sep 20 '25 13:09

CCP


1 Answers

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.

like image 145
Gwhyyy Avatar answered Sep 22 '25 04:09

Gwhyyy