Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpackandroid-developer-api

How to add more items to a static list in Jetpack Compose?


How can I add more elements to the static list in the jetpack compose

@OptIn(ExperimentalFoundationApi::class)
@Composable 
fun AddNotesToList(notesList: List<String>) { 
    val listState = rememberScrollState() 
    Log.d("TAG", notesList.toString()) 
    LazyColumn() { 
        items(notesList.size) { 
            Box(contentAlignment = Alignment.Center, 
                modifier = Modifier
                    .padding(start = 15.dp, top = 15.dp, bottom = 1.dp, end = 15.dp)
                    .fillMaxSize() .horizontalScroll(listState)
                    .background(Color.White)
                    .clip(RoundedCornerShape(10.dp)) .padding(15.dp)
                    .animateItemPlacement(animationSpec = tween(1000))) { 
                        Text(text = notesList[it], 
                            color = Color.Black, 
                            modifier = Modifier.align( Alignment.BottomCenter)
                                .animateItemPlacement(animationSpec = tween(10000)))
            }
        }
    }
} 

this is my addition to the Ui function, this is now I add elements

AddNotesToList(notesList = listOf(
    "Drink water", 
    "Read Books", 
    "Eat fruits", 
    "Go for a Walk", 
    "Drink water", 
    "Read Books", 
    "Eat fruits", 
    "Go for## Heading ## a Walk", 
    "Go for a Walk", 
    "Drink water", 
    "Read Books", 
    "Eat fruits", 
    "Go for a Walk"))

now I want to add one more element and I am trying this function

@Composable 
fun AddNewNote(noteDescription: String) {
    Log.d("noteDescription", noteDescription) 
    AddNotesToList(notesList = listOf(noteDescription))
}

Solution

  • Solution:

    val _noteList = remember { MutableStateFlow(listOf<String>()) }
    val noteList by remember { _noteList }.collectAsState()
    
    // Add note
    fun addItem(item: String) {
        val newList = ArrayList(noteList)
        newList.add(yourItem)
        _noteList.value = newList
    }
    

    And then you can pass noteList to your LazyColumn