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

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

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

screen_brightness_windowsscreen_brightness 插件在 Windows 平台上的实现。这个插件允许您在 Flutter 应用中控制屏幕亮度。

使用方法

该插件是被推荐使用的,这意味着您可以像平常一样使用 screen_brightness 包,并且当您这样做时,该插件会自动包含在您的应用中。

以下是一个完整的示例代码,展示了如何使用 screen_brightness_windows 控制屏幕亮度:

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_windows的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用screen_brightness_windows插件来控制Windows平台屏幕亮度的代码示例。

首先,确保你已经在pubspec.yaml文件中添加了screen_brightness_windows依赖:

dependencies:
  flutter:
    sdk: flutter
  screen_brightness: ^x.y.z  # 请使用最新版本号
  screen_brightness_windows: ^x.y.z  # 请使用最新版本号

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

接下来,你需要配置插件。在windows文件夹下的CMakeLists.txt文件中添加以下内容(如果文件不存在,则创建一个):

cmake_minimum_required(VERSION 3.10)

# 添加对screen_brightness_windows插件的支持
add_subdirectory(plugins/screen_brightness_windows/windows .)

并在windows文件夹下的Runner项目中,打开Runner.sln,然后右键点击Runner项目,选择“添加” -> “现有项”,将plugins/screen_brightness_windows/windows文件夹中的screen_brightness_plugin.cpp文件添加到项目中。

现在,你可以在你的Flutter项目中编写代码来控制屏幕亮度。以下是一个简单的示例:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Screen Brightness Control',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  double _brightness = 1.0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Screen Brightness Control'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Current Brightness: $_brightness',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            Slider(
              value: _brightness,
              min: 0.0,
              max: 1.0,
              divisions: 10,
              onChanged: (newBrightness) {
                setState(() {
                  _brightness = newBrightness;
                  // 更新屏幕亮度
                  ScreenBrightness.setBrightness(newBrightness).then((result) {
                    if (result) {
                      print('Brightness updated successfully.');
                    } else {
                      print('Failed to update brightness.');
                    }
                  });
                });
              },
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个滑块来调整屏幕亮度。当用户拖动滑块时,我们将新的亮度值传递给ScreenBrightness.setBrightness方法,该方法会尝试更新Windows平台的屏幕亮度。

请注意,由于Flutter和插件的更新,上述代码和步骤可能需要根据你的具体环境进行调整。确保查阅最新的插件文档和Flutter指南,以获得最准确的信息。

回到顶部