Home > Mobile >  Flutter Theme (dark & light)
Flutter Theme (dark & light)

Time:01-24

I am working on an application that contains two modes, Dark and Light Theme, I used extension to check between them as shown unfortunately.

Extension to check theme mode

import 'package:flutter/material.dart';

extension DarkMode on BuildContext {
  bool get isDarkMode {
    final brightness = MediaQuery.of(this).platformBrightness;
    return brightness == Brightness.dark;
  }
}

I also have a separate class that contains both Dark Theme and Light Theme

App theme class

class AppTheme {
  
  static final lightTheme = ThemeData(
    // My light theme
  );
  static final darkTheme = ThemeData(
    // My dark theme
  );

}

In the MaterialApp I put these codes

MaterialApp(
        theme: AppTheme.lightTheme,
        darkTheme: AppTheme.darkTheme,
        themeMode: ThemeMode.system,
        // ...
      ),

Now things work correctly when you change the mod from the phone system, the theme changes perfectly as shown below:

enter image description here

The problem now is when you select the theme, or rather when you put the Light theme, the theme does not work properly. I put an image:

Everything is supposed to change to a light theme, as in the previous video, but it does not happen

MaterialApp(
        theme: AppTheme.lightTheme,
        darkTheme: AppTheme.darkTheme,
        //themeMode: ThemeMode.system,
        themeMode: ThemeMode.light,
        // ...
      ),

enter image description here

I want to know what is wrong and how can I solve that problem so that everything works correctly when switching between each theme.

CodePudding user response:

Try to check on Theme.of(context).brightness instead of MediaQuery.of(this).platformBrightness In your DarkMode extension

  • Related