Keep Your Screen Awake with wakelock_plus for Flutter
Published on by Flutter News Hub
Ever wanted to keep your device's screen awake, preventing it from automatically dimming or sleeping? The wakelock_plus
plugin for Flutter has you covered. This guide will show you how to seamlessly integrate this powerful tool into your app for various platforms, including Android, iOS, and more.
Supported Platforms:
- 📱 Android
- 🍎 iOS
- 🌐 Web
- 💻 macOS
- 🪟 Windows
- 🐧 Linux
Prerequisites:
Before getting started, ensure you have the wakelock_plus
plugin installed in your Flutter project. Follow the installation instructions provided here.
Usage:
Activating and deactivating the screen wakelock is straightforward with wakelock_plus
:
import 'package:wakelock_plus/wakelock_plus.dart';
// To enable the wakelock:
WakelockPlus.enable();
// To disable the wakelock:
WakelockPlus.disable();
Advanced Usage:
You can toggle the wakelock based on a boolean value and retrieve its current status:
import 'package:wakelock_plus/wakelock_plus.dart';
// Toggle the wakelock:
WakelockPlus.toggle(enable: true); // Enable
WakelockPlus.toggle(enable: false); // Disable
// Check if the wakelock is enabled:
bool wakelockEnabled = await WakelockPlus.enabled;
Platform-Specific Instructions:
Android:
For Android, ensure you have the correct NDK version specified in your app
module's build.gradle
file. This can be found in the error message if you encounter any issues. For example:
android {
ndkVersion "25.1.8937393"
// ...
}
Best Practices:
- Call
WakelockPlus.enable()
only when necessary, as the wakelock can be released by external sources. - Consider enabling the wakelock based on specific UI components or events within your app, rather than in
main()
.
Conclusion:
With wakelock_plus
, you can now effectively keep your device's screen awake with minimal effort. Remember to use it judiciously and consider the user experience to avoid any potential drawbacks.