[英]LazyVerticalGrid for paging items in jetpack compose
我目前正在通過下面的擴展函數在LazyVerticalGrid
中使用分頁項( LazyPagingItems
),它工作正常。
inline fun <T : Any> LazyGridScope.items(
items: LazyPagingItems<T>,
crossinline itemContent: @Composable LazyGridItemScope.(item: T?) -> Unit
) {
items(count = items.itemCount) { index ->
itemContent(items[index])
}
}
但是,我想利用LazyLazyout
提供的其他參數,如key
、 span
等,並嘗試以下功能。
inline fun <T : Any> LazyGridScope.items(
items: LazyPagingItems<T>,
noinline key: ((item: T?) -> Any)? = null,
noinline span: (LazyGridItemSpanScope.(item: T?) -> GridItemSpan)? = null,
noinline contentType: (item: T?) -> Any? = { null },
crossinline itemContent: @Composable LazyGridItemScope.(item: T?) -> Unit
) = items(
count = items.itemCount,
key = if (key != null) { index: Int -> key(items[index]) } else null,
span = if (span != null) { { span(items[it]) } } else null,
contentType = { index: Int -> contentType(items[index]) }
) {
itemContent(items[it])
}
當我將該函數與key
一起使用時,它顯示錯誤Type mismatch: inferred type is Long? but Any was expected
Type mismatch: inferred type is Long? but Any was expected
的。
items(items = products, key = { product -> product?.productId }) {
//Content
}
我想這是由於聲明了public class LazyPagingItems<T : Any>
。 如何解決它以將所有參數與分頁項一起使用?
使用product?.productId
你試圖傳遞一個可選的Int?
值,而key
需要一個非可選的Any
值。
當您將key = null
傳遞給計算塊時,它會根據索引為每個對象創建一個唯一的鍵。 特定的項目鍵不能為null
,因為這會使它等於其他項目鍵,這是被禁止的。
您可以只為非可選項目設置調用key
,並為可選案例提供index
作為默認值:
inline fun <T : Any> LazyGridScope.items(
// ...
noinline key: ((item: T) -> Any)? = null,
// ...
) = items(
// ...
key = if (key != null) { index: Int -> items[index]?.let(key) ?: index } else null,
// ...
用法:
items(items = products, key = { product -> product.productId }) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.