Home > database >  the difference between initialize controller in initState and without
the difference between initialize controller in initState and without

Time:11-16

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

CodePudding user response:

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.

  • Related