I have a List which contains two TextFields for every element. One TextField is to put a key, and the other to put a value. I want to obtain the values of the TextFields, for example, the values of the key TextField in a List and the values of the value TextField in other List, or get the values of the keys and values and put them in a MutableMap(prefer this last one) but I don't know how to do it.
How can I do this? I'm using LazyColumn to show the list of TextField. Now, I just have two variables but is always the same value for all the TextFields, I want to have a different value for every single TextField.
val keys = remember { mutableStateOf(TextFieldValue()) }
val values = remember { mutableStateOf(TextFieldValue())}
LazyColumn(Modifier.fillMaxWidth()){
itemsIndexed(myListOfTextFields) { index, item ->
Row(Modifier.fillMaxWidth()) {
TextField(value = keys.value,
onValueChange = { keys.value = it },
singleLine = true)
TextField(value = values.value,
onValueChange = { values.value = it },
singleLine = true)
}
}
CodePudding user response:
From what I gather your want to store every single inputed "key/value" pair from your list inside an array of KV or and map
Compose provides you with the function mutableStateListOf
allowing you to interact with an observable MutableList
within the composition scope.
Compose also provides you with mutableStateMapOf
but in your case I'd advise against it since you would not be able to easily map key/value to index within your textfield see code comment.
Here is what I'd recommend:
val data = remember { mutableStateListOf<Pair<String, String>>() }
LazyColumn(Modifier.fillMaxWidth()) {
itemsIndexed(myListOfTextFields) { index, item ->
val datum = data[index] // can't do this with mutableStateMapOf ??
Row(Modifier.fillMaxWidth()) {
TextField(
value = datum.first,
onValueChange = { data[index] = data[index].copy(first = it) },
singleLine = true
)
TextField(
value = datum.second,
onValueChange = { data[index] = data[index].copy(second = it) },
singleLine = true
)
}
}
}
Combining List
and Pair
into MutableList<Pair<K, V>>
gives you access to kotlin's lib MutableList<Pair<K, V>>.toMap()
turning Iterable
into Map<K, V>
The returned map preserves the entry iteration order of the original collection. If any of two pairs would have the same key the last one gets added to the map.
Since your interaction relies on an iteration I'd strongly sticking with a list and turning it in a map later on, when submitting data perhaps.
data.toMap()