lele
lele

Reputation: 103

Can I have two actions in one IconButton?

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?

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

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

Upvotes: 0

Views: 531

Answers (1)

Nirmal Code
Nirmal Code

Reputation: 4058

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),
),

Upvotes: 1

Related Questions