【问题标题】:Screen Flashes when using datastore to update UI使用数据存储更新 UI 时屏幕闪烁
【发布时间】:2023-01-26 08:10:59
【问题描述】:

我正在使用 Jetpack Compose 构建我的 UI,当用户进入该应用程序时,该应用程序将首先检查他/她是否是新用户。

如果它是第一次使用,它将加载 ScreenStarter() 可组合项。否则,它将加载 AppContent() 可组合项。

我的代码是这样的:

应用程序.kt

 {
    /**
     * This is the Main MES app that will
     * determine which screen content to show
     **/

    /** Load the app settings from datastore **/
    val appSettings = application.datastore.data.collectAsState(initial = MesAppSettings()).value

    /** Set the correct app theme that the user has set **/
    val darkTheme = when (appSettings.appTheme) {
        AppTheme.FOLLOW_SYSTEM -> isSystemInDarkTheme()
        AppTheme.DARK -> true
        AppTheme.LIGHT -> false
    }

    MesTheme(
        darkTheme = darkTheme // Load the app theme
    ) {

        
        /** Determine screen content **/
        if (!appSettings.isFirstTimeLogging) {
            AppContent(
                application = application,
                appSettings = appSettings,
                widthSizeClass = widthSizeClass
            )
        } else {
            ScreenStarter(
                application = application,
                requestMultiplePermissions = requestMultiplePermissions
            )
        }

    }
}

这里的问题是,如果它是经常性用户并且他/她打开应用程序,屏幕会闪烁,我们可以在切换到 AppContent() 可组合项之前短暂地看到 ScreenStarter() 可组合项。我认为发生这种情况是因为数据是从数据存储中异步获取的。

有人可以建议如何解决这个问题吗?

【问题讨论】:

    标签: android kotlin android-jetpack-compose android-jetpack-compose-material3 android-jetpack-datastore


    【解决方案1】:

    为 appSettings 使用一些不同的初始值。例如,您可以使用null,然后如果appSettings 为空,则显示空白屏幕或一些进度指示器,如果它不为空,则您知道已从存储中加载正确的数据,您可以根据您的逻辑显示内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-17
      • 2011-01-06
      • 2015-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      • 1970-01-01
      相关资源
      最近更新 更多