Normal and Dark Mode implementation on both Android and iOS without the flashes using Xamarin.Forms 4.3.0.947036

走远了吗. 提交于 2019-12-13 03:39:36

问题


After some discussion on the Original Post, we needed to open a new question for its answer due to an issue found with iOS.


The Problem:

After attempting this and troubleshooting the results, the iOS async code doesn't work correctly. While Android works ok, the code below in App() doesn't seem to work correctly for iOS, as I apparently can't have await-ables in the App() which is needed to get the coloring correct when navigating.

Theme theme = await DependencyService.Get<IEnvironment>().GetOperatingSystemTheme();

even when using _ = GetOperatingSystemTheme().ConfigureAwait(true); in the App() the code isn't called, and therefore the Theme isn't set:

public static async Task<Theme> GetOperatingSystemThemeAsync()
{
    Theme systemTheme = await DependencyService.Get<IEnvironment>().GetOperatingSystemTheme().ConfigureAwait(true);

    SetTheme(systemTheme);
    return systemTheme;

}

And the Issue when trying to use it for iOS:

Using this non-async Environment_iOS code and the SetTheme() at Line 53 of the App.cs I got a

System.NullReferenceException Message=Object reference not set to an instance of an object". at the line "UIViewController rootController = UIApplication.SharedApplication.KeyWindow.RootViewController;

If you don't call it in App() and instead in only in App.OnStart(), this flashing issue occurs.

Troubleshooting Results:

Whatever the default is in your app, that will flash when navigation occurs, In other words, a default white background will flash before the page is rendered to dark mode. Setting the defaults (whatever colors for the background needed. i.e. App.Current.Resources = new DarkModeTheme() for dark pages) before the page is called (i.e. SomePage()) gives the correct results as it must be done before navigation occurs and the page is rendered.

Example Repository: https://github.com/Jakar510/FlickerTest


回答1:


Problem

UIApplication.SharedApplication.KeyWindow is null because Xamarin.Forms hasn't yet generated it.

Solution

Move the call to UIApplication.SharedApplication.KeyWindow from the constructor of Xamarin.Forms.Application to Xamarin.Forms.Application.OnStart().

I also sent you a PR which implements this fix and also correctly implements MergedDictionaries for your Light Theme and Dark Theme: https://github.com/Jakar510/FlickerTest/pull/1



来源:https://stackoverflow.com/questions/58738368/normal-and-dark-mode-implementation-on-both-android-and-ios-without-the-flashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!