flutterif-statementcastingnullablenull-safety

Why do I get this error: _CastError (Null check operator used on a null value)


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!


Solution

  • 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