We just launched Compose Examples featuring over 150+ components! Check it out →

animateFloatingActionButton

Common

Modifier in Material 3 Compose

Apply this modifier to a [FloatingActionButton] to show or hide it with an animation, typically based on the app's main content scrolling.

Last updated:

Installation

dependencies {
   implementation("androidx.compose.material3:material3:1.4.0-alpha02")
}

Overloads

@ExperimentalMaterial3ExpressiveApi
fun Modifier.animateFloatingActionButton(
    visible: Boolean,
    alignment: Alignment,
    targetScale: Float = FloatingActionButtonDefaults.ShowHideTargetScale,
    scaleAnimationSpec: AnimationSpec<Float>? = null,
    alphaAnimationSpec: AnimationSpec<Float>? = null
): Modifier

Parameters

namedescription
visiblewhether the FAB should be shown or hidden with an animation
alignmentthe direction towards which the FAB should be scaled to and from
targetScalethe initial scale value when showing the FAB and the final scale value when hiding the FAB
scaleAnimationSpecthe [AnimationSpec] to use for the scale part of the animation, if null the Fast Spatial spring spec from the [MotionScheme] will be used
alphaAnimationSpecthe [AnimationSpec] to use for the alpha part of the animation, if null the Fast Effects spring spec from the [MotionScheme] will be used

Code Example

AnimatedFloatingActionButtonSample

@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Preview
@Composable
fun AnimatedFloatingActionButtonSample() {
    val listState = rememberLazyListState()
    // The FAB is initially shown. Upon scrolling past the first item we hide the FAB by using a
    // remembered derived state to minimize unnecessary compositions.
    val fabVisible by remember { derivedStateOf { listState.firstVisibleItemIndex == 0 } }

    Scaffold(
        floatingActionButton = {
            MediumFloatingActionButton(
                modifier =
                    Modifier.animateFloatingActionButton(
                        visible = fabVisible,
                        alignment = Alignment.BottomEnd
                    ),
                onClick = { /* do something */ },
            ) {
                Icon(
                    Icons.Filled.Add,
                    contentDescription = "Localized description",
                    modifier = Modifier.size(FloatingActionButtonDefaults.MediumIconSize),
                )
            }
        },
        floatingActionButtonPosition = FabPosition.End,
    ) {
        LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {
            for (index in 0 until 100) {
                item { Text(text = "List item - $index", modifier = Modifier.padding(24.dp)) }
            }
        }
    }
}
by @alexstyl