How to Listen Volume Up/Down Button Press in Flutter

In this app example code, we are going to show you how to detect or listen Volume Hardware button press and identify which button is pressed, either volume up or down button in Flutter App. 

First, add perfect_volume_control Flutter package in your project by adding the following lines in pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  perfect_volume_control: ^1.0.5

perfect_volume_control package will facilitate you to get current volume, set volume, and listen to volume change. We will use its volume change listener to detect up or down volume button press.

Previously, We have posted a guide on How to Increase/Decrease Volume in the Flutter app, you can look into it if you want to change the volume. 

import 'package:perfect_volume_control/perfect_volume_control.dart';
PerfectVolumeControl.stream.listen((volume) {  
      //volume button is pressed, 
       // this listener will be triggeret 3 times at one button press
});

This listener will be triggered three times for system volume, music volume, and alarm volume. We have done a few tweaks to identify which button is pressed, either the volume or volume down button. Be careful, on our code, the manual increase from volume UI will be taken as a volume button press.

Look at the full Flutter App example code below, we have detected the volume button detection when the volume is changed.

import 'package:flutter/material.dart';
import 'package:perfect_volume_control/perfect_volume_control.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
     return MaterialApp(
         home: Home()
      );
  }
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  double currentvol = 0.5;
  String buttontype = "none";

  @override
  void initState() {
    Future.delayed(Duration.zero,() async {
        currentvol = await PerfectVolumeControl.getVolume();
        //get current volume

        setState(() {
            //refresh UI
        });
    });

    PerfectVolumeControl.stream.listen((volume) {  
      //volume button is pressed, 
      // this listener will be triggeret 3 times at one button press
        
       if(volume != currentvol){ //only execute button type check once time
           if(volume > currentvol){ //if new volume is greater, then it up button
              buttontype = "up";
           }else{ //else it is down button
              buttontype = "down";
           }
       }

       setState(() {
          currentvol = volume;
       });
    });
    super.initState();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
         appBar: AppBar(
            title: Text("Listen Volume Button Press"),
            backgroundColor: Colors.redAccent,
         ),

         body: Container(
                padding: EdgeInsets.all(20),
                child: Column( 
                  children: [
                     
                     Text("Current Volumen: $currentvol"),

                     Divider(),

                     buttontype == "none"?
                          Text("No button is pressed yet."):
                          Text(buttontype == "up"? "Volume Up Button is Pressed":
                                "Volume Down Button is Pressed", 
                                    style: TextStyle(fontSize: 20),)
                          
                  ],
                ) 
            )   
          
    );
  } 
}

Here we have used the Volume change listener from the package and recorded the last volume and the new volume, and we have compared these two volume values to get which button is pressed. If the new volume is greater, then it's obviously the UP button, if the new volume is less, then it's a down button.

When the Volume Up button is Pressed.

When the Volume Down button is pressed.

In this way, you can listen to Hardware Volume Button pressed, and identify which button is pressed, either Volume Up or Volume down in Flutter App.

No any Comments on this Article


Please Wait...