CCP
CCP

Reputation: 1236

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

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");

Upvotes: 4

Views: 892

Answers (1)

Gwhyyy
Gwhyyy

Reputation: 9186

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.

Upvotes: 2

Related Questions