Home > Net >  How to update Jetpack compose UI by override method or outside the function
How to update Jetpack compose UI by override method or outside the function

Time:04-19

I am converting my older XML UI as per requirement. in there, I am unable to update by Jetpack compose UI by my override function. In some research I see many websites shows remember function helps for state update, but, as for my situation. I need to update my UI by the override function that I implemented in another class.

    private lateinit var materialList: List<Material>


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (savedInstanceState == null)
            viewModel.initFilters(initText, initFilters)
        materialpresenter.attachView(this, lifecycle)

        materialList= listOf()
        setContent {
            FilterBox(materialList)
        }

    }


@Composable
fun FilterBox(materialList: List<Material>) {
    var selectedIndex by remember { mutableStateOf("0") }
    val onItemClick = { index: Int -> selectedIndex = "0" }

    FlowRow(
        modifier = Modifier.padding(top = 14.dp),
        mainAxisAlignment = MainAxisAlignment.Start,
        crossAxisSpacing = 8.dp,
        mainAxisSpacing = 4.dp
    ) {
        materialList.forEach { hashTag ->
            if (selectedIndex == hashTag.id) {
                FilterSelectionItemText(
                    hashTag.slug, index = 0,
                    onClick = onItemClick
                )
            } else {
                FilterUnSelectionItemText(
                    hashTag.slug, index = 0,
                    onClick = onItemClick
                )
            }

        }
    }
}

    override fun onMaterials(list: List<Material>) {
        print("list :-"   list)
        materialList = list
    }

I want to update my FilterBox Composable UI by my onMaterials function. because when I am print this this its printing data properly, but my UI is not updating.

CodePudding user response:

To update composable UI you first need state which holds data because composable functions are updating when there is a some state/data changes

in this example your data is materialList: List<Material>

You need to wrap your data with state / mutable state / mutable state list (for lists)

Change your list to stateList or mutableState...

private val materialList: MutableState<List<Material>> = mutableStateOf(emptyList())

Collect your data from state in setContent composable like:

val myList: List<Material> by materialList // here you will get updated last data as List<Material>

FilterBox(myList)

Update state from overridden method.

  override fun onMaterials(list: List<Material>){
        materialList.value = list // your updated List
    }
  • Related