I want to pass custom model list to glance widget but when i send to list and update widget then widget is re-creating.How can i pass custom model list to glance widget.My github project url in below.The purpose of my project is list of last 10 post on reddit androiddev channel https://github.com/mehmetpeker/Jetpack-Glance-Reddit-Widget
How to pass custom model list to Jetpack Glance Widget?
882 Views Asked by Mehmet Peker At
2
There are 2 best solutions below
0

There is a great article how to deal with this: https://proandroiddev.com/building-app-widgets-with-glance-8278cb455afa
When you look at the chapter Managing state, you will get some background, but transformed to code.
In your AppWidget class (the one with Composable):
override val stateDefinition = AppGlanceStateDefinition
AppGlanceStateDefinition might look like this:
object AppGlanceStateDefinition : GlanceStateDefinition<Preferences> {
private const val FILE_NAME = "app_widget_store"
private val Context.dataStore: DataStore<Preferences>
by preferencesDataStore(name = FILE_NAME)
override suspend fun getDataStore(context: Context, fileKey: String): DataStore<Preferences> {
return context.dataStore
}
override fun getLocation(context: Context, fileKey: String): File {
return File(context.applicationContext.filesDir, "datastore/$FILE_NAME")
}
}
You can use also ProtoBuf DataStore, if you want to store more complex objects.
Now in Content method you can get a state from preferences.
@Composable
override fun Content() {
val state = currentState<Preferences>()
. . .
}
Of course don't forget to call update (with update(<widgetId>)
or updateAll()
) widget whenever you update the preferences.
GlanceAppWidgetManager(context).getGlanceIds(AppWidget::class.java).forEach { glanceId ->
updateAppWidgetState(context, glanceId) { prefs ->
prefs[stringPreferencesKey("list")] = jsonList
}
}
AppWidget().updateAll(context)
Currently, Jetpack Glance's lists only accept the elements enumerated at construction time. If you want to update the list, you can update the whole App Widget. Remember that you can request an update of the App Widget from anywhere in your app.