https://kotlinlang.org logo
#compose
Title
# compose
n

Noé Casas

01/21/2021, 9:14 AM
Is there any pattern in Jetpack Compose to add actions to the
TobAppBar
from a Composable that does not have access to it? I am thinking in something like SwiftUI’s
toolbar
and
ToolbarItem
(e.g. see https://swiftwithmajid.com/2020/07/15/mastering-toolbars-in-swiftui/) . Also, is there a mechanism or pattern to set the `TopAppBar`’s title from somewhere else, like SwiftUI’s
navigationTitle
?
j

jim

01/21/2021, 12:43 PM
add actions to the 
TobAppBar
 from a Composable that does not have access to it
As a general rule of thumb, this sentence sounds like an inherent antipattern. Side-effects always look "easy" in quick code snippets, and then when they're all combined together to build a real application then the conglomeration becomes impossible to reason about, which is why we avoid side effects. A widget should not be modifying something it doesn't have access to. If a widget needs access to something (like a data model), that should be passed in explicitly.
💯 2
👍 2
k

Kari Kähkönen

01/21/2021, 1:51 PM
I was struggling with something related a couple of weeks ago. In my case I had a Scaffold (with TopAppBar) and bodyContent that contained NavHost from the Navigation component to display the current screen. I had a composable for a screen that was observing data from a ViewModel, but I also wanted to display some text in the app bar based on the state managed by the ViewModel. I was considering two options: • Just hide the top app bar in the Scaffold when user navigates to this particular screen and have the app bar as part of the screen composable itself • Share the ViewModel with the composables for the top app bar and for the screen. I didn't immediately figure out a clean way to share the ViewModel, though. In the end I didn't need the feature, so I didn't spend much time thinking about it. But I might come back to it in the future.
3 Views