본문 바로가기
IT

Flutter로 간단한 다크모드 앱 구현해보기

by dhui 2025. 4. 2.
반응형

Flutter로 간단한 다크모드 앱 구현해보기

많은 앱들이 이제는 다크모드를 기본처럼 지원합니다. 눈의 피로도 줄여주고, 배터리도 아낄 수 있으니까요. Flutter에서도 다크모드를 아주 간단하게 구현할 수 있어요. 이번 글에서는 Flutter에서 다크모드를 적용하는 방법을 차근차근 예제와 함께 알아보겠습니다.

 

[ 빠르게 이동하기 ]

● 프로젝트 생성

● 다크모드 테마 적용 기본 구조

● 기본 홈 화면 만들기

● 사용자 설정으로 다크모드 전환하기

● 테마 색상 커스터마이징 하기


🧱 프로젝트 생성부터 시작

먼저 새로운 Flutter 프로젝트를 생성해봅시다.

flutter create dark_mode_demo
cd dark_mode_demo

 

lib/main.dart 파일을 열어 아래처럼 기본 코드를 수정합니다.


🌗 다크모드 테마 적용 기본 구조

Flutter의 MaterialApp에는 theme과 darkTheme, 그리고 themeMode라는 속성이 있습니다.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '다크모드 데모',
      theme: ThemeData(
        brightness: Brightness.light,
        primarySwatch: Colors.blue,
      ),
      darkTheme: ThemeData(
        brightness: Brightness.dark,
        primarySwatch: Colors.blueGrey,
      ),
      themeMode: ThemeMode.system, // 시스템 설정에 따라 변경됨
      home: const HomePage(),
    );
  }
}

 

여기서 핵심은 themeMode입니다:

  • ThemeMode.system: 시스템 설정에 따라 자동 전환
  • ThemeMode.light: 항상 라이트 모드
  • ThemeMode.dark: 항상 다크 모드


🏠 기본 홈 화면 만들기

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('다크모드 예제'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '현재 테마:',
              style: Theme.of(context).textTheme.headline6,
            ),
            const SizedBox(height: 10),
            Icon(
              Theme.of(context).brightness == Brightness.dark
                  ? Icons.dark_mode
                  : Icons.light_mode,
              size: 48,
            ),
          ],
        ),
      ),
    );
  }
}

 

여기서 중요한 포인트는 Theme.of(context).brightness를 통해 현재 테마가 다크인지 라이트인지 알 수 있다는 점입니다.


🎚 사용자 설정으로 다크모드 전환하기

이번에는 유저가 직접 버튼을 눌러 테마를 전환할 수 있게 만들어 봅시다. Stateful 위젯으로 수정합니다.

class MyApp extends StatefulWidget {
  const MyApp({super.key});

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

class _MyAppState extends State<MyApp> {
  ThemeMode _themeMode = ThemeMode.light;

  void toggleTheme() {
    setState(() {
      _themeMode = _themeMode == ThemeMode.dark
          ? ThemeMode.light
          : ThemeMode.dark;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '다크모드 데모',
      theme: ThemeData(
        brightness: Brightness.light,
        primarySwatch: Colors.blue,
      ),
      darkTheme: ThemeData(
        brightness: Brightness.dark,
        primarySwatch: Colors.blueGrey,
      ),
      themeMode: _themeMode,
      home: HomePage(toggleTheme: toggleTheme),
    );
  }
}

 

그리고 HomePage는 이렇게 수정:

class HomePage extends StatelessWidget {
  final VoidCallback toggleTheme;

  const HomePage({super.key, required this.toggleTheme});

  @override
  Widget build(BuildContext context) {
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return Scaffold(
      appBar: AppBar(
        title: const Text('다크모드 예제'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              isDark ? '다크모드입니다 🌙' : '라이트모드입니다 ☀️',
              style: Theme.of(context).textTheme.headline6,
            ),
            const SizedBox(height: 20),
            Icon(
              isDark ? Icons.dark_mode : Icons.light_mode,
              size: 48,
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: toggleTheme,
              child: Text(isDark ? '라이트모드로 전환' : '다크모드로 전환'),
            )
          ],
        ),
      ),
    );
  }
}

 

이제 버튼을 눌러서 실시간으로 다크모드를 전환할 수 있게 되었습니다!


🎨 테마 색상 커스터마이징 하기

기본 색상 말고, 우리가 원하는 대로 색상을 바꾸고 싶다면?

ThemeData(
  brightness: Brightness.dark,
  scaffoldBackgroundColor: Colors.black,
  appBarTheme: AppBarTheme(
    backgroundColor: Colors.grey[900],
  ),
  textTheme: const TextTheme(
    bodyText1: TextStyle(color: Colors.white),
  ),
)

 

ThemeData를 이용해 각 컴포넌트의 색상을 내 입맛대로 조정할 수 있어요.


📦 정리

  • theme, darkTheme, themeMode만 설정해도 다크모드 기본 적용 가능
  • Theme.of(context).brightness로 현재 테마 확인 가능
  • Stateful 위젯에서 themeMode 변경하면 실시간 전환 가능
  • ThemeData로 색상 세부 조정 가능

✅ 마무리

Flutter는 기본적으로 다크모드에 강한 프레임워크입니다. 시스템 설정을 따르거나, 사용자가 직접 제어할 수 있도록 만들기도 쉽죠. 다크모드는 이제 선택이 아니라 기본이 된 시대인 만큼, 지금 바로 여러분의 앱에도 적용해보세요!

 

 


StatelessWidget과 StatefulWidget, 뭐가 다른 건데?

Flutter vs React Native: 초보 개발자는 뭘 선택해야 할까?

 

반응형