What is wakelock in Flutter?

Introduction

Flutter is one of the most widely used languages for multiplatform mobile application development. It provides many features and plugins that help developers solve complex problems.

Flutter’s Wakelock is a plugin that allows you to keep your mobile device screen awake. This plugin prevents the screen from sleeping, mostly when the screen is idle and not used for a long time.

This feature is available on:

  • Android
  • iOS
  • Web

Installation

To use this plugin in your Flutter application, you need to install it in your app.

To install this plugin in your app, you need to write the following code in the terminal:

flutter pub add wakelock

After completion, the following line will be added to your pubspec.yaml file.

dependencies:
wakelock: ^0.5.6

You can also directly copy the above dependency and paste it into your pubspec.yaml file.

After this, you have to run the following command in the terminal for complete installation and smooth usage of these plugins.

flutter pub get

Usage

To use the dependency above in your code, copy the following command in the dart file where you have to use this plugin.

import 'package:wakelock/wakelock.dart';

Wakelock.enable()

If we want to enable the Wakelock feature in our app, it provides us with a predefined function. When the Wakelock is enabled, the specific screen stays awake forever even if it is not used or touched.

The following function should run to enable Wakelock:

Wakelock.enable();

Similarly, if we want to disable the Wakelock feature from our app, run the following code:

Wakelock.disable();

Wakelock.toggle()

Another advanced feature we can use is the toggle feature. Whenever this function is called, it will toggle the state of Wakelock. This means it will enable Wakelock if it is disabled and vice versa.

The following code shows some examples of usage of Wakelock.toggle().

import 'package:wakelock/wakelock.dart';
bool togglestate = true;
Wakelock.toggle(enable: togglestate);
togglestate = false;
Wakelock.toggle(enable: togglestate);

Wakelock.enabled()

We can also check or get the current state of Wakelock on our app by using another built-in feature of the Wakelock plugin. The function is called isEnabled.

bool wakelockEnabled = await Wakelock.enabled;

await is used because it takes some time to switch between the toggle states or retrieve the current state of Wakelock.

Free Resources