테마 제공자는 플러터 애플리케이션에서 테마 관리를 간소화하는 가벼우면서도 사용자 정의 가능한 패키지입니다. 위젯 트리 전체에서 테마 컨트롤러를 쉽게 공유할 수 있으며, 밝은 모드와 어두운 모드 간 전환을 원활하게 지원합니다. 최소한의 설정으로 전역적으로 테마를 정의하고 적용할 수 있어 동적 테마가 필요한 앱에 적합합니다. 이 패키지는 플러터 빌드 시스템과 원활하게 통합되며 모든 주요 플랫폼을 지원합니다.
사용 사례
다이나믹 테마 전환
라이트 모드 및 다크 모드 구현
글로벌 테마 관리
사용자 정의 테마 생성
크로스 플랫폼 테마
주요 기능
간편한 테마 컨트롤러 공유
라이트 모드와 다크 모드를 지원합니다
매우 사용자 정의 가능
최소한의 보일러플레이트
크로스 플랫폼 호환성
적합한 대상
테마 지속성을 필요로 하는 앱
간단한 테마를 찾는 개발자
다수의 주제를 가진 프로젝트
UI 중심 애플리케이션
Flutter 초보자가 테마 배우기
고려 사항
수동 테마 상태 관리가 필요합니다
제한된 내장 테마 프리셋
기본적으로 자동 테마 유지 없음
사용자 정의 테마 로직에 따라 다름
복잡한 테마 계층 구조에 최적화되지 않음
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
theme_provider
Easy to use, customizable Theme Provider. This provides app color schemes throughout the app and automatically rebuilds the UI dynamically.
You can also persist your color theme as well. Easily store and retrieve user preference without hassle.
This package also provides you with several widgets that can help you to easily add theme switching abilities.
Additionally you can pass option classes to store and provide data which should be associated with the current theme.
You may also provide additional themes using the themes parameter. Here you have to provide a theme id string and theme data value. (Make sure to provide unique theme ids)
classMyAppextendsStatelessWidget{
@overrideWidgetbuild(BuildContext context) {
returnThemeProvider(
themes: [
AppTheme.light(), // This is standard light theme (id is default_light_theme)AppTheme.dark(), // This is standard dark theme (id is default_dark_theme)AppTheme(
id: "custom_theme", // Id(or name) of the theme(Has to be unique)
description: "My Custom Theme", // Description of theme
data: ThemeData( // Real theme data
primaryColor: Colors.black,
accentColor: Colors.red,
),
),
],
child: ThemeConsumer(
child: Builder(
builder: (themeContext) => MaterialApp(
theme: ThemeProvider.themeOf(themeContext).data,
title: 'Material App',
home: HomePage(),
),
),
),
);
}
}
Changing and accessing the current theme
You can use the theme id strings to change the current theme of the app.
If you provide the theme consumer on MaterialApp then you don't have to provide ThemeConsumer on routes. However that would disable the ability to use multiple theme controllers. Also a visible flickr may occur at the start of app when the saved theme is loaded.
This approach is much easier to integrate and works well with all other material components such as SearchDelegates and DialogBoxes without wrapping with ThemeConsumers.
Wrapping each route independently with ThemeProvider
However you could also wrap each route and dialog in ThemeConsumer instead of wrapping the whole material app.
This will give a more granular control and will not cause a visual flikr.
However, some integrations(eg: SearchDelegates) might not be trivial.
If you want to change the StatusBarColor when the theme changes, you can provide a onThemeChanged callback to the ThemeProvider.
Passing Additional Options
This can also be used to pass additional data associated with the theme. Use options to pass additional data that should be associated with the theme.
eg: If font color on a specific button changes according to the current theme, create a class to encapsulate the value.
Options classes must implement or extend AppThemeOptions.
defaultThemeId will always be used to determine the initial theme. (If not provided the first theme you specify will be the default app theme.)
But you can manually load the previous(saved) theme by using:
Or to load a theme/do some task at theme controller initialization use onInitCallback.
This will get called on the start.
For example, snippet below will load the previously saved theme from the disk. (if previosuly saved.)
ThemeProvider(
defaultThemeId: "theme_1",
themes: [
AppTheme.light(id: "theme_1"),
AppTheme.light(id: "theme_2"),
AppTheme.light(id: "theme_3"),
],
saveThemesOnChange: true,
onInitCallback: (controller, previouslySavedThemeFuture) async {
// Do some other task here if you need toString savedTheme = await previouslySavedThemeFuture;
if (savedTheme != null) {
controller.setTheme(savedTheme);
}
},
// ...
)
⚡ Dynamically Adding/Removing Themes
Themes can be dynamically added/removed via addTheme and removeTheme. Whether a theme id exists or not can be checked via hasTheme.
A theme can only be added if it is not added previously. Similarly, a theme can only be removed if it is previously added.
So the membership must be checked before adding/removing themes. (Whether a theme exists or not is decided via its theme id)
Note that the active theme cannot be removed.
🔌 Checking system theme when loading initial theme
You can do this by simply checking for the system theme in onInitCallback callback. Following is an example usage.
In the following snippet, the theme will be set to the previously saved theme.
If there is no previously saved theme, it is set to light/dark depending on system theme.
You can use any kind of logic here to change the initialization callback.
Dynamically listening to theme changes is not yet available. The theme check is only possible on app start.
import'package:flutter/scheduler.dart';
ThemeProvider(
saveThemesOnChange: true, // Auto save any theme change we do
loadThemeOnInit: false, // Do not load the saved theme(use onInitCallback callback)
onInitCallback: (controller, previouslySavedThemeFuture) async {
String savedTheme = await previouslySavedThemeFuture;
if (savedTheme != null) {
// If previous theme saved, use saved theme
controller.setTheme(savedTheme);
} else {
// If previous theme not found, use platform defaultBrightness platformBrightness =
SchedulerBinding.instance.window.platformBrightness;
if (platformBrightness == Brightness.dark) {
controller.setTheme('dark');
} else {
controller.setTheme('light');
}
// Forget the saved theme(which were saved just now by previous lines)
controller.forgetSavedTheme();
}
},
themes: <AppTheme>[
AppTheme.light(id: 'light'),
AppTheme.dark(id: 'dark'),
],
child: ThemeConsumer(
child: Builder(
builder: (themeContext) => MaterialApp(
theme: ThemeProvider.themeOf(themeContext).data,
title: 'Material App',
home: HomePage(),
),
),
),
);
🎁 Additional Widgets
Theme Cycle Widget
IconButton to be added to AppBar to cycle to next theme.