Flutter主题动态切换插件flutter_dynamic_theme的使用

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

Flutter主题动态切换插件flutter_dynamic_theme的使用

简介

flutter_dynamic_theme插件允许您指定多个颜色主题,用户可以在其中选择。选定的主题在应用程序重启时会保留。

在项目中包含该插件

  1. pubspec.yaml文件中添加依赖:
    dependencies:
      flutter_dynamic_theme: <lastedVersion>
    
  2. 运行packages get命令并导入插件:
    import 'package:flutter_dynamic_theme/flutter_dynamic_theme.dart';
    

如果您需要显示对话框:

import 'package:flutter_dynamic_theme/theme_switcher_widgets.dart';

如果您需要颜色列表:

import 'package:flutter_dynamic_theme/dynamic_colors.dart';

以下是示例图片:

image image

开始使用

以下是一个完整的示例代码,展示如何使用flutter_dynamic_theme插件:

import 'package:flutter/material.dart';

import 'package:flutter_dynamic_theme/flutter_dynamic_theme.dart';
import 'package:flutter_dynamic_theme/theme_switcher_widgets.dart';
import 'package:flutter_dynamic_theme/color_theme_dialog.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  @override
  Widget build(BuildContext context) {
    return FlutterDynamicTheme(
      // 默认亮度为亮色
      defaultBrightness: Brightness.light,
      // 根据亮度返回主题数据
      data: (Brightness brightness) => ThemeData(
        primarySwatch: Colors.indigo, // 主色调
        brightness: brightness, // 亮度
      ),
      loadBrightnessOnStart: true, // 启动时加载保存的亮度设置
      themedWidgetBuilder: (BuildContext context, ThemeData theme) {
        return MaterialApp(
          title: 'Flutter Dynamic Theme',
          theme: theme,
          home: MyHomePage(title: 'Flutter Dynamic Theme Home Page'),
        );
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: FlutterDynamicTheme.of(context)?.toggleBrightness, // 切换亮度
              child: const Text('Toggle brightness'),
            ),
            ElevatedButton(
              onPressed: showChooser, // 显示亮度和颜色选择器
              child: const Text('Pop Up Change brightness'),
            ),
            const Divider(),
            ElevatedButton(
              onPressed: showActionsSettingsColorTheme, // 显示颜色选择器
              child: const Text('Change color'),
            ),
          ],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.insert_drive_file),
            label: 'Tab 1',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.show_chart),
            label: 'Tab 2',
          ),
        ],
      ),
    );
  }

  // 显示颜色主题选择器
  showActionsSettingsColorTheme() {
    showDialog(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return const ColorThemeDialog();
        });
  }

  // 显示亮度选择器
  void showChooser() {
    showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return BrightnessSwitcherDialog(
          activeToggleMode: true, // 激活亮度切换模式
          activeColor: true, // 激活颜色选项
          textDarkMode: 'Mode Dark :(', // 暗模式文本
          textLightMode: 'Light Mode :)', // 亮模式文本
          onSelectedTheme: (Brightness brightness) {
            FlutterDynamicTheme.of(context)?.setBrightness(brightness); // 设置亮度
          },
        );
      },
    );
  }
}

更改颜色主题

您可以使用以下方法更改颜色主题:

FlutterDynamicTheme.of(context)?.setThemeData(new ThemeData(primarySwatch: Colors.red));
// 或者
FlutterDynamicTheme.of(context)?.setThemeData(new ThemeData(primaryColor: Colors.red));

显示弹出窗口以同时更改亮度和颜色

void showChooser() {
    showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return BrightnessSwitcherDialog(
          activeToggleMode: true,
          activeColor: true, // 激活颜色选项
          textDarkMode: 'Mode Dark :(',
          textLightMode: 'Light Mode :)',
          onSelectedTheme: (Brightness brightness) {
            FlutterDynamicTheme.of(context)?.setBrightness(brightness);
          },
        );
      },
    );
}

激活颜色选项:

activeColor: true

更多关于Flutter主题动态切换插件flutter_dynamic_theme的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter主题动态切换插件flutter_dynamic_theme的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用flutter_dynamic_theme插件来实现主题动态切换的代码案例。这个插件允许你在运行时切换应用的主题(如浅色和深色模式),并持久化用户的偏好设置。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加flutter_dynamic_theme依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_dynamic_theme: ^3.0.3  # 请检查最新版本号

2. 导入包

在你的主Dart文件(通常是main.dart)中导入必要的包:

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

3. 定义主题

定义一个浅色主题和一个深色主题:

final ThemeData lightTheme = ThemeData(
  brightness: Brightness.light,
  primarySwatch: Colors.blue,
  // 其他配置...
);

final ThemeData darkTheme = ThemeData(
  brightness: Brightness.dark,
  primarySwatch: Colors.blueGrey,
  // 其他配置...
);

4. 设置主题提供者和包裹应用

使用FlutterDynamicTheme包裹你的应用,并设置主题列表和默认主题:

void main() {
  runApp(
    FlutterDynamicTheme.builder(
      defaultBrightness: Brightness.light, // 或 Brightness.dark
      themes: {
        Brightness.light: lightTheme,
        Brightness.dark: darkTheme,
      },
      builder: (context, theme) => MaterialApp(
        theme: theme,
        home: MyHomePage(),
      ),
    ),
  );
}

5. 创建切换主题的按钮

在你的主页面(如MyHomePage)中,添加一个按钮来切换主题:

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dynamic Theme Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Current Theme: ${Theme.of(context).brightness == Brightness.light ? 'Light' : 'Dark'}',
              style: Theme.of(context).textTheme.headline4,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                FlutterDynamicTheme.of(context).setBrightness(
                  Theme.of(context).brightness == Brightness.light
                      ? Brightness.dark
                      : Brightness.light,
                );
              },
              child: Text('Switch Theme'),
            ),
          ],
        ),
      ),
    );
  }
}

6. 持久化主题偏好

为了在用户重新启动应用时保持主题设置,你可以使用shared_preferences插件来存储用户的主题偏好。以下是如何集成shared_preferences的简要说明:

添加shared_preferences依赖

pubspec.yaml中添加:

dependencies:
  shared_preferences: ^2.0.15  # 请检查最新版本号

使用shared_preferences持久化主题

import 'package:shared_preferences/shared_preferences.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final SharedPreferences prefs = await SharedPreferences.getInstance();

  Brightness initialBrightness = (prefs.getBool('darkMode') ?? false)
      ? Brightness.dark
      : Brightness.light;

  runApp(
    FlutterDynamicTheme.builder(
      defaultBrightness: initialBrightness,
      themes: {
        Brightness.light: lightTheme,
        Brightness.dark: darkTheme,
      },
      builder: (context, theme) {
        return MaterialApp(
          theme: theme,
          home: MyHomePage(prefs: prefs),
        );
      },
    ),
  );
}

class MyHomePage extends StatelessWidget {
  final SharedPreferences prefs;

  MyHomePage({required this.prefs});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dynamic Theme Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Current Theme: ${Theme.of(context).brightness == Brightness.light ? 'Light' : 'Dark'}',
              style: Theme.of(context).textTheme.headline4,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                bool isDarkMode = Theme.of(context).brightness == Brightness.dark;
                await prefs.setBool('darkMode', isDarkMode);
                FlutterDynamicTheme.of(context).setBrightness(
                  isDarkMode ? Brightness.light : Brightness.dark,
                );
              },
              child: Text('Switch Theme'),
            ),
          ],
        ),
      ),
    );
  }
}

以上代码展示了如何在Flutter中使用flutter_dynamic_theme插件来实现主题的动态切换,并通过shared_preferences持久化用户的主题偏好。

回到顶部