Search code examples
flutterdartnullabledart-null-safety

Dart compare int null safety issue : operator can't be unconditionally invoked because the receiver can be 'null'


I have an object of class State it contains a nullable list called playList and a nullable player object.

when I try to write this if statement

if(state.playList?.length > 0 && state.player?.currentIndex? >0)

I got this error

The operator '>' can't be unconditionally invoked because the receiver can be 'null'

I solved this issue by writing two nested if statement

if(state.playList != null && state.player?.currentIndex !=null)
{
    if(state.playList!.length > 0 && state.player!.currentIndex! >0 )
    {
        //some code
    }
}

How to rewrite the above code in better way?


Solution

  • One way would be

    if((state.playList?.length ?? 0) > 0 
     && (state.player?.currentIndex ?? 0) > 0)
    

    But if you want to work with those values later on, you need to put them in local variables, otherwise you will have to add countless ! as you have experienced in your second example.

    As an example of how to "get rid" of the nullability later on by using local variables that will be "promoted" to their non-nullable type after the check:

    final playList = state.playList;
    final currentIndex = state.player?.currentIndex;
    
    if(playList != null && currentIndex != null)
    {
        if(playList.length > 0 && currentIndex > 0)
        {
            //some code
        }
    }