Flutter主题管理插件theme_genius的使用
Flutter主题管理插件ThemeGenius的使用
简介
ThemeGenius 是一个 Flutter 插件,提供了简单的方式来管理应用中的主题模式。它支持浅色模式、深色模式和系统模式,并且可以通过 SharedPreferencesAsync API 保存和加载主题设置。
安装
为了开始使用 ThemeGenius,你需要确保已经安装了 Flutter SDK。然后可以通过以下两种方式之一来安装 ThemeGenius:
- 
使用
flutter pub add命令:dart pub add theme_genius - 
在
pubspec.yaml文件中添加依赖:dependencies: theme_genius: ^2.0.0 
使用示例
1. 包含 ThemeGeniusWrapper 的主应用程序
首先,导入 ThemeGeniusWrapper 并将其包裹在 MaterialApp 外面。这将允许你在整个应用程序中管理主题模式。
import 'package:flutter/material.dart';
import 'package:theme_genius/theme_genius.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  [@override](/user/override)
  Widget build(BuildContext context) {
    return ThemeGeniusWrapper(
      builder: (themeMode) {
        return MaterialApp(
          themeMode: themeMode,
          theme: ThemeData.light(useMaterial3: true),
          darkTheme: ThemeData.dark(useMaterial3: true),
          home: const HomePage(),
        );
      },
    );
  }
}
2. 获取当前的主题模式
你可以通过 ThemeGenius.getThemeMode 方法获取当前的主题模式。该方法返回一个 Future<ThemeMode>,因此需要使用 await 关键字。
final themeMode = await ThemeGenius.getThemeMode(context);
3. 更改并保存主题模式
要更改并保存主题模式,可以使用 ThemeGenius.setThemeMode 方法。同样,该方法返回一个 Future,因此需要使用 await 关键字。
final themeMode = ThemeMode.dark;
await ThemeGenius.setThemeMode(context, themeMode: themeMode);
4. 加载已保存的主题模式
如果你希望在应用程序启动时加载已保存的主题模式,可以使用 ThemeGenius.loadThemeMode 方法。
final themeMode = await ThemeGenius.loadThemeMode();
5. 设置默认主题模式
你可以在 ThemeGeniusWrapper 中设置默认的主题模式。如果用户没有选择过任何主题模式,应用程序将使用这个默认值。
return ThemeGeniusWrapper(
  builder: (themeMode) {
    return MaterialApp(...);
  },
  defaultThemeMode: ThemeMode.dark,
);
6. 设置占位符
你还可以设置一个占位符(例如一个加载指示器),在主题模式加载完成之前显示。
return ThemeGeniusWrapper(
  builder: (themeMode) {
    return MaterialApp(...);
  },
  placeholder: const Scaffold(
    body: Center(
      child: CircularProgressIndicator(),
    ),
  ),
);
完整示例代码
以下是一个完整的示例代码,展示了如何使用 ThemeGenius 来管理主题模式,并提供了一个下拉菜单供用户选择不同的主题模式。
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:theme_genius/theme_genius.dart';
const list = ['System', 'Light', 'Dark'];
const iconList = [Icons.auto_mode, Icons.light_mode, Icons.dark_mode];
void main() {
  FlutterError.onError = (details) {
    log(details.exceptionAsString(), stackTrace: details.stack);
  };
  runApp(const App());
}
class App extends StatelessWidget {
  const App({super.key});
  [@override](/user/override)
  Widget build(BuildContext context) {
    return ThemeGeniusWrapper(
      builder: (themeMode) {
        return MaterialApp(
          themeMode: themeMode,
          theme: ThemeData.light(useMaterial3: true),
          darkTheme: ThemeData.dark(useMaterial3: true),
          home: const HomePage(),
        );
      },
    );
  }
}
class HomePage extends StatefulWidget {
  const HomePage({super.key});
  [@override](/user/override)
  State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
  String? dropdownValue;
  String? themeModeText;
  [@override](/user/override)
  void initState() {
    super.initState();
    _loadCurrentThemeMode();
  }
  Future<void> _loadCurrentThemeMode() async {
    final themeMode = await ThemeGenius.getThemeMode(context);
    final value = switch (themeMode) {
      ThemeMode.light => list[1],
      ThemeMode.dark => list[2],
      _ => list[0],
    };
    setState(() {
      dropdownValue = value;
      themeModeText = themeMode.toString();
    });
  }
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 32),
        child: Column(
          children: [
            const SizedBox(height: 100),
            Text(
              'Current Theme Mode: $themeModeText',
              textAlign: TextAlign.center,
              style: const TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
            Expanded(
              child: Center(
                child: DropdownButton<String>(
                  isExpanded: true,
                  value: dropdownValue,
                  onChanged: (String? value) async {
                    final themeMode = switch (value) {
                      'Light' => ThemeMode.light,
                      'Dark' => ThemeMode.dark,
                      _ => ThemeMode.system,
                    };
                    await ThemeGenius.setThemeMode(
                      context,
                      themeMode: themeMode,
                    );
                    setState(() {
                      dropdownValue = value;
                      themeModeText = themeMode.toString();
                    });
                  },
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  items: List.generate(
                    list.length,
                    (index) => DropdownMenuItem(
                      value: list[index],
                      child: Row(
                        children: [
                          Icon(iconList[index]),
                          const SizedBox(width: 8),
                          Text(list[index]),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
更多关于Flutter主题管理插件theme_genius的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter主题管理插件theme_genius的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何使用 theme_genius 插件在 Flutter 中进行主题管理的代码示例。theme_genius 是一个强大的 Flutter 插件,它允许开发者轻松地管理和切换应用主题。
首先,确保你已经在 pubspec.yaml 文件中添加了 theme_genius 依赖:
dependencies:
  flutter:
    sdk: flutter
  theme_genius: ^latest_version  # 请替换为最新版本号
然后,运行 flutter pub get 来获取依赖。
接下来,让我们看一下如何在 Flutter 应用中使用 theme_genius。
1. 设置主题数据
首先,你需要定义你的主题数据。你可以在 lib 目录下创建一个 themes.dart 文件来存储这些主题。
// themes.dart
import 'package:flutter/material.dart';
ThemeData lightTheme() {
  return ThemeData(
    brightness: Brightness.light,
    primarySwatch: Colors.blue,
    scaffoldBackgroundColor: Colors.white,
    // 添加其他主题设置
  );
}
ThemeData darkTheme() {
  return ThemeData(
    brightness: Brightness.dark,
    primarySwatch: Colors.blueGrey,
    scaffoldBackgroundColor: Colors.black,
    // 添加其他主题设置
  );
}
2. 配置 ThemeGenius
在你的主应用文件(通常是 main.dart)中,配置 ThemeGenius。
// main.dart
import 'package:flutter/material.dart';
import 'package:theme_genius/theme_genius.dart';
import 'themes.dart';
void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ThemeGenius(
      // 定义默认主题
      defaultTheme: lightTheme(),
      // 定义所有可用主题
      themes: {
        'Light': lightTheme(),
        'Dark': darkTheme(),
      },
      // 监听主题变化回调(可选)
      onThemeChanged: (ThemeData theme) {
        print('Theme changed to: ${theme.brightness == Brightness.light ? 'Light' : 'Dark'}');
      },
      child: MaterialApp(
        title: 'Flutter Theme Genius Demo',
        theme: ThemeData(), // 这里不需要设置具体主题,ThemeGenius 会管理它
        home: HomeScreen(),
      ),
    );
  }
}
3. 在应用中使用主题切换功能
现在,你可以在应用中使用主题切换功能。例如,在 HomeScreen 中添加一个按钮来切换主题。
// home_screen.dart
import 'package:flutter/material.dart';
import 'package:theme_genius/theme_genius.dart';
class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final ThemeGenius themeGenius = ThemeGenius.of(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('Theme Genius Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Current Theme: ${themeGenius.currentThemeName ?? 'Light'}',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                // 切换主题
                themeGenius.switchTheme();
              },
              child: Text('Switch Theme'),
            ),
          ],
        ),
      ),
    );
  }
}
总结
上面的代码展示了如何使用 theme_genius 插件在 Flutter 应用中进行主题管理。你定义了两个主题(亮色和暗色),并在 ThemeGenius 中配置了这些主题。然后,在 HomeScreen 中,你添加了一个按钮来切换主题,并在屏幕上显示当前的主题名称。
这个示例只是一个起点,theme_genius 插件还提供了更多高级功能,比如持久化主题设置、根据系统主题自动切换等,你可以根据需求进一步探索和使用这些功能。
        
      
            
            
            
