@Composable 调用只能在 @Composable 函数的上下文中发生 - LazyColumn

问题描述 投票:0回答:1

我正在尝试获取联系号码和姓名,但遇到错误:

@Composable 调用只能在 @Composable 函数的上下文中发生。

如何解决这个问题?

data class Contact(val name: String, val phoneNumber: String)

@Composable
fun ContactList(){
    val context = LocalContext.current
    val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
        if (isGranted) {
            // Permission is granted, fetch the contacts
            val contacts = fetchContacts(context)
            LazyColumn {
                items(contacts) { contact ->
                    Text(text = "Name: ${contact.name}, Phone: ${contact.phoneNumber}")
                    Spacer(modifier = Modifier.padding(10.dp))
                }
            }
        } else {
            // Handle the case when the user denies the permission
        }
    }

    // Request permission to read contacts
    launcher.launch(Manifest.permission.READ_CONTACTS)
}

private fun fetchContacts(context: Context): List<Contact> {
    val contacts = mutableListOf<Contact>()
    val cursor = context.contentResolver.query(
        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
        null,
        null,
        null,
        null
    )

    cursor?.use {
        while (it.moveToNext()) {
            val name = it.getString(it.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
            val phoneNumber = it.getString(it.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
            contacts.add(Contact(name, phoneNumber))
        }
    }

    return contacts
}
android kotlin android-jetpack-compose android-jetpack android-jetpack-compose-lazy-column
1个回答
0
投票

rememberLauncherForActivityResult(...)
采用第二个参数
onResult
,它只是一个标准回调(不是可组合的)。当您尝试调用可组合函数 (
LazyList { ... }
) 时,您会收到错误,而预期是正常函数。我处理这种情况的方法是在
onResult
触发时更改视图模型上的某些状态变量,然后在 UI 中监听此变量的更改,然后在其中显示惰性列表

© www.soinside.com 2019 - 2024. All rights reserved.