Home > database >  How to make padding reusable for Scaffold content
How to make padding reusable for Scaffold content

Time:11-21

How can I set the content in my Scaffold to be reusable with content padding. Is it possible to extract contentPadding from a composable when I declare it? i.e. MyScaffoldContent

Cannot find a parameter with this name: contentPadding

@Composable
fun MyReusableScaffold(scaffoldTitle: String, scaffoldContent: @Composable () -> Unit) {
    val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()

    Scaffold(
        modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
        topBar = {
            LargeTopAppBar(
                title = { Text(text = scaffoldTitle) },
                scrollBehavior = scrollBehavior
            )
        },
        content = { contentPadding ->
            scaffoldContent(contentPadding = contentPadding)
        }
    )
}

// Example composable
@Composable
fun MyScaffoldContent(
    modifier: Modifier = Modifier,
    contentPadding: PaddingValues = PaddingValues()
) {
    Text(
        text = "Header $item",
        modifier = Modifier.fillMaxWidth()
    )
}

// Example update
@Composable
fun MyHomeScreen(navController: NavController) {
    MyReusableScaffold(
        scaffoldTitle = "Hello Android",
        scaffoldContent = MyScreenContent(contentPadding = ?))
    )
}

@Composable
fun MyScreenContent(modifier: Modifier = Modifier,
    contentPadding: PaddingValues = PaddingValues()) {
    Text(
        text = "Header",
        modifier = Modifier.fillMaxWidth()
    )
}

CodePudding user response:

if you want the MyHomeScreen composable to use the value of the content padding from MyReusableScaffold, you have to define a parameter in the scaffoldContent lambda and pass the contentPadding to it.

@Composable
fun MyReusableScaffold(scaffoldContent: @Composable ( contentPadding: PaddingValues) -> Unit) {
    Scaffold(
        topBar = {

        },
        content = { contentPadding ->
            scaffoldContent(contentPadding = contentPadding)
        }
    )
}

@Composable
fun MyScaffoldContent(
    modifier: Modifier = Modifier,
    contentPadding: PaddingValues = PaddingValues()
) {
    Text(
        text = "Header",
        modifier = Modifier.fillMaxWidth()
    )
}

@Composable
fun MyHomeScreen(navController: NavController) {
    MyReusableScaffold(
        scaffoldContent = {
            MyScreenContent(contentPadding = it)
        }
    )

//    or 
//    MyReusableScaffold(
//        scaffoldContent = {
//            MyScaffoldContent(contentPadding = it)
//        }
//    )
}
  • Related