Jetpack Compose - 通过可组合回调传递对象 [英] Jetpack Compose - pass an object through composable callback

查看:90
本文介绍了Jetpack Compose - 通过可组合回调传递对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个应用程序中,我有一个屏幕,您可以在其中输入笔记的标题和内容.

In this app, I have a screen where you can enter a title and content for a Note.

屏幕有两个可组合的 DetailScreen()DetailScreenContent.

The screen has two composables DetailScreen() and DetailScreenContent.

Detailscreen 有脚手架和应用栏,并调用 DetailScreenContents(),后者有两个 TextField 和一个按钮.

Detailscreen has the scaffold and appbars and calls DetailScreenContents() which has two TextFields and a button.

我希望用户在这些字段中输入文本,然后按下按钮,该按钮会将文本打包到 NOTE 对象中.我的问题是,如何将 NOTE 传递给上层可组合,即 DETAILSCREEN() 并带有回调,例如=点击:->注意或任何其他有效的方式?

I'm expecting the user to enter text in these fields and then press the button which will package the text into a NOTE object. My question is, how to pass the NOTE to the upper composable which is DETAILSCREEN() with a callback like= onclick: -> Note or any other efficient way?

@Composable
fun DetailScreen(navCtl : NavController, mviewmodel: NoteViewModel){

Scaffold(bottomBar = { TidyBottomBar()},
         topBar = { TidyAppBarnavIcon(
             mtitle = "",
             onBackPressed = {navCtl.popBackStack()},

         )
         }) {
    DetailScreenContent()
   }
}



@Composable
fun DetailScreenContent() {
val titleValue = remember { mutableStateOf("")}
val contentValue = remember { mutableStateOf("")}
val endnote by remember{ mutableStateOf(Note(
    Title = titleValue.value,
    Content = contentValue.value))}


Column(modifier = Modifier.fillMaxSize()) {

    OutlinedTextField(value = titleValue.value,
        onValueChange = {titleValue.value = it},
        singleLine = true,
        label = {Text("")}
    ,modifier = Modifier
            .fillMaxWidth()
            .padding(start = 3.dp, end = 3.dp),
        shape = cardShapes.small
    )

    OutlinedTextField(value = contentValue.value, onValueChange = {
        contentValue.value = it
    },
        label = {Text("Content")}
        ,modifier = Modifier
            .fillMaxWidth()
            .padding(start = 3.dp, end = 3.dp, top = 3.dp)
            .height(200.dp),
        shape = cardShapes.small,

    )

  Row(horizontalArrangement = Arrangement.End,
      modifier = Modifier.fillMaxWidth()){
      Button(onClick = {
                       /**return the object to the upper composable**/
      }, shape = cardShapes.small) {
          Text(text = stringResource(R.string.Finish))
      }
      
  }

}

推荐答案

您可以使用状态提升.使用 lambdas 是这里提升状态的最常见方式.

You could use state hoisting. Using lambdas is the most common way of hoisting state here.

好的,这里是 DetailScreenContent(),比如说

Ok so here's DetailScreenContent(), say

fun DetailScreenContent(
processNote: (Note) -> Unit
){
 Button( onClick = { processNote(/*Object to be "returned"*/) }
}

我们实际上并没有返回任何东西,而是将状态提升到层次结构中.现在,在 DetailsS​​creen

We are not literally returning anything, but we are hoisting the state up the hierarchy. Now, in DetailsScreen

fun DetailScreen(navCtl : NavController, mviewmodel: NoteViewModel){

Scaffold(bottomBar = { TidyBottomBar()},
         topBar = { TidyAppBarnavIcon(
             mtitle = "",
             onBackPressed = {navCtl.popBackStack()},

         )
         }) {
    DetailScreenContent(
        processNote = {note -> //This is the passed object
            /*Perform operations*/
        }
     )
   //You could also extract the processNote as a variable, like so
/*
 val processNote = (Note) {
 Reference the note as "it" here
 }
*/
   }
}

这里假设有一个Note类型(类似数据类之类的,传递的是哪个类型的对象,明白了吗?)

This assumes that there is a type Note (something like a data class or so, the object of which type is being passed up, get it?)

这就是我们如何提升我们的状态并将其提升到视图模型.请记住,compose 根据此处的变量呈现状态,因此保留变量至关重要,确保它们不会被随意修改并从随机位置读取.一次应该只有一个变量实例,应该在必要时进行修改,并且应该从公共位置读取.这是视图模型有用的地方.您将所有变量(状态)存储在视图模型中,并将读取和修改提升到那里.它必须充当应用的单一事实来源.

That's how we hoist our state and hoist it up to the viewmodel. Remember, compose renders state based on variables here, making it crucial to preserve the variables, making sure they are not modified willy nilly and read from random places. There should be, at a time, only one instance of the variables, which should be modified as and when necessary, and should be read from a common place. This is where viewmodels are helpful. You store all the variables (state) inside the viewmodel, and hoist the reads and modifications to there. It must act as a single source of truth for the app.

这篇关于Jetpack Compose - 通过可组合回调传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆