我有一个可组合的视图模型,我想把一个id从可组合传递给视图模型。
我的堆肥是:
@Composable
fun HttpRequestScreen(
viewModel: HttpRequestViewModel = hiltViewModel(),
id: String = EMPTYUUID,
onClick: (String, String, Int) -> Unit // respond, request Function: 1 - send request, 2 - edit request
) {
我有来自不同屏幕的id,我想把它传递给我的Hilt视图模型。
假设您已经遵循了撰写导航的文档,您可以在这里找到您的参数:
@HiltViewModel
class RouteDetailsViewModel @Inject constructor(
private val getRouteByIdUC: GetRouteByIdUC,
private val savedStateHandle: SavedStateHandle
): ViewModel() {
private val routeId = savedStateHandle.get<String>("your-param-name") // for example String in my case
}
您需要考虑单向数据流模式,其中事件向上流动,状态向下流动。为此,您需要从视图模型中公开某种状态,将请求的状态作为可观察状态发送给Composable。
你的视图模型可能是这样的。
class HttpRequestViewModel: ViewModel() {
private val _httpResponse = mutableStateOf("")
val httpResponse: State<String> = _httpResponse
fun onHttpRequest(requestUrl: String) {
// Execute your logic
val result = "result of your execution"
_httpResponse.value = result
}
}
然后在您的Composable中,您可以通过调用按钮上的ViewModel函数来发送事件,点击类似
@Composable
fun HttpRequestScreen(viewModel: HttpRequestViewModel) {
val state by viewModel.httpResponse
var userInput = remember { TextFieldValue("") }
Column {
Text(text = "HTTP Response = $state")
}
BasicTextField(value = userInput, onValueChange = {
userInput = it
})
Button(onClick = { viewModel.onHttpRequest(userInput.text) }) {
Text(text = "Make Request")
}
}
我希望这能为你指明正确的方向。祝你好运