https://kotlinlang.org logo
Title
a

AmrJyniat

11/20/2021, 6:53 AM
How to make 
ScaffoldState
 work with 
CompositionLocalProvider
 to control the drawer open/close from anywhere in my fragment?
b

Bradleycorn

11/21/2021, 2:34 PM
In general, you probably don’t want to use a
CompositionLocal
for something like that. Instead, pass a callback function down the compose tree. When you have some ui element that needs to open/close the drawer, it can call the callback and your top level composable that owns the ScaffoldState can update it to toggle the drawer
a

AmrJyniat

11/21/2021, 4:57 PM
I think
CompositionLocal
created in core to avoid passing callbacks all the way down tree.
b

Bradleycorn

11/22/2021, 12:37 PM
You probably could do it that way, but IMO it would be very brittle and your composables would not really be very re-useable, because they depend on the existence of the
CompositionLocal
. As developers, I think we sometimes think of callback functions as a bad thing (probably because of the proliferation of the term “callback hell”). But they aren’t always bad. And with compose I think we have to get used to the idea of passing callback lambda functions (for all kinds of things) as parameters on our composable functions, and we have to learn that those callbacks lambdas are not a bad thing. It’s something that we’re going to have to do a lot to adhere to the unidirectional data flow and no-side-effects patterns that Compose enforces encourages. In fact, my guess is that when the Android team renamed
Ambient
to
CompositionLocal
, they included the word “Local” in the name on purpose to clearly indicate that we probably should not use it in a Global fashion. And that’s what we’d be doing in this case. It’s setting up a
CompositionLocal
that is not local at all, and works like a Global variable used to control a navigation drawer.
a

AmrJyniat

11/22/2021, 1:16 PM
Yah your idea about
CompositionLocal
actually right, but here I wouldn't re-use the fun in anywhere else because it's a drawer which exists only in home screen so I guess I can benefit from
CompositionLocal
in such cases.