ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Riverpod] Riverpod으로 Theme관리
    플러터/Packages 2024. 5. 22. 16:58

    Riverpod으로 theme를 관리하고 싶었다.

    MaterialApp의 경우 themeMode가 있고, themeMode의 경우 system, light, dark 3가지 값을 가진다.

    themeMode의 값에 따라 화면의 테마를 바꿔준다.

    1. 컬러 설정

    테스트를 위해 간단하게 설정

    import 'package:flutter/material.dart';
    
    class AppColors {
      static const Color primary = Colors.blueAccent;
      static const Color secondary = Colors.blueGrey;
      static const Color error = Colors.redAccent;
      static const Color black = Colors.black;
      static const Color white = Colors.white;
    }
    

    2. Theme 설정

    dart, light theme 설정

    class AppTheme {
      static ThemeData get darkTheme {
        return ThemeData(
          brightness: Brightness.dark,
          primaryColor: AppColors.primary,
          colorScheme: const ColorScheme.dark(
            primary: AppColors.primary,
            secondary: AppColors.secondary,
            error: AppColors.error,
            surface: AppColors.black,
          ),
          scaffoldBackgroundColor: AppColors.black,
          appBarTheme: const AppBarTheme(
            elevation: 0,
            backgroundColor: AppColors.black,
          ),
        );
      }
    
      static ThemeData get lightTheme {
        return ThemeData(
          brightness: Brightness.light,
          primaryColor: AppColors.primary,
          colorScheme: const ColorScheme.light(
            primary: AppColors.primary,
            secondary: AppColors.secondary,
            error: AppColors.error,
            surface: AppColors.black,
          ),
          appBarTheme: const AppBarTheme(
            elevation: 0,
            backgroundColor: AppColors.primary,
          ),
        );
      }
    }
    

    3. theme provider 설정

    theme의 값을 가지는 provider을 만든다.

    상태값 캡슐화를 위해 StateNotifierProvider 사용.

    final themeProvider = StateNotifierProvider<ThemeModeNotifier, ThemeMode>((ref) {
      return ThemeModeNotifier();
    });
    
    class ThemeModeNotifier extends StateNotifier<ThemeMode> {
      ThemeMode currentTheme = ThemeMode.light;
    
      ThemeModeNotifier() : super(ThemeMode.light);
    
      void toggleTheme() {
        state = (state == ThemeMode.light) ? ThemeMode.dark : ThemeMode.light;
      }
    }
    

    4. theme provider 사용

    theme를 받아와 themeMode에 넣어준다.

    @override
    Widget build(BuildContext context, WidgetRef ref) {
      var theme = ref.watch(themeProvider);
    
      return MaterialApp(
        theme: AppTheme.lightTheme,
        darkTheme: AppTheme.darkTheme,
        themeMode: theme,
        home: const MyHomePage(),
      );
    }
    

    5. 실행 화면

    floatingbutton을 누르면 태마 바꿔준다.

     

     

    github : https://github.com/zerg0088/theme_riverpod

Designed by Tistory.