Flutter屏幕亮度控制插件screen_brightness_macos的使用

发布于 1周前 作者 vueper 来自 Flutter

Flutter屏幕亮度控制插件screen_brightness_macos的使用

screen_brightness_macosscreen_brightness 插件的macOS联邦插件实现。这个包是被认可的,这意味着你可以直接使用 screen_brightness 包,并且在你的应用中自动包含此插件。

使用示例

下面是一个完整的Flutter应用程序示例,展示了如何使用 screen_brightness_macos 来控制屏幕亮度。

import 'package:flutter/material.dart';
import 'package:screen_brightness_platform_interface/screen_brightness_platform_interface.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  static final RouteObserver<Route> routeObserver = RouteObserver<Route>();

  const MyApp({super.key});

  [@override](/user/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;

          case RouteAwarePage.routeName:
            page = const RouteAwarePage();
            break;

          case BlankPage.routeName:
            page = const BlankPage();
            break;

          case SettingPage.routeName:
            page = const SettingPage();
            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](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('屏幕亮度示例'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            FutureBuilder<double>(
              future: ScreenBrightnessPlatform.instance.application,
              builder: (context, snapshot) {
                double applicationBrightness = 0;
                if (snapshot.hasData) {
                  applicationBrightness = snapshot.data!;
                }

                return StreamBuilder<double>(
                  stream: ScreenBrightnessPlatform
                      .instance.onApplicationScreenBrightnessChanged,
                  builder: (context, snapshot) {
                    double changedApplicationBrightness = applicationBrightness;
                    if (snapshot.hasData) {
                      changedApplicationBrightness = snapshot.data!;
                    }

                    return Text(
                        '应用亮度 $changedApplicationBrightness');
                  },
                );
              },
            ),
            ElevatedButton(
              onPressed: () =>
                  Navigator.of(context).pushNamed(ControllerPage.routeName),
              child: const Text('控制器示例页面'),
            ),
            ElevatedButton(
              onPressed: () =>
                  Navigator.of(context).pushNamed(RouteAwarePage.routeName),
              child: const Text('路由感知示例页面'),
            ),
            ElevatedButton(
              onPressed: () =>
                  Navigator.of(context).pushNamed(SettingPage.routeName),
              child: const Text('设置页面'),
            ),
          ],
        ),
      ),
    );
  }
}

class ControllerPage extends StatefulWidget {
  static const routeName = '/controller';

  const ControllerPage({super.key});

  [@override](/user/override)
  State<ControllerPage> createState() => _ControllerPageState();
}

class _ControllerPageState extends State<ControllerPage> {
  Future<void> setSystemBrightness(double brightness) async {
    try {
      await ScreenBrightnessPlatform.instance
          .setSystemScreenBrightness(brightness);
    } catch (e) {
      debugPrint(e.toString());
      throw '无法设置系统亮度';
    }
  }

  Future<void> setApplicationBrightness(double brightness) async {
    try {
      await ScreenBrightnessPlatform.instance
          .setApplicationScreenBrightness(brightness);
    } catch (e) {
      debugPrint(e.toString());
      throw '无法设置应用亮度';
    }
  }

  Future<void> resetApplicationBrightness() async {
    try {
      await ScreenBrightnessPlatform.instance
          .resetApplicationScreenBrightness();
    } catch (e) {
      debugPrint(e.toString());
      throw '无法重置应用亮度';
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('控制器'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FutureBuilder<double>(
            future: ScreenBrightnessPlatform.instance.system,
            builder: (context, snapshot) {
              double systemBrightness = 0;
              if (snapshot.hasData) {
                systemBrightness = snapshot.data!;
              }

              return StreamBuilder<double>(
                  stream: ScreenBrightnessPlatform
                      .instance.onSystemScreenBrightnessChanged,
                  builder: (context, snapshot) {
                    double changedSystemBrightness = systemBrightness;
                    if (snapshot.hasData) {
                      changedSystemBrightness = snapshot.data!;
                    }
                    return Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Text('系统亮度: $changedSystemBrightness'),
                        Slider.adaptive(
                          value: changedSystemBrightness,
                          onChanged: (value) {
                            setSystemBrightness(value);
                          },
                        ),
                      ],
                    );
                  });
            },
          ),
          FutureBuilder<double>(
            future: ScreenBrightnessPlatform.instance.application,
            builder: (context, snapshot) {
              double applicationBrightness = 0;
              if (snapshot.hasData) {
                applicationBrightness = snapshot.data!;
              }

              return StreamBuilder<double>(
                stream: ScreenBrightnessPlatform
                    .instance.onApplicationScreenBrightnessChanged,
                builder: (context, snapshot) {
                  double changedApplicationBrightness = applicationBrightness;
                  if (snapshot.hasData) {
                    changedApplicationBrightness = snapshot.data!;
                  }

                  return Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      FutureBuilder<bool>(
                        future: ScreenBrightnessPlatform
                            .instance.hasApplicationScreenBrightnessChanged,
                        builder: (context, snapshot) {
                          return Text(
                              '应用亮度是否通过插件改变: ${snapshot.data}');
                        },
                      ),
                      Text(
                          '应用亮度: $changedApplicationBrightness'),
                      Slider.adaptive(
                        value: changedApplicationBrightness,
                        onChanged: (value) {
                          setApplicationBrightness(value);
                        },
                      ),
                      ElevatedButton(
                        onPressed: () {
                          resetApplicationBrightness();
                        },
                        child: const Text('重置亮度'),
                      ),
                    ],
                  );
                },
              );
            },
          ),
        ],
      ),
    );
  }
}

class RouteAwarePage extends StatefulWidget {
  static const routeName = '/routeAware';

  const RouteAwarePage({super.key});

  [@override](/user/override)
  State<RouteAwarePage> createState() => _RouteAwarePageState();
}

class _RouteAwarePageState extends State<RouteAwarePage> with RouteAware {
  [@override](/user/override)
  void didChangeDependencies() {
    super.didChangeDependencies();
    MyApp.routeObserver.subscribe(this, ModalRoute.of(context)!);
  }

  [@override](/user/override)
  void dispose() {
    MyApp.routeObserver.unsubscribe(this);
    super.dispose();
  }

  [@override](/user/override)
  void didPush() {
    super.didPush();
    ScreenBrightnessPlatform.instance.setApplicationScreenBrightness(0.7);
  }

  [@override](/user/override)
  void didPushNext() {
    super.didPushNext();
    ScreenBrightnessPlatform.instance.resetApplicationScreenBrightness();
  }

  [@override](/user/override)
  void didPop() {
    super.didPop();
    ScreenBrightnessPlatform.instance.resetApplicationScreenBrightness();
  }

  [@override](/user/override)
  void didPopNext() {
    super.didPopNext();
    ScreenBrightnessPlatform.instance.setApplicationScreenBrightness(0.7);
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('路由感知'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () => Navigator.of(context).pushNamed(BlankPage.routeName),
          child: const Text('下一页'),
        ),
      ),
    );
  }
}

class BlankPage extends StatelessWidget {
  static const routeName = '/blankPage';

  const BlankPage({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('空白页'),
      ),
    );
  }
}

class SettingPage extends StatefulWidget {
  static const routeName = '/setting';

  const SettingPage({super.key});

  [@override](/user/override)
  State<SettingPage> createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  bool isAutoReset = true;
  bool isAnimate = true;
  bool canChangeSystemBrightness = true;

  [@override](/user/override)
  void initState() {
    super.initState();
    getIsAutoResetSetting();
    getIsAnimateSetting();
    getCanChangeSystemBrightness();
  }

  Future<void> getIsAutoResetSetting() async {
    final isAutoReset = await ScreenBrightnessPlatform.instance.isAutoReset;
    setState(() {
      this.isAutoReset = isAutoReset;
    });
  }

  Future<void> getIsAnimateSetting() async {
    final isAnimate = await ScreenBrightnessPlatform.instance.isAnimate;
    setState(() {
      this.isAnimate = isAnimate;
    });
  }

  Future<void> getCanChangeSystemBrightness() async {
    final canChangeSystemBrightness =
        await ScreenBrightnessPlatform.instance.canChangeSystemBrightness;
    setState(() {
      this.canChangeSystemBrightness = canChangeSystemBrightness;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('设置'),
      ),
      body: ListView(
        children: [
          ListTile(
            title: const Text('自动重置'),
            trailing: Switch(
              value: isAutoReset,
              onChanged: (value) async {
                await ScreenBrightnessPlatform.instance.setAutoReset(value);
                await getIsAutoResetSetting();
              },
            ),
          ),
          ListTile(
            title: const Text('动画'),
            trailing: Switch(
              value: isAnimate,
              onChanged: (value) async {
                await ScreenBrightnessPlatform.instance.setAnimate(value);
                await getIsAnimateSetting();
              },
            ),
          ),
          ListTile(
            title: const Text('可以更改系统亮度'),
            trailing: Switch(
              value: canChangeSystemBrightness,
              onChanged: (value) {},
            ),
          ),
        ],
      ),
    );
  }
}

更多关于Flutter屏幕亮度控制插件screen_brightness_macos的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter屏幕亮度控制插件screen_brightness_macos的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用screen_brightness_macos插件来控制macOS屏幕亮度的示例代码。这个插件允许你在Flutter应用中调整设备的屏幕亮度。

首先,确保你的Flutter项目已经创建,并且你已经安装了screen_brightness插件及其macOS平台特定的实现。

  1. 添加依赖

    在你的pubspec.yaml文件中添加screen_brightness依赖:

    dependencies:
      flutter:
        sdk: flutter
      screen_brightness: ^x.y.z  # 替换为最新版本号
    

    然后运行flutter pub get来安装依赖。

  2. 配置iOS和macOS平台

    由于screen_brightness_macos是macOS平台特定的实现,你需要在ios/Podfile中确保平台版本符合要求(通常是macOS 10.12及以上),并在Info.plist中添加必要的权限(虽然屏幕亮度控制通常不需要用户权限,但总是好的做法检查并配置)。

    确保你的macos/Runner/Info.plist文件(如果存在)已正确配置。

  3. 使用插件

    接下来,在你的Flutter代码中导入screen_brightness插件并使用它来控制屏幕亮度。

    import 'package:flutter/material.dart';
    import 'package:screen_brightness/screen_brightness.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      double _brightness = 1.0;  // 默认亮度为1.0(最大亮度)
    
      @override
      void initState() {
        super.initState();
    
        // 获取当前屏幕亮度
        _getBrightness();
      }
    
      Future<void> _getBrightness() async {
        try {
          double brightness = await ScreenBrightness.getBrightness();
          setState(() {
            _brightness = brightness;
          });
        } catch (e) {
          print("Error getting brightness: $e");
        }
      }
    
      Future<void> _setBrightness(double brightness) async {
        try {
          await ScreenBrightness.setBrightness(brightness);
          setState(() {
            _brightness = brightness;
          });
        } catch (e) {
          print("Error setting brightness: $e");
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: Text('Screen Brightness Control'),
            ),
            body: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('Current Brightness: $_brightness'),
                  Slider(
                    value: _brightness,
                    min: 0.0,
                    max: 1.0,
                    onChanged: (newValue) {
                      setState(() {
                        _brightness = newValue;
                      });
                      // 实时设置屏幕亮度(可以添加防抖逻辑以避免频繁调用)
                      _setBrightness(newValue);
                    },
                  ),
                ],
              ),
            ),
          ),
        );
      }
    }
    

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个显示当前屏幕亮度的文本和一个允许用户调整屏幕亮度的滑块。滑块的值范围从0.0(完全关闭)到1.0(最大亮度)。当用户移动滑块时,我们会调用_setBrightness方法来更新屏幕亮度。

注意:由于screen_brightness_macos是特定于macOS的实现,因此这个代码示例仅在macOS上有效。如果你在iOS或其他平台上运行此代码,你需要使用相应的平台特定实现或添加平台检查。

回到顶部