Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access shared preferences in Composable function?

I am migrating from multiple activity compose project to a single activity compose project.

While migrating I have found that I am using shared preferences in multiple screens (Now composable functions)

Passing shared preference object as a parameter to each composable seems tedious is there any better way to do it?

like image 928
nayan dhabarde Avatar asked Jul 28 '26 11:07

nayan dhabarde


1 Answers

You don't.

Composable functions' purpose is only to compose the screen and handle UI events (clicks, scrolls, etc.).

You need to use your shared preferences from a view model and expose a state to the composable function, that state will be updated by the shared preferences and will automatically tigger recomposition the screen.

Read State and Jetpack Compose, especially this about states, and this how to use states with view models.

like image 104
Shlomi Katriel Avatar answered Jul 30 '26 23:07

Shlomi Katriel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!