Null check operator used on a null value- futter chat

Issue

I’m creating a chat app with sending voice message. now I’m getting this error in my code. appreciate your help on this. I HAVE INSERTED FOLLOWING CODE ANS THEN ERROR APPEARS. Cant find a exact file error occurring.

Null check operator used on a null value 

error image

class SoundRecorder {

  FlutterSoundRecorder? _audioRecorder;
  bool _isRecorderInitialised = false;

  bool get isRecording => _audioRecorder!.isRecording;

  Future init() async {
    _audioRecorder = FlutterSoundRecorder();
    await _audioRecorder?.openAudioSession(); //start recording


    //asking permisson
    final status = await Permission.microphone.request();
    if (status != PermissionStatus.granted) {
      throw RecordingPermissionException("Microphone permission");
    }
    await _audioRecorder!.openAudioSession();
    _isRecorderInitialised = true;
  }


  void dispose() {
    if (!_isRecorderInitialised) return;
    _audioRecorder!.closeAudioSession();
    _audioRecorder = null;
    _isRecorderInitialised = false;
  }

  Future _record() async {
    if (!_isRecorderInitialised) return;
    await _audioRecorder!.startRecorder(toFile: pathToSaveAudio);
  }

  Future _stop() async {
    if (!_isRecorderInitialised) return;
    await _audioRecorder!.stopRecorder();
  }

  Future toggleRecording() async {
    if (_audioRecorder!.isStopped) {
      await _record();
    } else {
      await _stop();
    }
  }
}

Solution

Looks like at some point you use the ! operator to assert that _audioRecorder isn’t null but it actually is. From the stack, I think this would be from the isRecording getter.

A simple fix to this would be to make the getter bool get isRecording => _audioRecorder?.isRecording ?? false, since if _audioRecorder is null, then you can’t be recording, right?

Answered By – user6118986

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *