Ad

Can I Have Two Actions In One IconButton?

- 1 answer

I want the speech to text function to start when one microphone icon is pressed and the noise meter function to start at the same time.

Currently, the icon for speech to text and the icon for noise meter are separated. Is there any way to combine these into one icon?

  • noise_meter
IconButton(
    onPressed: () {
        setState(() {
            _isRecording = !_isRecording;

            if (_isRecording) {
                NoiseMeterHelper().start(
                    onData: onData,
                    onError: onError,
                );
            } else {
                NoiseMeterHelper().stop();
            }
        });
    },
    icon: _isRecording ? Icon(Icons.mic) : Icon(Icons.mic),
),
  • speech_to_text
IconButton(
    onPressed: recognizing ? stopRecording : streamingRecognize,
    icon: recognizing
        ? Icon(Icons.mic, color: Colors.red, size: 30)
        : Icon(Icons.mic, color: Colors.blue,size: 30)
),
Ad

Answer

You can run any number of functions in one onPressed function.

Also, you don't have to use setState() to run functions. setState is used to update class variables and rebuild the UI with those changes.

if you are displaying _isRecording or using it to update any UI, wrap it in a setState. If not, no need to use setState. Also, note that incorrect use of setState will lead to multiple unnecessary UI rebuilds.

Try this,

IconButton(
    onPressed: () {
        setState(() {
            _isRecording = !_isRecording;
        });

        if (_isRecording) {
            NoiseMeterHelper().start(
                onData: onData,
                onError: onError,
            );
        } else {
            NoiseMeterHelper().stop();
        }
        recognizing ? stopRecording() : streamingRecognize();
    },
    icon: _isRecording ? Icon(Icons.mic) : Icon(Icons.mic),
),
Ad
source: stackoverflow.com
Ad