How to structure a Jetpack Compose project?

Viewed 2932

I am new to Android and Jetpack Compose. With Views screens were defined in different Fragments or Activities, but with Compose it looks like all Screens are defined in the MainAcitivity. What is the best way to structure screen code for different screens when using Compose? Are there any guides to best practices here?

2 Answers

I don't think there is "the best" way to structure your code, it depends on the size of your project and your preferences. But here is how I organize the UI layer of my compose projects:

Jetpack compose project structure

  • screens: contains packages that contain screen-specific components and an eventual view model like home.
  • Navigation.kt: contains the NavHost and other navigation-related utils. I use the navigation-compose library to manage the app navigation.
  • screens/shared: contains classes or/and functions that are not specific to a single screen e.g: reusable components used in different screens or shared view models.
  • MainActivity: set the composable that contains the NavHost as its content.
  • GameResApplication: contains nothing special, I created it because I'm using Hilt.
  • theme: created by Android Studio.
  • utils: some UI utils and fake data that I use in my @Preview composables.

Here is a real project example on github

I guess it's totally up to you and/or your team. I'm using compose in a real multi-module project and following this approach:

  • core/components: common/generic components used by the entire app.
  • core/theme:: classes related to the application theme.
  • [feature]/components: unlike the previous one, this package contains components shared across screens of the same feature. Of course if/when a component is used by two or more features, it should be promoted to the core/components package.
  • [feature]/screens: contains the screens related to a given feature.
  • [feature]/navigation: this is where located the NavHost and other classes related to navigation.
Related