skip to Main Content

I am looking to play video in a screen using VideoPlayer. The video needs to be fetched from an API. Here is how my initState looks:

@override
  void initState() {
    super.initState();
    getCandidateProfileVideo();
  }

I have the following two late variables in my stateful widget class and a global variable:

late VideoPlayerController _controller;
late Future<void> _initializeVideoPlayerFuture;
String videoUrl = "";

getCandidateProfileVideo() is implemented as follows:

getCandidateProfileVideo() async {
  // await call to get video from REST API, and store the response in the variable videoUrl

  _controller = VideoPlayerController.network(
        videoUrl,
      );
      _initializeVideoPlayerFuture = _controller.initialize();
      _controller.setLooping(true);
      _controller.setVolume(1.0);
}

Problem

When I try to load the screen, I am getting the following issue: LateInitializationError: Field ‘_initializeVideoPlayerFuture@75490850’ has not been initialized.

Request

What is wrong in my code that is causing this issue and how to resolve it?

2

Answers


  1. You should not use late keyword when you are initializing an object in asynchronous function. You are initializing the video player object in getCandidateProfileView() which is asynchronous. By the time, the first frame is rendered by flutter, the video_player variable won’t be initialized. That’s why it throws late initialization error. To solve this, you can make your video_player variable of Nullable type.

    VideoPlayerController? _controller;
    Future<void>? _initializeVideoPlayerFuture;
    String videoUrl = "";
    

    and wherever you use your VideoPlayerController _controller make sure to use ?. or "!." nullable operators.

    For ex:

    _controller!.play() // you can use any function you want
    

    For more information you can read about dart’s sound null safety.

    Login or Signup to reply.
  2. Adding to Just a Person’s answer:
    If you want to keep using your async function you can consider using FutureBuilder widget which will call for your async function you put in it’s future property and update snapshot when function returns some value
    Example:

    FutureBuilder(
      future: yourAsyncFunction(), 
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return snapshot.data;
        }
        return CircularProgressIndicator();
      }
    )
    

    For more information about FutureBuilder see official documentation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search