LazyColumn with key, when showing keyboard it is hiding last item

I am trying to implement a chat screen that works the same way as the JetChat compose sample. However when I modify the code to use a Flow I am getting an issue

The issue is that when working with a key inside a LazyColumn, the keyboard will overflow / hide the last item in the LazyColumn. I think the issue is related to LazyColumn when using reverseLayout = true

The keyboard does not hide when I don’t include a key, so this feels like a bug in the framework.

I’ve included a stripped down version of the code, which should be runnable, to show the issue

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject

// setting this to 1 above our initial values
private const val INIT_ID = 8

@Composable
fun ChatBugDevScreen(
    viewModel: ChatBugViewModel = hiltViewModel(),
) {

    // we are using a unique key for id, so this should not cause an issue
    var currentId by remember { mutableStateOf(INIT_ID) }

    val uiState: ChatBugUiState by viewModel.uiState.collectAsState()

    when (uiState) {
        ChatBugUiState.Initial -> {
            Column {
            }
        }

        is ChatBugUiState.Success -> {

            Column(Modifier.fillMaxSize()) {
                ChatBugMessages(
                    (uiState as ChatBugUiState.Success).data,
                    modifier = Modifier.weight(1f),
                )

                ChatBugInput(
                    onMessageSent = { content ->
                        currentId += 1
                        viewModel.addMessage(ChatBugMessage(currentId, content))
                    }
                )
            }
        }
    }
}

@Composable
private fun ChatBugMessages(
    messages: List<ChatBugMessage>,
    modifier: Modifier = Modifier
) {

    // sorting the list in decending order, to work with reverseLayout
    val sortedMessages = messages.sortedByDescending { it.id }

    Box(modifier = modifier) {
        LazyColumn(reverseLayout = true, modifier = Modifier.fillMaxSize()) {

            // ISSUE: If you use the items without the key, then the keyboard does not hide the last item
            //  if you use the items with a key the keyboard does hide the last item

            items(sortedMessages) { message ->
            //items(sortedMessages, key = { message -> message.id }) { message ->
                Row {
                    Text(
                        text = message.message,
                        fontSize = 40.sp,
                        color = Color.White
                    )
                }
            }
        }
    }
}

@Composable
private fun ChatBugInput(
    onMessageSent: (String) -> Unit,
    modifier: Modifier = Modifier,
) {

    var textState by rememberSaveable(stateSaver = TextFieldValue.Saver) {
        mutableStateOf(TextFieldValue())
    }

    Surface(tonalElevation = 2.dp) {
        Column(modifier = modifier) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(64.dp),
                horizontalArrangement = Arrangement.End
            ) {
                Box(Modifier.fillMaxSize()) {
                    BasicTextField(
                        value = textState,
                        onValueChange = { textState = it },
                        modifier = modifier
                            .padding(start = 32.dp)
                            .align(Alignment.CenterStart),
                        keyboardOptions = KeyboardOptions(
                            keyboardType = KeyboardType.Text,
                            imeAction = ImeAction.Send
                        ),
                        keyboardActions = KeyboardActions {
                            if (textState.text.isNotBlank()) {
                                onMessageSent(textState.text)
                                textState = TextFieldValue()
                            }
                        },
                        maxLines = 1,
                    )
                }
            }

        }
    }
}

@HiltViewModel
class ChatBugViewModel
@Inject
constructor() : ViewModel() {

    // ISSUE: This issue only occurs when using a Flow
    private val _messagesFlow: MutableStateFlow<List<ChatBugMessage>> = MutableStateFlow(emptyList())
    private val messagesFlow: Flow<List<ChatBugMessage>> = _messagesFlow

    // if the code is the below then you do not get the hidden keyboard, however this does not have the functionality
    // of the flow
    // private val _messages: MutableList<ChatBugMessage> = initialMessages.toMutableStateList()
    // val messages: List<ChatBugMessage> = _messages

    val uiState: StateFlow<ChatBugUiState> = messagesFlow.map { messagesFlow ->
        ChatBugUiState.Success(messagesFlow)
    }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(),
            initialValue = ChatBugUiState.Initial,
        )

    init {

        val initialMessages = listOf(
            ChatBugMessage(1, "initial 1"),
            ChatBugMessage(2, "initial 2"),
            ChatBugMessage(3, "initial 3"),
            ChatBugMessage(4, "initial 4"),
            ChatBugMessage(5, "initial 5"),
            ChatBugMessage(6, "initial 6"),
            ChatBugMessage(7, "initial 7")
        )

        _messagesFlow.value = initialMessages + _messagesFlow.value
    }

    fun addMessage(msg: ChatBugMessage) {
        _messagesFlow.value = listOf(msg) + _messagesFlow.value
    }
}

data class ChatBugMessage(
    val id: Int,
    val message: String,
)

sealed interface ChatBugUiState {
    data object Initial : ChatBugUiState
    data class Success(val data: List<ChatBugMessage>) : ChatBugUiState
}


Has anyone else had this issue, it feels like something that should just work as long as I’m adding to the Flow correctly and including unique id’s

2

I’ve raised a bug request with the compose team for this https://issuetracker.google.com/issues/363189652

As a workaround you can add Scroll to last item with a delay

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

// setting this to 1 above our initial values
private const val INIT_ID = 8

@Composable
fun ChatBugDevScreen(
    viewModel: ChatBugViewModel = hiltViewModel(),
) {

    // we are using a unique key for id, so this should not cause an issue
    var currentId by remember { mutableStateOf(INIT_ID) }
    // scrollState is included here simply incase it is part of the solution
    val scrollState = rememberLazyListState()

    val scope = rememberCoroutineScope()

    val uiState: ChatBugUiState by viewModel.uiState.collectAsState()

    when (uiState) {
        ChatBugUiState.Initial -> {
            Column {
            }
        }

        is ChatBugUiState.Success -> {

            Column(Modifier.fillMaxSize()) {
                ChatBugMessages(
                    (uiState as ChatBugUiState.Success).data,
                    modifier = Modifier.weight(1f),
                    scrollState = scrollState,
                )

                ChatBugInput(
                    onMessageSent = { content ->
                        currentId += 1
                        viewModel.addMessage(ChatBugMessage(currentId, content))

                        scope.launch {
                            
                            // HACK, you need the delay here otherwise it still does not show the last item
                            delay(20)
                            scrollState.scrollToItem(0)
                        }

                    }
                )
            }
        }
    }
}

@Composable
private fun ChatBugMessages(
    messages: List<ChatBugMessage>,
    scrollState: LazyListState,
    modifier: Modifier = Modifier
) {

    // sorting the list in decending order, to work with reverseLayout
    val sortedMessages = messages.sortedByDescending { it.id }

    Box(modifier = modifier) {
        LazyColumn(reverseLayout = true,
            state = scrollState,
            modifier = Modifier
                .fillMaxSize()
        ) {

            // ISSUE: If you use the items without the key, then the keyboard does not hide the last item
            //  if you use the items with a key the keyboard does hide the last item

            // items(sortedMessages) { message ->
            items(sortedMessages, key = { message -> message.id }) { message ->
                Row {
                    Text(
                        text = message.message,
                        fontSize = 40.sp,
                        color = Color.White
                    )
                }
            }
        }
    }
}

@Composable
private fun ChatBugInput(
    onMessageSent: (String) -> Unit,
    modifier: Modifier = Modifier,
) {

    var textState by rememberSaveable(stateSaver = TextFieldValue.Saver) {
        mutableStateOf(TextFieldValue())
    }

    Surface(tonalElevation = 2.dp) {
        Column(modifier = modifier) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(64.dp),
                horizontalArrangement = Arrangement.End
            ) {
                Box(Modifier.fillMaxSize()) {
                    BasicTextField(
                        value = textState,
                        onValueChange = { textState = it },
                        modifier = modifier
                            .padding(start = 32.dp)
                            .align(Alignment.CenterStart),
                        keyboardOptions = KeyboardOptions(
                            keyboardType = KeyboardType.Text,
                            imeAction = ImeAction.Send
                        ),
                        keyboardActions = KeyboardActions {
                            if (textState.text.isNotBlank()) {
                                onMessageSent(textState.text)
                                textState = TextFieldValue()
                            }
                        },
                        maxLines = 1,
                    )
                }
            }

        }
    }
}

@HiltViewModel
class ChatBugViewModel
@Inject
constructor() : ViewModel() {

    // ISSUE: This issue only occurs when using a Flow
    private val _messagesFlow: MutableStateFlow<List<ChatBugMessage>> = MutableStateFlow(emptyList())
    private val messagesFlow: Flow<List<ChatBugMessage>> = _messagesFlow

    // if the code is the below then you do not get the hidden keyboard, however this does not have the functionality
    // of the flow
    // private val _messages: MutableList<ChatBugMessage> = initialMessages.toMutableStateList()
    // val messages: List<ChatBugMessage> = _messages

    val uiState: StateFlow<ChatBugUiState> = messagesFlow.map { messagesFlow ->
        ChatBugUiState.Success(messagesFlow)
    }
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(),
            initialValue = ChatBugUiState.Initial,
        )

    init {

        val initialMessages = listOf(
            ChatBugMessage(1, "initial 1"),
            ChatBugMessage(2, "initial 2"),
            ChatBugMessage(3, "initial 3"),
            ChatBugMessage(4, "initial 4"),
            ChatBugMessage(5, "initial 5"),
            ChatBugMessage(6, "initial 6"),
            ChatBugMessage(7, "initial 7")
        )

        _messagesFlow.value = initialMessages + _messagesFlow.value
    }

    fun addMessage(msg: ChatBugMessage) {
        _messagesFlow.value = listOf(msg) + _messagesFlow.value
    }
}

data class ChatBugMessage(
    val id: Int,
    val message: String,
)

sealed interface ChatBugUiState {
    data object Initial : ChatBugUiState
    data class Success(val data: List<ChatBugMessage>) : ChatBugUiState
}


Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật