본문 바로가기
Flutter/Flutter FAQ

Flutter 플러터에서 다크 모드와 라이트 모드를 구현하는 방법은 무엇인가요?, How to implement Dark mode and Light Mode in flutter?

by 베타코드 2023. 6. 12.
반응형

질문


I want to create a flutter app that has 2 light and dark mode themes that change by a switch in-app and the default theme is default android theme.
I need to pass some custom color to the fellow widget and I don't want to just config material theme.

  • how to detect the user device default theme?
  • the secend question is how to provide a theme to the whole app?
  • third is how change the theme with a simple switch in running time?

답변


Material App 사용하기

MaterialApp(
      title: 'App Title',
      theme: ThemeData(
        brightness: Brightness.light,
        /* light theme settings */
      ),
      darkTheme: ThemeData(
        brightness: Brightness.dark,
        /* dark theme settings */
      ),
      themeMode: ThemeMode.dark, 
      /* 시스템 테마를 따르려면 ThemeMode.system, 
         밝은 테마를 사용하려면 ThemeMode.light, 
         어두운 테마를 사용하려면 ThemeMode.dark
      */
      debugShowCheckedModeBanner: false,
      home: YourAppHomepage(),
    );

Cupertino App 사용하기

  1. WidgetsBinding.instance?.window.platformBrightness를 사용하여 어두운 모드를 감지합니다.

  2. 실시간으로 업데이트하려면 WidgetsBindingObserver를 사용하여 시스템에서 밝기 변경을 수신해야 할 수도 있습니다. 그리고 didChangePlatformBrightness();를 재정의합니다.

Cupertino App 예제:

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

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

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  Brightness? _brightness;

  @override
  void initState() {
    WidgetsBinding.instance?.addObserver(this);
    _brightness = WidgetsBinding.instance?.window.platformBrightness;
    super.initState();
  }

  @override
  void dispose() {
    WidgetsBinding.instance?.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangePlatformBrightness() {
    if (mounted) {
      setState(() {
        _brightness = WidgetsBinding.instance?.window.platformBrightness;
      });
    }

    super.didChangePlatformBrightness();
  }

  CupertinoThemeData get _lightTheme =>
      CupertinoThemeData(brightness: Brightness.light, /* light theme settings */);

  CupertinoThemeData get _darkTheme => CupertinoThemeData(
        brightness: Brightness.dark, /* dark theme settings */,
      );

  @override
  Widget build(BuildContext context) {
    return CupertinoApp(
      title: 'Demo App',
      theme: _brightness == Brightness.dark ? _darkTheme : _lightTheme,
      home: MyHomePage(title: 'Demo Home Page'),
    );
  }
}

scoped_model, provider, bloc, 또는 get을 사용하여 원활한 사용자 경험을 제공할 수 있습니다.

반응형

댓글