LazyColumn item, Unit cant be called in this context by implicit receiver - android

I have the next code, everything is fine except that I need to put my second AnswerOption in a lazyverticalGrid.
Which i cant do it, because its inside a lazycolumn this is the code
#Composable
fun AssessmentScreen(
onClose: (String, String) -> Unit,
relatedSubSkillIdsJson: String,
uiState: AssessmentUiState,
onSelectedOption: (String) -> Unit,
onShowAnswerFeedback: (Boolean) -> Unit,
onNextQuestion: () -> Unit,
onCloseAssessment: () -> Unit,
navigateToAndPop: (Pair<String, String>) -> Unit,
goBack: () -> Unit,
assessmentType: String,
) {
val context = LocalContext.current
val activity = context.findActivity()
val navigationBarHeightDp = activity?.getNavigationBarHeightInDp() ?: 0.dp
val blur =
if (uiState.isLoading) dimensionResource(dimen.default_screen_blur) else 0.dp
val currentArtiIndex = remember { mutableStateOf(0) }
if (uiState.questions.isNotEmpty()) {
LazyColumn(
Modifier
.fillMaxSize()
.padding(
top = dimensionResource(dimen.default_screen_padding),
start = dimensionResource(dimen.default_screen_padding),
end = dimensionResource(dimen.default_screen_padding)
)
.blur(blur)
) {
item {
CloseAssessment(
relatedSubSkillIdsJson = relatedSubSkillIdsJson,
uiState = uiState,
questionIndex = uiState.currentQuestionIndex,
isAnsweredQuestion = uiState.showAnswerFeedback,
onCloseAssessment = { onCloseAssessment() },
navigateToAndPop = navigateToAndPop,
goBack = goBack
)
AssessmentTitle(artiImages[currentArtiIndex.value], assessmentType)
QuestionDotsIndicator(uiState.questionAnswersStatus)
AssessmentQuestion(
thumbnail = uiState.getCurrentQuestionItem().thumbnail,
question = uiState.getCurrentQuestionItem().question
)
Spacer(modifier = Modifier.height(20.dp))
}
val optionsAbcLetterDescription = ('a'..'z').toList()
itemsIndexed(uiState.currentAnswerOptions) { index, option ->
if (uiState.currentAnswerOptions[index].thumbnail == ""){
AnswerOption(
selectedOptionId = uiState.selectedAnswerId,
showFeedback = uiState.showAnswerFeedback,
optionLetter = circularCharIteration(optionsAbcLetterDescription, index),
option = option,
onSelectedOption = { onSelectedOption(it) }
)
}else{
AnswerOption(
selectedOptionId = uiState.selectedAnswerId,
showFeedback = uiState.showAnswerFeedback,
optionLetter = circularCharIteration(optionsAbcLetterDescription, index),
option = option,
onSelectedOption = { onSelectedOption(it) }
)
}
}
item {
ChallengeBtn(
modifier = Modifier
.padding(bottom = navigationBarHeightDp + dimensionResource(dimen.default_screen_padding)),
uiState = uiState,
navigateToAndPop = navigateToAndPop,
onShowAnswerFeedback = { onShowAnswerFeedback(it) },
onCloseAssessment = { onCloseAssessment() },
onNextQuestion = {
if (!uiState.isLastQuestion) {
currentArtiIndex.value =
nextArtiImage(currentArtiIndex.value)
onNextQuestion()
}
} ,
relatedSubSkillIdsJson = relatedSubSkillIdsJson,
)
}
}
}
ProgressBarComponentComposable(isLoading = uiState.isLoading)
any idea on how to do it?

wrap it inside item{…} block
...
val optionsAbcLetterDescription = ('a'..'z').toList()
itemsIndexed(uiState.currentAnswerOptions) { index, option ->
if (uiState.currentAnswerOptions[index].thumbnail == "") {
this#LazyColumn.item { // item block
AnswerOption(
...
)
}
} else {
this#LazyColumn.item { // item block
AnswerOption(
...
)
}
}
...
or you can make the AnswerOption an extension of LazyItemScope,
#Composable
fun LazyItemScope.AnswerOption() {...}
and you can simply call it like this
...
val optionsAbcLetterDescription = ('a'..'z').toList()
itemsIndexed(uiState.currentAnswerOptions) { index, option ->
if (uiState.currentAnswerOptions[index].thumbnail == "") {
AnswerOption(
...
)
} else {
AnswerOption(
...
)
}
...

Related

Hide LaodingView when search have no result

I have implemented search functionality in my app which display result as a verticalGridView with pagination : https://github.com/alirezaeiii/TMDb-Compose
I have following logic for refresh load state that works as I wish :
#Composable
fun <T : TMDbItem> PagingScreen(
viewModel: BasePagingViewModel<T>,
onClick: (TMDbItem) -> Unit,
) {
val lazyTMDbItems = viewModel.pagingDataFlow.collectAsLazyPagingItems()
when (lazyTMDbItems.loadState.refresh) {
is LoadState.Loading -> {
TMDbProgressBar()
}
is LoadState.Error -> {
val message =
(lazyTMDbItems.loadState.refresh as? LoadState.Error)?.error?.message ?: return
lazyTMDbItems.apply {
ErrorScreen(
message = message,
modifier = Modifier.fillMaxSize(),
refresh = { retry() }
)
}
}
else -> {
LazyTMDbItemGrid(lazyTMDbItems, onClick)
}
}
}
In LazyTMDbItemGrid, I try to manage append load state as follow :
#Composable
private fun <T : TMDbItem> LazyTMDbItemGrid(
lazyTMDbItems: LazyPagingItems<T>,
onClick: (TMDbItem) -> Unit,
) {
LazyVerticalGrid(
columns = GridCells.Fixed(COLUMN_COUNT),
contentPadding = PaddingValues(
start = Dimens.GridSpacing,
end = Dimens.GridSpacing,
bottom = WindowInsets.navigationBars.getBottom(LocalDensity.current)
.toDp().dp.plus(
Dimens.GridSpacing
)
),
horizontalArrangement = Arrangement.spacedBy(
Dimens.GridSpacing,
Alignment.CenterHorizontally
),
content = {
repeat(COLUMN_COUNT) {
item {
Spacer(
Modifier.windowInsetsTopHeight(
WindowInsets.statusBars.add(WindowInsets(top = 56.dp))
)
)
}
}
items(lazyTMDbItems.itemCount) { index ->
val tmdbItem = lazyTMDbItems[index]
tmdbItem?.let {
TMDbItemContent(
it,
Modifier
.height(320.dp)
.padding(vertical = Dimens.GridSpacing),
onClick
)
}
}
lazyTMDbItems.apply {
when (loadState.append) {
is LoadState.Loading -> {
item(span = span) {
LoadingRow(modifier = Modifier.padding(vertical = Dimens.GridSpacing))
}
}
is LoadState.Error -> {
val message =
(loadState.append as? LoadState.Error)?.error?.message ?: return#apply
item(span = span) {
ErrorScreen(
message = message,
modifier = Modifier.padding(vertical = Dimens.GridSpacing),
refresh = { retry() })
}
}
else -> {}
}
}
})
}
The problem is when there is no result for search, or when result items is shorter than screen size, it displays LoadingRow. My expectation is when we are in this state, LoadingRow does not display, but how can I detect this state?
Correct me if I'm wrong but these should be dictated by the PagingSource.LoadResult.Page
Documentation :
Success result object for PagingSource.load. Params: data - Loaded
data prevKey - Key for previous page if more data can be loaded in
that direction, null otherwise. nextKey - Key for next page if more
data can be loaded in that direction, null otherwise.
So if you reached the pagination end (in either direction) :
PagingSource.LoadResult.Page(
data = loadedData,
prevKey = null,
nextKey = null)

problem with LazyVerticalGrid and Composables can only be invoked from the context of a composable contex

I have some troubles with the next function:
#Composable
fun AssessmentScreen(
onClose: (String, String) -> Unit,
relatedSubSkillIdsJson: String,
uiState: AssessmentUiState,
onSelectedOption: (String) -> Unit,
onShowAnswerFeedback: (Boolean) -> Unit,
onNextQuestion: () -> Unit,
onCloseAssessment: () -> Unit,
navigateToAndPop: (Pair<String, String>) -> Unit,
goBack: () -> Unit,
assessmentType: String,
) {
val context = LocalContext.current
val activity = context.findActivity()
val navigationBarHeightDp = activity?.getNavigationBarHeightInDp() ?: 0.dp
val blur =
if (uiState.isLoading) dimensionResource(dimen.default_screen_blur) else 0.dp
val currentArtiIndex = remember { mutableStateOf(0) }
if (uiState.questions.isNotEmpty()) {
LazyColumn(
Modifier
.fillMaxSize()
.padding(
top = dimensionResource(dimen.default_screen_padding),
start = dimensionResource(dimen.default_screen_padding),
end = dimensionResource(dimen.default_screen_padding)
)
.blur(blur)
) {
item {
CloseAssessment(
relatedSubSkillIdsJson = relatedSubSkillIdsJson,
uiState = uiState,
questionIndex = uiState.currentQuestionIndex,
isAnsweredQuestion = uiState.showAnswerFeedback,
onCloseAssessment = { onCloseAssessment() },
navigateToAndPop = navigateToAndPop,
goBack = goBack
)
AssessmentTitle(artiImages[currentArtiIndex.value], assessmentType)
QuestionDotsIndicator(uiState.questionAnswersStatus)
AssessmentQuestion(
thumbnail = uiState.getCurrentQuestionItem().thumbnail,
question = uiState.getCurrentQuestionItem().question
)
Spacer(modifier = Modifier.height(20.dp))
}
val optionsAbcLetterDescription = ('a'..'z').toList()
if( uiState.assessmentType != "grid"){
LazyVerticalGrid(
columns = GridCells.Fixed(2)
) {
itemsIndexed(uiState.currentAnswerOptions) {index, option ->
AnswerOption(
selectedOptionId = uiState.selectedAnswerId,
showFeedback = uiState.showAnswerFeedback,
optionLetter = circularCharIteration(optionsAbcLetterDescription, index),
option = option,
onSelectedOption = { onSelectedOption(it) }
)
}
}
}else{
itemsIndexed(uiState.currentAnswerOptions) { index, option ->
AnswerOption(
selectedOptionId = uiState.selectedAnswerId,
showFeedback = uiState.showAnswerFeedback,
optionLetter = circularCharIteration(optionsAbcLetterDescription, index),
option = option,
onSelectedOption = { onSelectedOption(it) }
)
}
}
item {
ChallengeBtn(
modifier = Modifier
.padding(bottom = navigationBarHeightDp + dimensionResource(dimen.default_screen_padding)),
uiState = uiState,
navigateToAndPop = navigateToAndPop,
onShowAnswerFeedback = { onShowAnswerFeedback(it) },
onCloseAssessment = { onCloseAssessment() },
onNextQuestion = {
if (!uiState.isLastQuestion) {
currentArtiIndex.value =
nextArtiImage(currentArtiIndex.value)
onNextQuestion()
}
} ,
relatedSubSkillIdsJson = relatedSubSkillIdsJson,
)
}
}
}
ProgressBarComponentComposable(isLoading = uiState.isLoading)
}
my problem here its that LazyVerticalGrid gives me the next message "Composables can only be invoked from the context of a composable context", im not completly sure but i belive that its because the lazy vertical grid its inside a lazy column not sure really.
But what can i do to fix it? i mean i really need that lazy column there but i need the lazy grid too

How to pass selected single choice option to specific text field

How can a selected option from a single choice menu be passed to a different composable to that it is displayed in a Text object? Would I need to modify the selectedOption value in some way?
#Composable
fun ScreenSettings(navController: NavController) {
Scaffold(
topBar = {...},
content = {
LazyColumn(...) {
item {
ComposableSettingTheme()
}
}
},
containerColor = ...
)
}
#Composable
fun ComposableSettingTheme() {
val singleDialog = remember { mutableStateOf(false)}
Column(modifier = Modifier
.fillMaxWidth()
.clickable(onClick = {
singleDialog.value = true
})) {
Text(text = "Theme")
Text(text = selectedOption) // selected theme name should be appearing here
if (singleDialog.value) {
AlertSingleChoiceView(state = singleDialog)
}
}
}
#Composable
fun CommonDialog(
title: String?,
state: MutableState<Boolean>,
content: #Composable (() -> Unit)? = null
) {
AlertDialog(
onDismissRequest = {
state.value = false
},
title = title?.let {
{
Column( Modifier.fillMaxWidth() ) {
Text(text = title)
}
}
},
text = content,
confirmButton = {
TextButton(onClick = { state.value = false }) { Text("OK") }
},
dismissButton = {
TextButton(onClick = { state.value = false }) { Text("Cancel") }
}
)
}
#Composable
fun AlertSingleChoiceView(state: MutableState<Boolean>) {
CommonDialog(title = "Theme", state = state) { SingleChoiceView(state = state) }
}
#Composable
fun SingleChoiceView(state: MutableState<Boolean>) {
val radioOptions = listOf("Day", "Night", "System default")
val (selectedOption, onOptionSelected) = remember { mutableStateOf(radioOptions[2]) }
Column(
Modifier.fillMaxWidth()
) {
radioOptions.forEach { themeOption ->
Row(
Modifier
.clickable(onClick = { })
.selectable(
selected = (text == selectedOption),
onClick = {onOptionSelected(text)}
)
) {
RadioButton(
selected = (text == selectedOption),
onClick = { onOptionSelected(text) }
)
Text(text = themeOption)
}
}
}
}
Update
According to official documentation, you should use state hoisting pattern.
Thus:
Just take out selectedOption local variable to the "highest point of it's usage" (you use it in SingleChoiceView and ComposableSettingTheme methods) - ScreenSettings method.
Then, add selectedOption: String and onSelectedOptionChange: (String) -> Unit parameters to SingleChoiceView and ComposableSettingTheme (You can get more info in documentation).
Refactor your code using this new parameters:
Pass selectedOption local variable from ScreenSettings
into SingleChoiceView and ComposableSettingTheme.
Write logic of onSelectedOptionChange - change local variable to new passed value
Hope I helped you!

Screen scrolls to the top (Jetpack Compose Pagination)

I am trying to do pagination in my application. First, I'm fetching 20 item from Api (limit) and every time i scroll down to the bottom of the screen, it increase this number by 20 (nextPage()). However, when this function is called, the screen goes to the top, but I want it to continue where it left off. How can I do that?
Here is my code:
CharacterListScreen:
#Composable
fun CharacterListScreen(
characterListViewModel: CharacterListViewModel = hiltViewModel()
) {
val state = characterListViewModel.state.value
val limit = characterListViewModel.limit.value
Box(modifier = Modifier.fillMaxSize()) {
val listState = rememberLazyListState()
LazyColumn(modifier = Modifier.fillMaxSize(), state = listState) {
itemsIndexed(state.characters) { index, character ->
characterListViewModel.onChangeRecipeScrollPosition(index)
if ((index + 1) >= limit) {
characterListViewModel.nextPage()
}
CharacterListItem(character = character)
}
}
if (state.error.isNotBlank()) {
Text(
text = state.error,
color = MaterialTheme.colors.error,
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp)
.align(Alignment.Center)
)
}
if (state.isLoading) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
}
}
CharacterListViewModel:
#HiltViewModel
class CharacterListViewModel #Inject constructor(
private val characterRepository: CharacterRepository
) : ViewModel() {
val state = mutableStateOf(CharacterListState())
val limit = mutableStateOf(20)
var recipeListScrollPosition = 0
init {
getCharacters(limit.value, Constants.HEADER)
}
private fun getCharacters(limit : Int, header : String) {
characterRepository.getCharacters(limit, header).onEach { result ->
when(result) {
is Resource.Success -> {
state.value = CharacterListState(characters = result.data ?: emptyList())
}
is Resource.Error -> {
state.value = CharacterListState(error = result.message ?: "Unexpected Error")
}
is Resource.Loading -> {
state.value = CharacterListState(isLoading = true)
}
}
}.launchIn(viewModelScope)
}
private fun incrementLimit() {
limit.value = limit.value + 20
}
fun onChangeRecipeScrollPosition(position: Int){
recipeListScrollPosition = position
}
fun nextPage() {
if((recipeListScrollPosition + 1) >= limit.value) {
incrementLimit()
characterRepository.getCharacters(limit.value, Constants.HEADER).onEach {result ->
when(result) {
is Resource.Success -> {
state.value = CharacterListState(characters = result.data ?: emptyList())
}
is Resource.Error -> {
state.value = CharacterListState(error = result.message ?: "Unexpected Error")
}
is Resource.Loading -> {
state.value = CharacterListState(isLoading = true)
}
}
}.launchIn(viewModelScope)
}
}
}
CharacterListState:
data class CharacterListState(
val isLoading : Boolean = false,
var characters : List<Character> = emptyList(),
val error : String = ""
)
I think the issue here is that you are creating CharacterListState(isLoading = true) while loading. This creates an object with empty list of elements. So compose renders an empty LazyColumn here which resets the scroll state. The easy solution for that could be state.value = state.value.copy(isLoading = true). Then, while loading, the item list can be preserved (and so is the scroll state)
Not sure if you are using the LazyListState correctly. In your viewmodel, create an instance of LazyListState:
val lazyListState: LazyListState = LazyListState()
Pass that into your composable and use it as follows:
#Composable
fun CharacterListScreen(
characterListViewModel: CharacterListViewModel = hiltViewModel()
) {
val limit = characterListViewModel.limit.value
Box(modifier = Modifier.fillMaxSize()) {
LazyColumn(modifier = Modifier.fillMaxSize(), state = characterListViewModel.lazyListState) {
itemsIndexed(state.characters) { index, character ->
}
}
}
}

Does Jetpack Compose's LazyVerticalGrid have span strategy

I have a LazyVerticalGrid with 2 cells.
LazyVerticalGrid(
cells = GridCells.Fixed(2),
content = {
items(moviePagingItems.itemCount) { index ->
val movie = moviePagingItems[index] ?: return#items
MovieItem(movie, Modifier.preferredHeight(320.dp))
}
renderLoading(moviePagingItems.loadState)
}
)
I am trying to show full width loading with LazyGridScope's fillParentMaxSize modifier.
fun LazyGridScope.renderLoading(loadState: CombinedLoadStates) {
when {
loadState.refresh is LoadState.Loading -> {
item {
LoadingColumn("Fetching movies", Modifier.fillParentMaxSize())
}
}
loadState.append is LoadState.Loading -> {
item {
LoadingRow(title = "Fetching more movies")
}
}
}
}
But since we have 2 cells, the loading can occupy half of the screen. Like this:
Is there a way my loading view can occupy full width?
Jetpack Compose 1.1.0-beta03 version includes horizontal span support for LazyVerticalGrid.
Here is the example usage:
private const val CELL_COUNT = 2
private val span: (LazyGridItemSpanScope) -> GridItemSpan = { GridItemSpan(CELL_COUNT) }
LazyVerticalGrid(
cells = GridCells.Fixed(CELL_COUNT),
content = {
items(moviePagingItems.itemCount) { index ->
val movie = moviePagingItems.peek(index) ?: return#items
Movie(movie)
}
renderLoading(moviePagingItems.loadState)
}
}
private fun LazyGridScope.renderLoading(loadState: CombinedLoadStates) {
if (loadState.append !is LoadState.Loading) return
item(span = span) {
val title = stringResource(R.string.fetching_more_movies)
LoadingRow(title = title)
}
}
Code examples of this answer can be found at: Jetflix/MoviesGrid.kt
LazyVerticalGrid has a span strategy built into items() and itemsIndexed()
#Composable
fun SpanLazyVerticalGrid(cols: Int, itemList: List<String>) {
val lazyGridState = rememberLazyGridState()
LazyVerticalGrid(
columns = GridCells.Fixed(cols),
state = lazyGridState
) {
items(itemList, span = { item ->
val lowercase = item.lowercase()
val span = if (lowercase.startsWith("a") || lowercase.lowercase().startsWith("b") || lowercase.lowercase().startsWith("d")) {
cols
}
else {
1
}
GridItemSpan(span)
}) { item ->
Box(modifier = Modifier
.fillMaxWidth()
.height(150.dp)
.padding(10.dp)
.background(Color.Black)
.padding(2.dp)
.background(Color.White)
) {
Text(
modifier = Modifier.align(Alignment.Center),
text = item,
fontSize = 18.sp
)
}
}
}
}
'
val names = listOf("Alice", "Bob", "Cindy", "Doug", "Ernie", "Fred", "George", "Harris")
SpanLazyVerticalGrid(
cols = 3,
itemList = names
)
Try something like:
var cellState by remember { mutableStateOf(2) }
LazyVerticalGrid(
cells = GridCells.Fixed(cellState),
content = {
items(moviePagingItems.itemCount) { index ->
val movie = moviePagingItems[index] ?: return#items
MovieItem(movie, Modifier.preferredHeight(320.dp))
}
renderLoading(moviePagingItems.loadState) {
cellState = it
}
}
)
The renderLoading function:
fun LazyGridScope.renderLoading(loadState: CombinedLoadStates, span: (Int) -> Unit) {
when {
loadState.refresh is LoadState.Loading -> {
item {
LoadingColumn("Fetching movies", Modifier.fillParentMaxSize())
}
span(1)
}
...
else -> span(2)
}
}
I have created an issue for it: https://issuetracker.google.com/u/1/issues/176758183
Current workaround I have is to use LazyColumn and implement items or header.
override val content: #Composable () -> Unit = {
LazyColumn(
contentPadding = PaddingValues(8.dp),
content = {
items(colors.chunked(3), itemContent = {
Row(horizontalArrangement = Arrangement.SpaceEvenly) {
val modifier = Modifier.weight(1f)
it.forEach {
ColorItem(modifier, it)
}
for (i in 1..(3 - it.size)) {
Spacer(modifier)
}
}
})
item {
Text(
text = stringResource(R.string.themed_colors),
style = MaterialTheme.typography.h3
)
}
items(themedColors.chunked(3), itemContent = {
Row(horizontalArrangement = Arrangement.SpaceEvenly) {
val modifier = Modifier.weight(1f)
it.forEach {
ColorItem(modifier, it)
}
for (i in 1..(3 - it.size)) {
Spacer(modifier)
}
}
})
})
}

Categories

Resources