Home > Mobile >  _CastError (Null check operator used on a null value) while developing dictionary app
_CastError (Null check operator used on a null value) while developing dictionary app

Time:09-27

I am developing a dictionary app..And I am getting this error while clicking the search icon.

_CastError (Null check operator used on a null value)

This is a part of my code

Container(
           child: ListTile(
           title: Text(data.word!),
           subtitle: Text(
           data.phonetics![index].text!),
           trailing: IconButton(
             onPressed: () {
               final path = data
                .phonetics![index]
                .audio;
                  playAudio("https:$path");
                  },
                  icon: const Icon(
                  Icons.audiotrack)),
                  ),
                ),

And this is the code the exception is pointing to

data.phonetics![index].text!

I am using flutter 2.5.3 Help me solve this error..Thanks in advance

CodePudding user response:

Try accepting null on text case and check null before using !

Container(
  child: ListTile(
    title: Text("${data.word}"),
    subtitle: Text("${data.phonetics?[index].text}"),
    trailing: IconButton(
        onPressed: () {
          final path = data.phonetics?[index].audio;
          if (path != null) {
            playAudio("https:$path");
          }
        },
        icon: const Icon(Icons.audiotrack)),
  ),
),

CodePudding user response:

Error Explanation: Bang operator(!) means that in flutter, when you use this operator, you are completely sure that variable is not going to be null in any case.

As you had written data.phonetics![index].text!, this is the where error is generating. Now error is saying that either phonetics or text is null.

There are two ways to resolve this peacefully -

  1. Use if conditional to confirm that variable is not null
  2. Use null-aware or if-null operator ?? like this
${data.phonetics?[index].text ?? ''}
  • Related