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
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 throwslate initialization error
. To solve this, you can make your video_player variable of Nullable type.and wherever you use your VideoPlayerController
_controller
make sure to use?.
or "!." nullable operators.For ex:
For more information you can read about dart’s sound null safety.
Adding to Just a Person’s answer:
If you want to keep using your
async
function you can consider usingFutureBuilder
widget which will call for yourasync
function you put in it’sfuture
property and updatesnapshot
when function returns some valueExample:
For more information about
FutureBuilder
see official documentation