Android Studio 如何在项中传递2个列表(LazyColumn)

wnvonmuf  于 2022-11-16  发布在  Android
关注(0)|答案(2)|浏览(185)

我有LazyColumn,我想在items中传递2个列表,如何实现
如果可能的话我想做类似的事情

LazyColumn(
    modifier = Modifier.fillMaxHeight(0.85f)
) {
    items(cartItems,products) { cartItems,product ->
        CardProduct2(cartItems, product)
    }
}
vojdkbi0

vojdkbi01#

**您不能。**但您可以尝试执行以下操作:

LazyColumn {
    items(max(cars.size, products.size)) { idx ->
        CardProduct(cars.getOrNull(idx), products.getOrNull(idx)) // Assume that your CardProduct composable are applying null values
    }
}

或者更好的方法是将这些列表合并为一个

gpnt7bae

gpnt7bae2#

我假设,如果你在CardProduct内部传递一个列表,是因为你在内部使用LazyColumn来绘制该列表。
只要这样做

Column {
    CardProduct2(cartItems, product)
}

注意嵌套LazyColumns,您将得到一个编译错误,最好执行以下操作

LazyColumn(
    modifier = Modifier.fillMaxHeight(0.85f)
) {
    items(cartItems, null) { cartItems ->
        CardProduct2(cartItems)
    }

     items(null, product) { product ->
        CardProduct2(product)
    }
}

在CardProduct2中做一个简单的空值检查,以提取其中的一个,或者如果需要同时提取这两个,则创建只包含产品列表的CardProduct3。但是在CardProduct中不应该有任何LazyColumn代码,而应该只有卡片细节本身

LazyColumn(
        modifier = Modifier.fillMaxHeight(0.85f)
    ) {
        items(cartItems) { cartItems ->
            CardProduct2(cartItems)
        }
    
         items(product) { product ->
            CardProduct3(product)
        }
    }

如果您需要在CardProduct2中使用cartItemsproduct数据,只需创建一个对象,该对象接受cartItemsproduct参数,并将唯一参数作为数据传递

相关问题