Skip to content

Instantly share code, notes, and snippets.

@anitaa1990
Created November 30, 2024 18:12
Show Gist options
  • Save anitaa1990/8bb526c4f917f341e06c21551bc6368f to your computer and use it in GitHub Desktop.
Save anitaa1990/8bb526c4f917f341e06c21551bc6368f to your computer and use it in GitHub Desktop.
/**
* A composable function that displays the main notes screen in the app.
* This screen dynamically updates its content based on the UI state provided by the ViewModel.
*
* @param viewModel The ViewModel that provides the state and handles user interactions.
*/
@Composable
fun NotesScreen(
viewModel: NoteViewModel
) {
// Observes the UI state from the ViewModel using StateFlow and lifecycle-aware collection.
val noteUiState = viewModel.notesViewState.collectAsStateWithLifecycle(
lifecycleOwner = LocalLifecycleOwner.current
)
// Provides a title for the app bar.
ProvideAppBarTitle {
Text(
modifier = Modifier
.fillMaxWidth(),
text = stringResource(id = R.string.app_name), // Displays the app name as the title.
style = MaterialTheme.typography.displaySmall,
color = MaterialTheme.colorScheme.onSecondaryContainer
)
}
// Displays a loading indicator if the state indicates loading.
if (noteUiState.value.isLoading) {
LoadingItem()
// Displays an empty screen message if there are no notes to show.
} else if (noteUiState.value.notes.isEmpty()) {
EmptyScreen()
// Displays the list of notes if the state contains notes.
} else {
LazyVerticalStaggeredGrid(
modifier = Modifier.padding(top = 10.dp, bottom = 10.dp, start = 12.dp, end = 12.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp),
columns = StaggeredGridCells.Adaptive(minSize = 140.dp), // Dynamically adjusts columns based on screen size.
) {
val notes = noteUiState.value.notes
items(notes.size) {
val note = notes[it]
NoteItem(
note = note,
onNoteItemClicked = { viewModel.handleIntent(NoteIntent.OpenNoteClicked(it)) }, // Handles note click.
onNoteItemDeleted = { viewModel.handleIntent(NoteIntent.DeleteNote(it)) } // Handles note deletion.
)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment