Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading