Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shorten MaterialTheme.colors.primary?

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

like image 887
Reza Faraji Avatar asked Nov 23 '25 17:11

Reza Faraji


1 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"
like image 182
Sweeper Avatar answered Nov 26 '25 22:11

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!