Punpuf
Punpuf

Reputation: 2144

Jetpack Compose Bottom Sheet initialization error

In Jetpack compose 1.0.0-beta01, I am calling the BottomSheetScaffold like this:

BottomSheetScaffold(
    scaffoldState = bottomSheetScaffoldState,
    sheetContent = { Text("") },
    sheetShape = Shapes.large,
    backgroundColor = AppTheme.colors.uiBackground,
    modifier = modifier
    
) { (content) }

... and getting the following error:

java.lang.IllegalArgumentException: The initial value must have an associated anchor.

Any tips on fixing this?

Upvotes: 23

Views: 18866

Answers (5)

João Eudes Lima
João Eudes Lima

Reputation: 895

On new version, this error happens when the initial State is Expanded, where try to open the Modal before launched. Try launcher via ModalBottomSheetState from LaunchedEffect (maybe can need a delay)

Upvotes: 1

Tink
Tink

Reputation: 636

I got the same issue when using ModalBottomSheetLayout, and my compose material version is 1.2.0-rc02 androidx.compose.material:material:1.2.0-rc02 I want to show the bottom modal when one item is selected, and if no item is selected, the modal should be empty.

ModalBottomSheetLayout(
    sheetState = modalBottomSheetState,
    sheetContent = {
        EditProgressContent(book = book)
    }
) { ... }

@Composable
fun EditProgressContent(book: Book?) {
    if (book == null) return
    Text(book.title)
}

When book is null, I got the same crash. There is no peekHeight parameter for ModalBottomSheetLayout, so I have to add a pixel when book is null

@Composable
fun EditProgressContent(book: Book?) {
    if (book == null) { 
        Box(modifier = Modifier.size(1.dp)
        return
    }
    Text(book.title)
}

The code looks silly, hope it can be fixed from Google.

Upvotes: 5

Muse
Muse

Reputation: 460

When bottomSheetState is expand, sheetContent must have real content to show.

You need check this.

Upvotes: 20

jendress
jendress

Reputation: 169

In case you end up on this page because you use the BackdropScaffold, the suggested solution does the trick as well. Simply set the peekHeight. For example like this:

BackdropScaffold(
        appBar = {},
        backLayerContent = {},
        frontLayerContent = {},
        peekHeight = 0.dp
    )

Then Preview works like a charm again.

Fun fact though: Don't set it to 56.dp which is the default init value it normally should be initialised with (value of BackdropScaffoldDefaults.PeekHeight). 56.dp results in the anchor rendering problem in my current setup. (Using compose version '1.1.1')

Upvotes: 1

Punpuf
Punpuf

Reputation: 2144

Don't forget to add the following atribute:

sheetPeekHeight = 0.dp

So your code should be like this:

BottomSheetScaffold(
    scaffoldState = bottomSheetScaffoldState,
    sheetContent = { Text("") },
    sheetShape = Shapes.large,
    sheetPeekHeight = 0.dp, // <--- new line
    backgroundColor = AppTheme.colors.uiBackground,
    modifier = modifier
    
) { (content) }

Upvotes: 15

Related Questions