Tomáš Repčík - 13. 3. 2023

Android Jetpack Compose Silly Mistakes

Silly mistakes, which took me hours to figure out

During learning how to write the Jetpack Compose, I fell into a couple of rabbit holes, from which it was hard to dig out. Of course, most of you will not fall for these traps or will quickly figure it out. But for those lost ones, here are some bright ideas. For brighter ones, here is a laugh or two.

Photo by Jane Almon on Unsplash

1. Launching a preview instead of an app

Imagine you write your first compose screen and are thrilled that it works and looks how it should. With excitement, you go for the next compose screen. Sees it in the preview that everything is looking good. The implementation of the navigation is straightforward. However… you smash the shortcut shift+F10 to launch the app to test it out. After clicking the button to navigate to the second screen, the app crashes with a null exception …

Firstly, I doubted myself. I assumed the incorrect implementation of the navigation. However, I always run the app preview on the first screen, not the actual app…. The app did not know about the second screen, so it crashed as a null exception.

You can learn more here about the navigation in jetpack compose

2. Importing the Material 2.0 theme instead of Material 3.0

I created a new app with a systematized theme around Material 3. I implemented custom colours for the dark and light themes with custom fonts. However, when I tried to design the app settings, every screen component received the default font and white background.

I checked that the root composable containsCustomMaterialTheme { } with custom colours and fonts, but still …, the screen took default colours and fonts, not mine. After forcing Material.colors.primary I noticed that my theme does not contain the colors field but colorScheme.

I mistakenly imported material 2.0 instead of material 3.0…. Just be careful what you import.

* Material 3.0  
import androidx.compose.material3.MaterialTheme  
* Material 2.0  
import androidx.compose.material.MaterialTheme // just number 3 is the differnce

3. Pushing composables out of the screen

Repeatedly, I managed to push the last item out of the screen/row /column. By default, I assumed that child composable would take only the space, which can and is constrained by the parent. However, this does not apply to Spacer(modifier = Modifier.fillMaxWidth()) // or fillMaxHeight. If you place Icon, Spacer and Text together in Row, the Spacer will push out the text outside to take maximal width.

The solution is to eliminate Spacer and use a vertical or horizontal Arrangement of the Row/Column. The second solution is to add weight Spacer(modified = Modifier.weight(1f)) , so the Spacer is constrained by its neighbouring children too.

Thanks for reading, and do forget to follow me for more!

Subscribe for more
LinkedIn GitHub Mail Medium