I'm building a Blazor WASM app with MudBlazor and I'm using custom themes for light and dark mode.
The theme provider is in the MainLayout.razor
file:
<MudThemeProvider Theme="@_theme" IsDarkMode="_isDarkMode" />
The _isDarkMode
field is first initialized to null
:
private MudTheme? _theme = null;
But them gets an instance in OnInitialized()
:
protected async override void OnInitialized()
{
base.OnInitialized();
_theme = new()
{
PaletteLight = _lightPalette,
PaletteDark = _darkPalette,
LayoutProperties = new LayoutProperties()
};
}
The themes are defined lower in the same file:
private readonly PaletteLight _lightPalette = new()
{
Black = "#110e2d",
AppbarText = "#424242",
AppbarBackground = "rgba(255,255,255,0.8)",
DrawerBackground = "#ffffff",
GrayLight = "#e8e8e8",
GrayLighter = "#f9f9f9",
};
private readonly PaletteDark _darkPalette = new()
{
Primary = "#7e6fff",
Surface = "#1e1e2d",
Background = "#1a1a27",
BackgroundGray = "#151521",
AppbarText = "#92929f",
AppbarBackground = "rgba(26,26,39,0.8)",
DrawerBackground = "#1a1a27",
ActionDefault = "#74718e",
ActionDisabled = "#9999994d",
ActionDisabledBackground = "#605f6d4d",
TextPrimary = "#b2b0bf",
TextSecondary = "#92929f",
TextDisabled = "#ffffff33",
DrawerIcon = "#92929f",
DrawerText = "#92929f",
GrayLight = "#2a2833",
GrayLighter = "#1e1e2d",
Info = "#4a86ff",
Success = "#3dcb6c",
Warning = "#ffb545",
Error = "#ff3f5f",
LinesDefault = "#33323e",
TableLines = "#33323e",
Divider = "#292838",
OverlayLight = "#1e1e2d80",
};
The problem is, when I refresh any page, the colors change for some reason. The mode (dark/light) stays the same but the colors are a bit brighter in dark mode. Like if they got reset to some default values.
The colors I get after a refresh in the browser:
If I now open the hamburger menu or switch the mode to light and then back to dark the colors get corrected.
What am I doing wrong that the colors are not correct right after the refresh?
Apparently, it was enough to move around these two calls in OnInitialized()
.
It seems that base.OnInitialized()
takes the default theme colors and applies them and then calls StateHasChanged()
to redraw the GUI and I apply my custom colors after that.
I could call StateHasChanged()
again in my code but the result is that I can see the default colors for a split second before my colors are applied. Moving the custom color setting before base.OnInitialized()
solved the issue as now my custom colors are set up before anything else.
MainLayout.razor:
protected async override void OnInitialized()
{
_theme = new()
{
PaletteLight = _lightPalette,
PaletteDark = _darkPalette,
LayoutProperties = new LayoutProperties()
};
base.OnInitialized();
}