1

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!

best_of_man
  • 643
  • 2
  • 15
  • There's some place that you put "!" after what ends up being a null. Find that. Try writing your code entirely without !, and just do the null checks in your code. – Randal Schwartz Mar 09 '23 at 05:39

2 Answers2

1

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 ??

  1. ! - Saying the compiler value can never be null.
var val1 = val2! // val2 can never be null
  1. ? - Saying the compiler value can be null.
String? val; // Here val can be potentially null
  1. ?. - Access only if not null.
object?.prop1; // Here prop1 is accessed only if object is not null
  1. ?? - Alternate value if the value is null
var val1 = val2 ?? val3; // if val2 is null assign va13 to val1
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
0

Looks your product.videos itself null. So change ! to ? in if condition.

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'),
  ]),
Alex Sunder Singh
  • 2,378
  • 1
  • 7
  • 17
  • Could you explain what is the difference between `!` and `?.` and `?` and `??` – best_of_man Mar 09 '23 at 05:49
  • 1
    `!` means that we are sure that will not be null, `?.` means that variable may be null and proceed with null value further, `?` means that result may null. and `??` means that if result is null the use the default value which we given following that. – Alex Sunder Singh Mar 09 '23 at 05:54