Flutter 中优雅切换应用主题的组件

简介: 【Flutter】使用adaptive_theme组件优雅切换应用主题:封装MaterialApp,支持light/dark/system模式,自定义色彩,保存选择,含调试按钮。安装配置、设置主题、监听切换、自定义颜色、读取配置步骤详细。代码示例与学习路径推荐。[查看完整教程](https://flutter.ducafecat.com/blog/flutter-app-theme-switch)

Flutter 中优雅切换应用主题的组件

视频

https://youtu.be/L--XLpc452I

https://www.bilibili.com/video/BV1wD421n75p/

前言

原文 https://ducafecat.com/blog/flutter-app-theme-switch

adaptive_theme

Adaptive Theme 这个组件通过包裹 MaterialApp 的方式整体管理 theme 主题,实现如下功能:

  • 切换 light、dark、system 三种模式
  • 自定义色彩
  • 保存主题选择
  • 开启调试按钮

参考

https://pub.dev/packages/adaptive_theme

https://flutter.ducafecat.com/pubs/adaptive_theme-package-info

https://github.com/birjuvachhani/adaptive_theme

步骤

安装配置

https://pub.dev/packages/adaptive_theme

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter

  adaptive_theme: ^3.6.0

lib/main.dart

class MyApp extends StatelessWidget {
   
   
  const MyApp({
   
   super.key});

  
  Widget build(BuildContext context) {
   
   
    return AdaptiveTheme(
      light: ThemeData.light(useMaterial3: true),
      dark: ThemeData.dark(useMaterial3: true),
      initial: AdaptiveThemeMode.light,
      debugShowFloatingThemeButton: true,
      builder: (theme, darkTheme) => MaterialApp(
        title: 'Flutter Demo',
        theme: theme,
        darkTheme: darkTheme,
        home: const MyHomePage(title: 'Flutter Demo Home Page'),
      ),
    );
  }
}

debugShowFloatingThemeButton 开启调试按钮

设置主题

设置亮色

ElevatedButton(
  onPressed: () {
   
   
    AdaptiveTheme.of(context).setLight();
  },
  child: const Text('Set Light Theme'),
),

设置暗色

ElevatedButton(
  onPressed: () {
   
   
    AdaptiveTheme.of(context).setDark();
  },
  child: const Text('Set Dark Theme'),
),

设置系统

ElevatedButton(
  onPressed: () {
   
   
    AdaptiveTheme.of(context).setSystem();
  },
  child: const Text('Set System Theme'),
),

toggle 切换

ElevatedButton(
  onPressed: () {
   
   
    AdaptiveTheme.of(context).toggleThemeMode();
  },
  child: const Text('Toggle Theme Mode'),
),

重置样式

ElevatedButton(
  onPressed: () {
   
   
    AdaptiveTheme.of(context).reset();
  },
  child: const Text('Reset Theme'),
),

监听样式切换

// 监听当前样式
ValueListenableBuilder(
  valueListenable: AdaptiveTheme.of(context).modeChangeNotifier,
  builder: (_, mode, child) {
   
   
    return Text(mode.modeName);
  },
),

自定义样式颜色

ElevatedButton(
  onPressed: () {
   
   
    AdaptiveTheme.of(context).setTheme(
      light: ThemeData(
        useMaterial3: true,
        brightness: Brightness.light,
        colorSchemeSeed: Colors.green,
      ),
      dark: ThemeData(
        useMaterial3: true,
        brightness: Brightness.dark,
        colorSchemeSeed: Colors.brown,
      ),
    );
  },
  child: const Text('Change Theme Color'),
),

读取配置

Future<void> main() async {
   
   
  WidgetsFlutterBinding.ensureInitialized();
  final savedThemeMode = await AdaptiveTheme.getThemeMode();
  runApp(MyApp(savedThemeMode: savedThemeMode));
}
class MyApp extends StatelessWidget {
   
   
  final AdaptiveThemeMode? savedThemeMode;

  const MyApp({
   
   super.key, this.savedThemeMode});

  // This widget is the root of your application.
  
  Widget build(BuildContext context) {
   
   
    return AdaptiveTheme(
      light: ThemeData.light(useMaterial3: true),
      dark: ThemeData.dark(useMaterial3: true),
      initial: savedThemeMode ?? AdaptiveThemeMode.light,
      debugShowFloatingThemeButton: true,
      builder: (theme, darkTheme) => MaterialApp(
        title: 'Flutter Demo',
        theme: theme,
        darkTheme: darkTheme,
        home: const MyHomePage(title: 'Flutter Demo Home Page'),
      ),
    );
  }
}

不要覆盖 key

本地离线采用 shared_preferences 组件,所以不要覆盖键值 adaptive_theme_preferences

https://github.com/BirjuVachhani/adaptive_theme/blob/main/lib/src/adaptive_theme.dart

  /// Key used to store theme information into shared-preferences. If you want
  /// to persist theme mode changes even after shared-preferences
  /// is cleared (e.g. after log out), do not remove this [prefKey] key from
  /// shared-preferences.
  static const String prefKey = 'adaptive_theme_preferences';

代码

https://github.com/ducafecat/flutter_develop_tips/tree/main/flutter_application_adaptive_theme

小结

通过使用 Flutter 的 adaptive_theme 组件,我们可以轻松地实现应用主题的切换功能。该组件提供了简单的方法来手动设置浅色或深色主题,并且还可以根据系统定义的主题进行自适应切换。无论是在用户界面上还是在代码层面上,我们可以灵活地控制应用程序的主题外观,为用户提供更好的体验。

感谢阅读本文

如果有什么建议,请在评论中让我知道。我很乐意改进。


flutter 学习路径


© 猫哥
ducafecat.com

end

相关文章
|
26天前
|
Dart 开发者 UED
flutter 非常用组件整理 第三篇
本文是非常用组件的第三讲,介绍了一些不为人知但却能大幅提升Flutter应用UI效果和功能的高级组件,包括FadeInImage、GridPaper、Hero等,为开发者带来更丰富的UI设计可能。
flutter 非常用组件整理 第三篇
|
26天前
|
Dart 数据安全/隐私保护 开发者
flutter 非常用组件整理 第二篇
本文是Flutter非常用组件第二篇,从开发者的视角出发,精选并深入剖析了AboutDialog、AnimatedGrid、Badge等鲜为人知却功能强大的隐藏组件,为读者提供了一份全面的Flutter UI组件使用指南。无论您是初学者还是有经验的开发者,相信本文都能为您的Flutter项目注入新的活力,助力打造出色的应用界面。
flutter 非常用组件整理 第二篇
|
26天前
|
存储 安全 数据安全/隐私保护
构建安全Flutter应用 - 6个实用技巧
随着越来越多的敏感用户数据在Flutter应用中流通,应用安全已成为首要关注点。本文为您总结6大关键Flutter应用安全最佳实践,帮助开发者筑牢应用安全防线,保护用户隐私。
构建安全Flutter应用 - 6个实用技巧
|
7天前
|
开发工具
解决Flutter中ThemeData.primaryColor在AppBar等组件中不生效
解决Flutter中ThemeData.primaryColor在AppBar等组件中不生效
15 1
|
8天前
|
开发者 容器
Flutter笔记:Widgets Easier组件库(3)使用按钮组件
Flutter笔记:Widgets Easier组件库(3)使用按钮组件
16 2
|
5天前
|
编解码 Dart 网络协议
"震撼揭秘!Flutter如何玩转超低延迟RTSP/RTMP播放,跨平台视频流体验大升级,让你的应用秒变直播神器!"
【8月更文挑战第15天】Flutter作为跨平台UI框架,以其高效性和丰富生态著称。本文详述如何利用flutter_vlc_player等插件在Flutter中实现低延迟RTSP/RTMP播放,并提供代码示例。通过优化播放器设置,如禁用缓冲、启用帧丢弃等,可进一步减少延迟,提升用户观看体验,展现了Flutter在视频流媒体应用中的强大潜力。
13 0
|
1月前
flutter 导航组件 AppBar (含顶部选项卡TabBar,抽屉菜单 drawer ,自定义导航图标)
flutter 导航组件 AppBar (含顶部选项卡TabBar,抽屉菜单 drawer ,自定义导航图标)
23 1
|
2月前
|
监控 Serverless 持续交付
阿里云云效产品使用问题之如何让流水线支持构建 flutter web 应用到 OSS
云效作为一款全面覆盖研发全生命周期管理的云端效能平台,致力于帮助企业实现高效协同、敏捷研发和持续交付。本合集收集整理了用户在使用云效过程中遇到的常见问题,问题涉及项目创建与管理、需求规划与迭代、代码托管与版本控制、自动化测试、持续集成与发布等方面。
|
2月前
|
缓存 视频直播
flutter3-dylive 基于flutter3.19+getx短视频/直播应用
基于跨端技术flutter3.19+dart3+getx实战短视频/直播应用项目。
46 4
|
2月前
|
开发框架 Dart JavaScript
深入探讨Flutter中的Web支持功能,以及如何利用Flutter构建跨平台Web应用的最佳实践
【6月更文挑战第11天】Flutter,Google的开源跨平台框架,已延伸至Web支持,让开发者能用同一代码库构建移动和Web应用。Flutter Web基于Dart转JavaScript,利用WebAssembly和JavaScript在Web上运行。构建Web应用最佳实践包括选择合适项目、优化性能、进行兼容性测试和利用Flutter的声明式UI、热重载等优势。尽管性能挑战存在,Flutter Web为跨平台开发提供了更多机会和潜力。
64 1