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

패키지 상세v3.0.0

best_theme

라이트 모드와 다크 모드를 지원하는 Flutter용 테마 관리 패키지입니다.

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
88
좋아요
6
Pub 점수
160

패키지 설치

flutter pub add best_theme

패키지 개요

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

Best_Theme는 시ーム리스한 테마 관리를 위한 Flutter 패키지로, 라이트 모드와 다크 모드를 내장된 지원 기능을 제공합니다. 다양한 플랫폼 간 동적 테마 구현을 단순화하여 개발자가 모드 전환을 쉽게 할 수 있도록 합니다. 이 패키지는 Flutter 애플리케이션에 원활하게 통합되며, 안드로이드, iOS, 웹, macOS, 윈도우, 리눅스에서 일관된 UI 경험을 제공합니다. 단일 pub 명령어로 최소한의 설정만으로 접근성과 사용자 경험을 향상시키는 적응형 디자인을 가능하게 합니다. 가벼운 구조로 불필요한 부담 없이 빠른 성능을 보장합니다.

사용 사례

  • 모바일 앱에서 라이트 모드와 다크 모드 구현하기
  • 테마 전환을 사용한 접근성 있는 UI 만들기
  • 일관된 테마로 크로스 플랫폼 앱 빌드하기
  • 사용자 선호도 기반 테마 선택 활성화
  • 테마 상태 관리 간소화

주요 기능

  • 내장된 라이트 모드 및 다크 모드 지원
  • 크로스 플랫폼 호환성
  • flutter pub add와의 간편한 통합
  • 최소한의 보일러플레이트 코드
  • 자동 테마 유지

적합한 대상

  • 반응형 앱을 구축하는 Flutter 개발자
  • 동적 테마가 필요한 앱
  • 다양한 플랫폼을 대상으로 하는 개발자
  • 사용자 경험 및 접근성에 중점을 둔 프로젝트
  • 빠른 테마 구현을 원하는 팀

고려 사항

  • 사용자 정의 테마를 위해 추가 로직이 필요할 수 있습니다
  • 사전 정의된 밝기/어두운 모드로 제한
  • 기본 설정 외에 내장된 테마 사용자 지정 기능이 없습니다
  • Flutter의 테마 시스템에 의존합니다
  • 매우 복잡한 테마 아키텍처에는 적합하지 않습니다

원본 README

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

Best Theme


Best Theme is a powerful Flutter package designed to simplify theme management within your applications. It provides an intuitive way to define and switch between light and dark modes while allowing you to add your own custom colors, text styles, and assets with seamless context-based access — powered by Flutter's native ThemeExtension system and static code generation.

Table of Contents

Features

  • ✅ Built on Flutter's native ThemeExtension system
  • ✅ Static code generation
  • ✅ Light & Dark theme support
  • ✅ Type-safe custom colors
  • ✅ Type-safe text styles
  • ✅ Type-safe assets
  • ✅ Persistent theme storage support
  • ✅ Context-based access
  • ✅ Easy theme switching
  • ✅ Supports custom ThemeData configuration
  • ✅ Zero runtime token parsing

Installation

Add the required packages:

flutter pub add best_theme
flutter pub add best_theme_annotation
dart pub add dev:best_theme_generator
dart pub add dev:build_runner

Then run:

flutter pub get

Usage

1. Create Theme File with Tokens and Class Definition

Create a theme file (for example my_theme.dart):

import 'package:best_theme/best_theme.dart';
import 'package:best_theme_annotation/best_theme_annotation.dart';
import 'package:flutter/material.dart';

part 'my_theme.g.dart';

@BestTheme(extensionName: 'appTheme')
class MyTheme extends _$MyTheme {

  static const primary = BestColor(
    light: Colors.blue,
    dark: Colors.indigo,
  );

  static const card = BestColor(
    light: Color(0xffFCFCFC),
    dark: Color(0xff1E1E2A),
  );

  static const titleLarge = BestTextStyle(
    light: TextStyle(
      fontSize: 24,
      fontWeight: FontWeight.bold,
      color: Colors.black87,
    ),
    dark: TextStyle(
      fontSize: 24,
      fontWeight: FontWeight.bold,
      color: Colors.white,
    ),
  );

  static const appLogo = BestAsset(
    light: 'assets/images/logo_light.png',
    dark: 'assets/images/logo_dark.png',
  );
}

Generate the code:

dart run build_runner build -d

For continuous generation:

dart run build_runner watch -d

2. Persistent Storage Adapter (Optional)

To automatically save and restore the selected theme mode:

import 'package:best_theme/best_theme.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SharedPrefThemeStorage implements BestThemeStorage {
  static const _key = 'theme_mode_index';

  @override
  Future<ThemeMode?> loadThemeMode() async {
    final prefs = await SharedPreferences.getInstance();
    final index = prefs.getInt(_key);

    return index != null
        ? ThemeMode.values[index]
        : null;
  }

  @override
  Future<void> saveThemeMode(ThemeMode mode) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_key, mode.index);
  }
}

3. Wrap Your App with MyThemeMaterial
void main() {
  runApp(
    MyThemeMaterial(
      initialMode: ThemeMode.system,
      storage: SharedPrefThemeStorage(),
      builder: (
        context,
        mode,
        lightTheme,
        darkTheme,
      ) {
        return MaterialApp(
          title: 'My App',
          themeMode: mode,
          theme: lightTheme,
          darkTheme: darkTheme,
          home: const HomePage(),
        );
      },
    ),
  );
}

4. Using Custom Design Tokens

Access your colors, text styles, and assets using the generated context extension:

Container(
  decoration: BoxDecoration(
    color: context.appTheme.card,
    border: Border.all(
      color: context.appTheme.primary,
    ),
  ),
  child: Column(
    children: [
      Image.asset(
        context.appTheme.appLogo,
      ),
      Text(
        'Hello World!',
        style: context.appTheme.titleLarge,
      ),
    ],
  ),
);

5. Customize ThemeData (Fonts, Colors, Components, etc.)

Override the generated theme builders:

@BestTheme(extensionName: 'appTheme')
class MyTheme extends _$MyTheme {

  static const primary = BestColor(
    light: Colors.blue,
    dark: Colors.indigo,
  );

  @override
  ThemeData buildLightTheme(ThemeData base) {
    return base.copyWith(
      fontFamily: 'Roboto',
      appBarTheme: const AppBarTheme(
        elevation: 0,
        centerTitle: true,
      ),
      colorScheme: ColorScheme.light(
        primary: Colors.blue,
      ),
    );
  }

  @override
  ThemeData buildDarkTheme(ThemeData base) {
    return base.copyWith(
      fontFamily: 'Roboto',
      scaffoldBackgroundColor: const Color(0xFF0A1628),
      colorScheme: ColorScheme.dark(
        primary: Colors.indigo,
      ),
    );
  }
}

Generated extensions are automatically merged into ThemeData.extensions.


6. Theme Control

Toggle between themes:

context.toggleTheme();

Set a specific mode:

context.setThemeMode(ThemeMode.dark);
context.setThemeMode(ThemeMode.light);
context.setThemeMode(ThemeMode.system);

Shortcuts:

context.toDark();
context.toLight();

Check current state:

bool isDarkMode = context.isDark;

Access common ThemeData properties:

Color background = context.scaffoldBackgroundColor;
Color primary = context.primary;

7. Theme Toggle Switch Example
Switch(
  value: context.isDark,
  onChanged: (_) {
    context.toggleTheme();
  },
)

8. GoRouter Support
final router = GoRouter(
  routes: [
    GoRoute(
      path: '/',
      builder: (_, __) => const HomePage(),
    ),
  ],
);

void main() {
  runApp(
    MyThemeMaterial(
      initialMode: ThemeMode.system,
      builder: (
        context,
        mode,
        lightTheme,
        darkTheme,
      ) {
        return MaterialApp.router(
          routerConfig: router,
          themeMode: mode,
          theme: lightTheme,
          darkTheme: darkTheme,
        );
      },
    ),
  );
}

API Reference

Context Extensions
Extension Description
context.{extensionName}.{fieldName} Access generated color, text style, or asset
context.isDark Returns true when current theme is dark
context.toggleTheme() Toggle between light and dark modes
context.setThemeMode(mode) Set a specific ThemeMode
context.toDark() Switch to dark mode
context.toLight() Switch to light mode
context.primary Access ThemeData primary color
context.scaffoldBackgroundColor Access scaffold background color

Migration from 2.0.0 to 3.0.0 (Breaking Changes)

Version 3.0.0 introduces a fully static approach for better performance, cleaner code generation, and improved type safety.

For the old 2.0.0 documentation, see the 2.0.0 README.

Changes Checklist
Remove vars

Old:

@BestTheme(
  vars: ['primary'],
  extensionName: 'appColors',
)
class MyTheme extends _$MyTheme {}

New:

@BestTheme(
  extensionName: 'appColors',
)
class MyTheme extends _$MyTheme {
  static const primary = BestColor(
    light: Colors.blue,
    dark: Colors.indigo,
  );
}

Remove Runtime Constructors

Old:

List<BestColor> dataColor = [
  const BestColor(
    name: 'primary',
    light: Colors.blue,
    dark: Colors.indigo,
  ),
];

class MyTheme extends _$MyTheme {
  MyTheme() : super(
    myColors: dataColor,
  );
}

New:

class MyTheme extends _$MyTheme {
  static const primary = BestColor(
    light: Colors.blue,
    dark: Colors.indigo,
  );
}

Declare Tokens as Static Constants

Old:

final primary = BestColor(
  light: Colors.blue,
  dark: Colors.indigo,
);

New:

static const primary = BestColor(
  light: Colors.blue,
  dark: Colors.indigo,
);

Contributing

Contributions are welcome and appreciated.

Report Issues

Open an issue if you find a bug or unexpected behavior.

Request Features

Have an idea for improvement? Create a feature request and share it with the community.

Submit Pull Requests

Pull requests are always welcome.


About the Developer

Developed by Dosty Pshtiwan — a passionate Full-Stack Software Developer focused on building tools that improve developer productivity and Flutter development experience.

Connect
  • 🌐 Website: https://dostypshtiwan.com
  • 💻 GitHub: https://github.com/dosty17
  • 📺 YouTube: Flutter Tutorials
  • 📘 Facebook: Dosty Pshtiwan

Links

  • 🎥 YouTube Tutorials
  • 💻 GitHub Repository
  • 🌐 Official Website

카테고리

소스 저장소

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

아직 데이터가 없습니다.