Flutter屏幕亮度控制插件screen_brightness的使用
Flutter屏幕亮度控制插件screen_brightness的使用
描述
screen_brightness
是一个用于控制应用内屏幕亮度的Flutter插件。它允许开发者调整应用内的屏幕亮度,而不会影响系统的全局亮度设置。因此,在使用此插件时无需申请额外的权限。
开始使用
安装
首先在 pubspec.yaml
文件中添加依赖:
dependencies:
screen_brightness: ^latest_version
请确保使用最新的版本号,可以通过访问 pub.dev 获取最新版本信息。
对于Android平台,如果需要调整系统亮度(非必须),还需要在 AndroidManifest.xml
中添加以下权限声明:
<uses-permission android:name="android.permission.WRITE_SETTINGS" tools:ignore="ProtectedPermissions"/>
API介绍
获取/设置系统亮度
-
获取系统亮度
Future<double> get systemBrightness async { try { return await ScreenBrightness.instance.system; } catch (e) { print(e); throw 'Failed to get system brightness'; } }
-
设置系统亮度
Future<void> setSystemBrightness(double brightness) async { try { await ScreenBrightness.instance.setSystemScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); throw 'Failed to set system brightness'; } }
获取/设置应用亮度
-
获取应用亮度
Future<double> get applicationBrightness async { try { return await ScreenBrightness.instance.application; } catch (e) { print(e); throw 'Failed to get application brightness'; } }
-
设置应用亮度
Future<void> setApplicationBrightness(double brightness) async { try { await ScreenBrightness.instance.setApplicationScreenBrightness(brightness); } catch (e) { debugPrint(e.toString()); throw 'Failed to set application brightness'; } }
-
重置应用亮度
Future<void> resetApplicationBrightness() async { try { await ScreenBrightness.instance.resetApplicationScreenBrightness(); } catch (e) { debugPrint(e.toString()); throw 'Failed to reset application brightness'; } }
监听亮度变化
-
监听系统亮度变化
StreamBuilder<double>( stream: ScreenBrightness.instance.onSystemScreenBrightnessChanged, builder: (context, snapshot) { double changedSystemBrightness = systemBrightness; if (snapshot.hasData) { changedSystemBrightness = snapshot.data!; } return Text('system brightness $changedSystemBrightness'); }, )
-
监听应用亮度变化
StreamBuilder<double>( stream: ScreenBrightness.instance.onApplicationScreenBrightnessChanged, builder: (context, snapshot) { double changedApplicationBrightness = applicationBrightness; if (snapshot.hasData) { changedApplicationBrightness = snapshot.data!; } return Text('application brightness $changedApplicationBrightness'); }, )
其他功能
-
检查是否启用了自动重置
Future<bool> getIsAutoResetSetting() async { final isAutoReset = await ScreenBrightness.instance.isAutoReset; setState(() { this.isAutoReset = isAutoReset; }); }
-
切换是否可以更改系统亮度
Future<void> getCanChangeSystemBrightness() async { final canChangeSystemBrightness = await ScreenBrightness.instance.canChangeSystemBrightness; setState(() { this.canChangeSystemBrightness = canChangeSystemBrightness; }); }
示例代码
下面是一个完整的示例应用,展示了如何使用 screen_brightness
插件来控制屏幕亮度。该应用包含了一个主页面和一个控制器页面,用户可以在控制器页面通过滑块调整系统或应用的亮度,并查看当前亮度值。
import 'package:flutter/material.dart';
import 'package:screen_brightness/screen_brightness.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
static final RouteObserver<Route> routeObserver = RouteObserver<Route>();
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: const HomePage(),
onGenerateRoute: (settings) {
late final Widget page;
switch (settings.name) {
case HomePage.routeName:
page = const HomePage();
break;
case ControllerPage.routeName:
page = const ControllerPage();
break;
default:
throw UnimplementedError('page name not found');
}
return MaterialPageRoute(
builder: (context) => page,
settings: settings,
);
},
navigatorObservers: [
routeObserver,
],
);
}
}
class HomePage extends StatelessWidget {
static const routeName = '/home';
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Screen brightness example'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
FutureBuilder<double>(
future: ScreenBrightness.instance.application,
builder: (context, snapshot) {
double applicationBrightness = 0;
if (snapshot.hasData) {
applicationBrightness = snapshot.data!;
}
return StreamBuilder<double>(
stream: ScreenBrightness.instance.onApplicationScreenBrightnessChanged,
builder: (context, snapshot) {
double changedApplicationBrightness = applicationBrightness;
if (snapshot.hasData) {
changedApplicationBrightness = snapshot.data!;
}
return Text(
'Application brightness $changedApplicationBrightness');
},
);
},
),
ElevatedButton(
onPressed: () =>
Navigator.of(context).pushNamed(ControllerPage.routeName),
child: const Text('Controller example page'),
),
],
),
),
);
}
}
class ControllerPage extends StatefulWidget {
static const routeName = '/controller';
const ControllerPage({super.key});
@override
State<ControllerPage> createState() => _ControllerPageState();
}
class _ControllerPageState extends State<ControllerPage> {
Future<void> setSystemBrightness(double brightness) async {
try {
await ScreenBrightness.instance.setSystemScreenBrightness(brightness);
} catch (e) {
debugPrint(e.toString());
throw 'Failed to set system brightness';
}
}
Future<void> setApplicationBrightness(double brightness) async {
try {
await ScreenBrightness.instance.setApplicationScreenBrightness(brightness);
} catch (e) {
debugPrint(e.toString());
throw 'Failed to set application brightness';
}
}
Future<void> resetApplicationBrightness() async {
try {
await ScreenBrightness.instance.resetApplicationScreenBrightness();
} catch (e) {
debugPrint(e.toString());
throw 'Failed to reset application brightness';
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Controller'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FutureBuilder<double>(
future: ScreenBrightness.instance.system,
builder: (context, snapshot) {
double systemBrightness = 0;
if (snapshot.hasData) {
systemBrightness = snapshot.data!;
}
return StreamBuilder<double>(
stream: ScreenBrightness.instance.onSystemScreenBrightnessChanged,
builder: (context, snapshot) {
double changedSystemBrightness = systemBrightness;
if (snapshot.hasData) {
changedSystemBrightness = snapshot.data!;
}
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('System brightness: $changedSystemBrightness'),
Slider.adaptive(
value: changedSystemBrightness,
onChanged: (value) {
setSystemBrightness(value);
},
),
],
);
},
);
},
),
FutureBuilder<double>(
future: ScreenBrightness.instance.application,
builder: (context, snapshot) {
double applicationBrightness = 0;
if (snapshot.hasData) {
applicationBrightness = snapshot.data!;
}
return StreamBuilder<double>(
stream: ScreenBrightness.instance.onApplicationScreenBrightnessChanged,
builder: (context, snapshot) {
double changedApplicationBrightness = applicationBrightness;
if (snapshot.hasData) {
changedApplicationBrightness = snapshot.data!;
}
return Column(
mainAxisSize: MainAxisSize.min,
children: [
FutureBuilder<bool>(
future: ScreenBrightness.instance.hasApplicationScreenBrightnessChanged,
builder: (context, snapshot) {
return Text(
'Application brightness has changed via plugin: ${snapshot.data}');
},
),
Text(
'Application brightness: $changedApplicationBrightness'),
Slider.adaptive(
value: changedApplicationBrightness,
onChanged: (value) {
setApplicationBrightness(value);
},
),
ElevatedButton(
onPressed: () {
resetApplicationBrightness();
},
child: const Text('reset brightness'),
),
],
);
},
);
},
),
],
),
);
}
}
这段代码创建了一个简单的Flutter应用程序,其中包含两个页面:首页和控制器页面。在控制器页面中,用户可以通过滑动条调整系统或应用的亮度,并实时看到亮度的变化。同时,还提供了按钮用于重置应用亮度。
更多关于Flutter屏幕亮度控制插件screen_brightness的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter屏幕亮度控制插件screen_brightness的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter中使用screen_brightness
插件来控制屏幕亮度的示例代码。
首先,你需要在你的pubspec.yaml
文件中添加screen_brightness
插件的依赖:
dependencies:
flutter:
sdk: flutter
screen_brightness: ^0.5.0 # 请检查最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,在你的Flutter项目中,你可以使用以下代码来控制屏幕亮度。
示例代码
- 导入必要的包
在你的Dart文件中(例如main.dart
),导入screen_brightness
包:
import 'package:flutter/material.dart';
import 'package:screen_brightness/screen_brightness.dart';
- 创建状态类
创建一个StatefulWidget,并在其中使用ScreenBrightness
插件:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: ScreenBrightnessControl(),
);
}
}
class ScreenBrightnessControl extends StatefulWidget {
@override
_ScreenBrightnessControlState createState() => _ScreenBrightnessControlState();
}
class _ScreenBrightnessControlState extends State<ScreenBrightnessControl> {
ScreenBrightness? _screenBrightness;
double _brightness = 1.0; // 初始亮度设为1.0(最大亮度)
@override
void initState() {
super.initState();
_screenBrightness = ScreenBrightness();
// 获取当前屏幕亮度
_getCurrentBrightness();
}
@override
void dispose() {
_screenBrightness?.dispose();
super.dispose();
}
Future<void> _getCurrentBrightness() async {
double? brightness = await _screenBrightness?.getBrightness();
if (brightness != null) {
setState(() {
_brightness = brightness;
});
}
}
Future<void> _setBrightness(double brightness) async {
await _screenBrightness?.setBrightness(brightness);
setState(() {
_brightness = brightness;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Screen Brightness Control'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Current Brightness: $_brightness'),
Slider(
value: _brightness,
min: 0.0,
max: 1.0,
onChanged: (newBrightness) {
setState(() {
_brightness = newBrightness;
});
_setBrightness(newBrightness);
},
),
],
),
),
);
}
}
解释
-
依赖导入:首先,我们导入了
flutter/material.dart
和screen_brightness/screen_brightness.dart
。 -
状态管理:使用
StatefulWidget
和_ScreenBrightnessControlState
来管理状态。 -
插件初始化:在
initState
方法中,我们初始化了ScreenBrightness
插件,并获取了当前的屏幕亮度。 -
亮度获取和设置:我们定义了两个方法
_getCurrentBrightness
和_setBrightness
,分别用于获取和设置屏幕亮度。 -
UI界面:使用
Slider
组件来让用户调整屏幕亮度,并在UI上实时显示当前的亮度值。
这样,你就可以通过滑动条来动态调整设备的屏幕亮度了。确保在不再需要时调用dispose
方法以释放资源。