How to shorten MaterialTheme.colors.primary?

Viewed 61

When coding with compose we use MaterialTheme code so much. Is there a way to shorten this part of the code? for example: mColor.primay

4 Answers

This is less of a Jetpack Compose solution - more of "using Kotlin language features".

You can use the with scope function to make MaterialTheme, which is an object, an implicit receiver. Then you can refer to colors.primary or colors.whatever without saying MaterialTheme.

You can surround the entire enclosing function with a with block:

@Composable
fun foo() {
    with(MaterialTheme) {
        // compose your view here...
        // and you can say "colors.primary" instead of 
        // "MaterialTheme.colors.primary" in here
    }
}

Alternatively, simply use a type alias to make the name MaterialTheme shorter:

typealias MT = MaterialTheme
// now you can say "MT.colors.primary" instead of "MaterialTheme.colors.primary"

I guess this can be done in various ways. One of them being

val mColor
    get() =  @Composable{
        MaterialTheme.colors
    }

usage

mColor().primary

I think the best answer is this:

val mColors: MColor()   @Composable get() = MyTheme.colors

and we can call colors like this: mColors.primary We can do this for typography, shapes and dimensions as well.

You can do it with function.

@Composable
fun materialThemeColor() = MaterialTheme.colors

While using you can use

   color = materialThemeColor().primary
Related