We will use Screen package dependency and add to pubspec.yaml file
screen: ^2.5.0
Add the wakelock permission in AndroidManifest.xml file
<uses-permission android:name="android.permission.WAKE_LOCK"/>
Now your main.dart file be like:
import 'package:flutter/material.dart';
import 'package:screen/screen.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget{
@override
_HomePageState createState(){
return _HomePageState();
}
}
class _HomePageState extends State<HomePage> {
double screenbrightness = 0.5;
//brightness must be double value rainding 0.0 - 1.0
// Get the current brightness:
double brightness = await Screen.brightness;
// Set the brightness:
Screen.setBrightness(0.5);
// Check if the screen is kept on:
bool isKeptOn = await Screen.isKeptOn;
// Prevent screen from going into sleep mode:
Screen.keepOn(true);
@override
void initState() {
Future.delayed(Duration.zero,() async { //there is await function, so we use Future.delayed
double brightness = await Screen.brightness; //get the current screen brightness
if(brightness > 1){
brightness = brightness / 10;
// sometime it gives value ranging 0.0 - 10.0, so convert it to range 0.0 - 1.0
}
print(brightness);
setState(() {
screenbrightness = brightness;
//change the variable value and update screen UI
});
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blue[100], //background color of scaffold
appBar: AppBar(
title:Text("Change Screen Brightness"), //title of app
backgroundColor: Colors.redAccent, //background color of app bar
),
body: Container(
child:Column(children: [
Container(
margin: EdgeInsets.only(top:60),
child: Text("Chnage Screen Brightness")
),
Container(
child: Text("Brightness Value: $screenbrightness")
),
Container(
child: Slider( //add the slider to configure brightness
min: 0.0,
max: 1.0,
onChanged: (value){ //this function will be executed when slider value is changed
Screen.setBrightness(value); //set screen brightness with slider value
setState(() {
screenbrightness = value; //update the UI
});
},
value: screenbrightness, //set default slider value
)
)
],)
)
);
}
}