Android: Migrate compose theme from Material 2 to 3 and nesting themes in multi-module app

177 views Asked by At

Migrating compose Material theme from 2 to 3 is pretty straightforward and described in the docs. They say that you create M3 theme and just migrate your composable by components and/or by screens (so called phased-migration). They also say you shouldn't keep both M2 and M3 themes together for too long (makes sense so far).

Now, what does this mean exactly? You can either wrap one theme in another for the time being M3 { M2 {} } or (to avoid nesting themes) pretty much duplicate all your custom composable components and have both versions for M2 and M3.

Option 1: nest themes and your composables will use either androidx.compose.material or androidx.compose.material3 based on import applying both themes respectively since they are nested.

    androidx.compose.material.MaterialTheme(
        colors = ... // M2 theme specific stuff
    ) {
      androidx.compose.material3.MaterialTheme(
          colorScheme = ... // M3 theme specific stuff
      ) {
        // content
      }
    }

Option 2: duplicate your components that are used in screens and then use one or the other theme. Each one of them can be used in the correspondent screen otherwise your theming will be broken.

@Composable
fun MyComponentforM2() { 
  androidx.compose.material.Text(text = "Text")
}

@Composable
fun MyComponentforM3() { 
  androidx.compose.material3.Text(text = "Text")
}

Option 1 seems more reasonable. I tried to find some info about possible conflicts when nesting themes - seems unlikely, because they come from different dependencies, right?. They could use the same foundation (and they do i.e. ripple). Also I'm not sure if there is any big performance impact, but the documentation does not say anything about it.

So, could option 1 be considered anti-pattern or any of those 2 could be considered as phased migration? Of course, the ultimate goal in both cases would be to get rid of M2 from the app.

This question is a bit related to this.

0

There are 0 answers