I am try to learning jetpack compose, and I have list items with name and image, my project working and no problem for list name , but user images are not showing in the emulator. I do not know what I missed. Is there any solution?
Model:
data class Data(
var name: String,
var image: String)
Screen:
@Composable
fun DataScreen() {
val listOfData = listOf(
Data("name1", "image1"),
Data("name2", "image2"),
Data("name3", "image3"),)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxSize()
.background(Color.White)
) {
LazyColumn(
modifier = Modifier
) {
items(listOfData.size) { index ->
DataListItem(listOfData[index])
}}}}
Item:
@Composable
fun DataListItem(data: Data) {
val context = LocalContext.current
val painter = rememberImagePainter(
data = data.image
)
Column(
modifier = Modifier.padding(5.dp)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp)
) {
Image(
painter = painter,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.size(32.dp)
.clip(CircleShape))
Text(
text = data.name,
fontSize = 12.sp,
)}}}
CodePudding user response:
All I see is a string for your image. A painter can't display an image from just a string. You also don't need to use state management for the painter since you've included the painter in a Data object that retains the state:
This code has been tested:
data class Data(
var name: String,
var painter: Painter
)
@Composable
fun DataScreen() {
val listOfData = listOf(
Data("name1", painterResource(R.drawable.cat_1)),
Data("name2", painterResource(R.drawable.cat_2))
)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxSize()
.background(Color.White)
) {
LazyColumn(
modifier = Modifier.fillMaxSize()
) {
items(listOfData.size) { index ->
DataListItem(listOfData[index])
}
}
}
}
@Composable
fun DataListItem(data: Data) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp)
) {
Image(
painter = data.painter,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.size(32.dp)
.clip(CircleShape)
)
Text(
text = data.name,
fontSize = 12.sp,
)
}
}
}