Home > Back-end >  Why remember doesnt convert StateFlow to specific type?
Why remember doesnt convert StateFlow to specific type?

Time:11-24

I have this class in Jetpack compose:

class MainActivity : ComponentActivity(){

    private var viewModel: MAViewModel = MAViewModel()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AplicacionCiudadesTheme {
                val navController = rememberNavController()
                NavHost(navController = navController, startDestination = "splash") {
                    composable("splash") {
                        SplashScreen(navController)
                    }
                    composable("main") {
                        val fichasState = viewModel.fichas.collectAsState()
                        val listaFichas = remember {
                            fichasState
                        }
                       * MainScreen(listaFichas)*
                    }
                }
            }
        }
    }
}

Class MAViewModel:

class MAViewModel : ViewModel() {
    private val _fichas = MutableStateFlow<List<FichaX>>(emptyList())
    val fichas: StateFlow<List<FichaX>> get() = _fichas

    init {
        listarFichas()
        Log.i("Info", "$_fichas")
    }

    private fun listarFichas() {
        viewModelScope.launch {
            val fichasService = fichasRepo.listFichas(
                Resources.idCategoriaPadre,
                Resources.idIdioma,
                Resources.idProyecto
            )
            _fichas.value = fichasService.fichas
        }
    }
}

When i call to MainScreen, listaFichas show me this error:

type mismatch
require: List<FichaX>
found: State<List<FichaX>>

MainScreen is a Class that receive a objetc list of type FichaX, remember doesnt works correctly

CodePudding user response:

You must use listaFichas.value.
If you want to use listaFichas without .value, You must declare your remember like this:

val listaFichas by remember {
    fichasState
}
  • Related