Flutter – Wakelock
The Wakelock package in Flutter is used to keep the screen awake while using it. It can be adjusted according to the requirements (how long to stay awake). These are very simple things that enhance the quality of the app and increases the user-friendliness of the same.
In this article, we will explore the process of keeping the mobile screen awake while not using the application. To do, so we will build a simple application with two buttons namely:
- enable wakelock: It will prevent the phone screen to lock itself irrespective of how long it stays that way.
- disable wakelock: It will disable the wakelock functionality of the application.
Now let’s build the application. To do so follow the below steps:
- Add the dependency to the pubspec.yaml file
- Import the dependency to the main.dart file
- Create a Statefulwidget to give a simple structure to the application
- Add OutlineButton to the body of the application
- Assign actions to the buttons
Now let’s discuss the steps in detail.
Adding the Dependency:
Inside the dependencies attribute of the pubspec.yaml file, add the wakelock dependency as shown below:
Importing the Dependency:
To import the wakelock dependency to the main.dart file, use the following:
Creating an application structure:
The StatefulWidget can be used to give a simple structure to the application as shown below:
One of the ways to add buttons in an application is to use the inbuilt OutlineButton widget in flutter. These are simple to implement and as discussed earlier, we will add two buttons to the body of the application namely: enable wakelock and disable wakelock as shown below:
Assigning Actions to Buttons:
Here we will be using a simple FutureBuilder to assign actions to the buttons. The first button (ie, enable wakelock) as the name suggests will keep the screen awake and the later (ie, disable wakelock) will disable the wakelock functionality. That can be done using the following:
Complete Source Code:
Since the output is not possible to show in any form unless tried by yourself, use the above source code and try it for yourself. The above output shows only the basic UI of the application we have built.