Outline
When you develop the app with Flutter, sometimes you need to keep the screen awake when the Flutter app is activated or the user uses the specific features in the app.
In my case, the app has the TTS feature to repeat playing the voice. When the screen is off, the TTS repeating is stopped, so I need to keep the screen awake when the user uses repeating playing the voice by TTS.
At this time, I use the wakelock
package.
- wakelock: https://pub.dev/packages/wakelock
In this blog post, I will introduce how to the wakelock
package to keep the screen awake when the Flutter app is started.
Install wakelock
To keep the screen awake in the Flutter app, you need to install the wakelock
package first. Execute the command below to install the wakelock
package.
flutter pub add wakelock
enable and disable
wakelock
provides the enable
function and disable
function. When you use the enable
function of wakelock
, you can keep the screen awake. To check this feature, open the main.dart
file and modify it like the following.
...
void main() {
WidgetsFlutterBinding.ensureInitialized();
Wakelock.enable();
runApp(..);
}
class _MyAppState extends State<MyApp> {
...
@override
void dispose() {
Wakelock.disable();
super.dispose();
}
...
}
...
The wakelock
class has the enable
function and disable
funtion. When you use the enable
function of the wakelock
class, the screen does not sleep automatically. And when you use the disable
function, the screen sleeps automatically.
The functions of the wakelock
class should be called after checking WidgetsBinding
initialized by WidgetsFlutterBinding.ensureInitialized()
.
toggle
You can use the toggle
function of wakelock
instead of the enable
and disable
function roles. To check this, open the main.dart
file and modify it like the following.
...
void main() {
WidgetsFlutterBinding.ensureInitialized();
Wakelock.toggle(enable: true);
runApp(..);
}
class _MyAppState extends State<MyApp> {
...
@override
void dispose() {
Wakelock.toggle(enable: false);
super.dispose();
}
...
}
...
enabled
wakelock
also provides the enabled
variable to check whether the current screen automatically sleeps or not.
...
bool wakelockEnabled = await Wakelock.enabled;
...
Completed
Done! we’ve seen how to use the wakelock
package to keep the screen awake in the Flutter app. Next, try to use the wakelock
package to keep the screen awake.
Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!
App promotion
Deku
.Deku
created the applications with Flutter.If you have interested, please try to download them for free.