I have a column like this:
Column(children: [
product.videos![product.videoIndex].videoUrl != null &&
product.videos![product.videoIndex].videoUrl != ""
? VideoPlayerWidget(
videoAddress: product.videos![product.videoIndex].videoUrl)
: Image.asset('assets/images/video-placeholder.jpg'),
]),
And I get this error:
_CastError (Null check operator used on a null value)
I know that the variables may be null and that's the reason I put them within a null check if statement, but I don't know why do I get the null check error and how can I pass that?
The Flutter forced me to put !
after null variables, then it gives me error because of that!
It is because product.videos
is null
, though you handled the condition if it is null
, but you are assuring dart
compiler that product.videos
can nver be null
, by using !
opeartor. Change !
to ?
meaning , it may be subjected to being null
, and precautions would be taken if it is null
.
Change your code by replacing !
to ?
:
product.videos?[product.videoIndex].videoUrl != null &&
product.videos?[product.videoIndex].videoUrl != ""
? VideoPlayerWidget(
videoAddress: product.videos![product.videoIndex].videoUrl)
: Image.asset('assets/images/video-placeholder.jpg'),
Edit for the comment:
Could you explain what is the difference between ! and ?. and ? and ??
!
- Saying the compiler value can never be null
.var val1 = val2! // val2 can never be null
?
- Saying the compiler value can be null
.String? val; // Here val can be potentially null
?.
- Access only if not null.object?.prop1; // Here prop1 is accessed only if object is not null
??
- Alternate value if the value is nullvar val1 = val2 ?? val3; // if val2 is null assign va13 to val1