Вот мой полный код:
Код: Выделить всё
data class Note(
val text: String = ""
)
data class UiState(
val notes: List
)
class NoteRepository {
private val notes = mutableListOf()
fun getNotes(): List = notes
fun addNote(note: Note) {
notes.add(note)
}
}
class NoteViewModel : ViewModel() {
private val repository = NoteRepository()
private val _uiState = MutableStateFlow(UiState(repository.getNotes()))
val uiState: StateFlow = _uiState.asStateFlow()
fun addNote(note: Note) {
repository.addNote(note)
// Logging to check the state update
Log.d("NoteViewModel", "Notes list: ${repository.getNotes()}")
//_uiState.value = uiState.value.copy(notes = repository.getNotes())
_uiState.value = UiState(repository.getNotes())
}
}
@Composable
fun Board(modifier: Modifier = Modifier, viewModel: NoteViewModel) {
val uiState by viewModel.uiState.collectAsState()
Box(modifier = Modifier
.fillMaxSize()
.then(modifier)
) {
Button(
onClick = { viewModel.addNote(Note()) },
modifier = Modifier.align(Alignment.BottomEnd)
) {
Text(text = "Add")
}
Column {
uiState.notes.forEach { _ ->
Box(
modifier = Modifier
.padding(6.dp)
.size(20.dp)
.background(Color.Blue)
)
}
}
}
}
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
NoteTheme {
Board(viewModel = viewModel())
}
}
}
}
Изменить
Использование mutableStateListOf вместо mutableListOf в классе репозитория решает проблему:
Код: Выделить всё
private val notes = mutableStateListOf()
Подробнее здесь: https://stackoverflow.com/questions/787 ... ate-update