패키지, 저장소 및 앱 카테고리 검색

패키지 상세v3.8.0

adaptive_theme

다이내믹하게 라이트 테마와 다크 테마를 전환하고 시스템 적응형 테마 지원을 추가할 수 있습니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
3.5만
좋아요
956
Pub 점수
150

패키지 설치

flutter pub add adaptive_theme

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Adaptive Theme는 플러터 패키지로, 라이트 테마와 다크 테마 간의 동적 전환을 가능하게 하며, 시스템 수준의 테마 적응을 내장 지원합니다. 개발자가 다양한 기기에서 사용자 선호도에 원활하게 반응할 수 있도록 주제 관리를 단순화합니다. 이 패키지는 플러터의 테마 시스템과 원활하게 통합되며, Android, iOS, Web, macOS, Windows, Linux 등 모든 주요 플랫폼을 지원합니다. 프로그래밍 방식으로 테마를 변경하거나 장치의 시스템 설정과 동기화하기 위한 깔끔한 API를 제공합니다.

사용 사례

  • 앱에서의 동적 테마 전환
  • 시스템 테마 인식 구현
  • 다크 모드로 접근성 있는 UI 만들기
  • 사용자 선호 지속성 지원
  • 크로스 플랫폼 애플리케이션 빌드
  • 실시간 테마 업데이트 활성화

주요 기능

  • 시스템 테마 자동 감지
  • 런타임 테마 전환
  • 지속적인 테마 저장
  • 크로스 플랫폼 호환성
  • 간단한 API 통합
  • 테마 사용자 정의 옵션

적합한 대상

  • 반응형 UI를 구축하는 개발자
  • 다크 모드 지원이 필요한 앱
  • 다중 플랫폼을 대상으로 하는 프로젝트
  • 사용자 중심 설계 구현
  • 접근성 우선 고려하는 팀
  • Flutter 초보자가 테마를 배우는 방법

고려 사항

  • 테마 상태 유지에 대한 수동 처리가 필요합니다
  • 라이트/다크 테마 전환에 제한됨
  • 복잡한 테마 계획을 위해 추가 로직이 필요할 수 있습니다
  • 올바른 초기화 순서에 따라 달라진다
  • 밝음/어두움을 초과한 다중 테마 디자인에는 적합하지 않습니다
  • 다중 페이지 탐색에서 주의 깊은 조작이 필요합니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

adaptive_theme

Adaptive Theme

The easiest way to add support for light and dark themes in your Flutter app. It allows you to manually set a light or dark theme and also lets you define themes based on the system. It also persists the theme mode changes across app restarts.

Build Tests Codecov Pub Version

Demo: Adaptive Theme

Index

Getting Started

Add the following dependency to your pubspec.yaml

dependencies:
  adaptive_theme: <latest_version>

Initialization

You need to wrap your MaterialApp with AdaptiveTheme in order to apply themes.

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

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

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return AdaptiveTheme(
      light: ThemeData.light(useMaterial3: true),
      dark: ThemeData.dark(useMaterial3: true),
      initial: AdaptiveThemeMode.light,
      builder: (theme, darkTheme) => MaterialApp(
        title: 'Adaptive Theme Demo',
        theme: theme,
        darkTheme: darkTheme,
        home: MyHomePage(),
      ),
    );
  }
}

Changing Theme Mode

Now that you have initialized your app as mentioned above. It's very easy and straightforward to change your theme modes: light to dark, dark to light, or to system default.

// sets theme mode to dark
AdaptiveTheme.of(context).setDark();

// sets theme mode to light
AdaptiveTheme.of(context).setLight();

// sets theme mode to system default
AdaptiveTheme.of(context).setSystem();

Toggle Theme Mode

AdaptiveTheme allows you to toggle between light, dark, and system themes the easiest way possible.

AdaptiveTheme.of(context).toggleThemeMode();

Changing Themes

If you want to change the theme entirely, e.g., change all the colors to some other color swatch, then you can use setTheme method.

AdaptiveTheme.of(context).setTheme(
  light: ThemeData(
    useMaterial3: true,
    brightness: Brightness.light,
    colorSchemeSeed: Colors.purple,
  ),
  dark: ThemeData(
    useMaterial3: true,
    brightness: Brightness.dark,
    colorSchemeSeed: Colors.purple,
  ),
);

Reset Theme

AdaptiveTheme is smart enough to keep your default themes handy that you provided at the time of initialization. You can fall back to those default themes in a very easy way.

AdaptiveTheme.of(context).reset();

This will reset your theme as well as theme mode to the initial values provided at the time of initialization.

Set Default Theme

AdaptiveTheme persists theme mode changes across app restarts and uses the default themes to set theme modes (light/dark) on. You can change this behavior if you want to set a different theme as the default theme other than the one provided at the time of initialization.

This comes in handy when you're fetching themes remotely on app starts and the setting theme as the current theme.

Doing so is quite easy. You would set a new theme normally as you do by calling setTheme method but this time, with a flag isDefault set to true.

This is only useful when you might want to reset to default theme at some point.

AdaptiveTheme.of(context).setTheme(
  light: ThemeData(
    useMaterial3: true,
    brightness: Brightness.light,
    colorSchemeSeed: Colors.blue,
  ),
  dark: ThemeData(
    useMaterial3: true,
    brightness: Brightness.dark,
    colorSchemeSeed: Colors.blue,
  ),
  isDefault: true,
);

Get ThemeMode at App Start

When you change your theme, the next app run won't be able to pick the most recent theme directly before rendering with the default theme for the first time. This is because at the time of initialization, we cannot run async code to get the previous theme mode. However, it can be avoided if you make your main() method async and load the previous theme mode asynchronously. The example below shows how it can be done.

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final savedThemeMode = await AdaptiveTheme.getThemeMode();
  runApp(MyApp(savedThemeMode: savedThemeMode));
}
AdaptiveTheme(
  light: lightTheme,
  dark: darkTheme,
  initial: savedThemeMode ?? AdaptiveThemeMode.light,
  builder: (theme, darkTheme) => MaterialApp(
    title: 'Adaptive Theme Demo',
    theme: theme,
    darkTheme: darkTheme,
    home: MyHomePage(),
  ),
)

Notice that I passed the retrieved theme mode to my material app so that I can use it while initializing the default theme. This helps to avoid theme change flickering on app startup.

Listen to the theme mode changes

You can listen to the changes in the theme mode via a ValueNotifier. This can be useful when designing a theme settings screen or developing UI to show theme status.

AdaptiveTheme.of(context).modeChangeNotifier.addListener(() {
  // do your thing.
});

Or you can utilize it to react on UI with

ValueListenableBuilder(
  valueListenable: AdaptiveTheme.of(context).modeChangeNotifier,
  builder: (_, mode, child) {
    // update your UI
    return Container();
  },
);

Using a floating theme button overlay

Starting from v3.3.0, you can now set debugShowFloatingThemeButton to true and enable a floating button that can be used to toggle theme mode very easily. This is useful when you want to test your app with both light and dark themes without restarting the app or navigating to the settings screen where your theme settings are available.

AdaptiveTheme(
  light: ThemeData.light(),
  dark: ThemeData.dark(),
  debugShowFloatingThemeButton: true, // <------ add this line
  initial: AdaptiveThemeMode.light,
  builder: (theme, darkTheme) => MaterialApp(
    theme: theme,
    darkTheme: darkTheme,
    home: MyHomePage(),
  ),
);

Video

Caveats

Non-Persistent theme changes

This is only useful in scenarios where you load your themes dynamically from network in the splash screen or some initial screens of the app. Please note that AdaptiveTheme does not persist the themes, it only persists the theme modes(light/dark/system). Any changes made to the provided themes won't be persisted and you will have to do the same changes at the time of the initialization if you want them to apply every time app is opened. e.g changing the accent color.

Using SharedPreferences

This package uses shared_preferences plugin internally to persist theme mode changes. If your app uses shared_preferences which might be the case all the time, clearing your shared_preferences at the time of logging out or signing out might clear these preferences too. Be careful not to clear these preferences if you want it to be persisted.

/// Do not remove this key from preferences
AdaptiveTheme.prefKey

You can use the above key to exclude it while clearing all the preferences.

Or you can call AdaptiveTheme.persist() method after clearing the preferences to make it persistable again as shown below.

final prefs = await SharedPreferences.getInstance();
await prefs.clear();
AdaptiveTheme.persist();

Using CupertinoTheme

Wrap your CupertinoApp with CupertinoAdaptiveTheme in order to apply themes.

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

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

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return CupertinoAdaptiveTheme(
      light: CupertinoThemeData(
        brightness: Brightness.light,
      ),
      dark: CupertinoThemeData(
        brightness: Brightness.dark,
      ),
      initial: AdaptiveThemeMode.light,
      builder: (theme) => CupertinoApp(
        title: 'Adaptive Theme Demo',
        theme: theme,
        home: MyHomePage(),
      ),
    );
  }
}
Changing Cupertino Theme
// sets dark theme
CupertinoAdaptiveTheme.of(context).setDark();

// sets light theme
CupertinoAdaptiveTheme.of(context).setLight();

// sets system default theme
CupertinoAdaptiveTheme.of(context).setSystem();

Contribution

You are most welcome to contribute to this project!

Please have a look at Contributing Guidelines, before contributing and proposing a change.

Liked Adaptive Theme?

Show some love and support by starring the repository.

Or You can

Buy Me A Coffee

License

Copyright © 2020 Birju Vachhani

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

카테고리

의존성

의존성 목록 3 개

소스 저장소

이 패키지를 사용하는 프로젝트