0

I have a Screen ( composable function ) that gets It's data from view model ( a list and two function to remove and add data in it ).

    @Composable
fun MainScreen(
    notes: List<Note>,
    onAddNote: (Note) -> Unit,
    onRemoveNote: (Note) -> Unit
){}

Now when i call this function inside the composable of my Nav host, I get errors stating that i should fill the parameters.

@Composable
fun NotesNavigation(){

    val navController = rememberNavController()
    NavHost(navController = navController, startDestination = Navigation.MainScreen.name){

        composable(Navigation.MainScreen.name){
            MainScreen() // error here
        }
    }
}

Now I am wondering what is the best practice to sort it out, do i need to provide default values for my parameters like supplying an empty list or there is better way to get around it.

1 Answers1

0

You can set default values to the MainScreenFunction, but since you are using navigation, this would become useless. I would suggest to set the viewmodel as a parameter. The viewmodel should still be passed through the navigation though.

I don't know if you use any dependency injection. If so, that would make it a bit easier. Then you can set it up like this:

   @Composable
fun MainScreen(
    viewModel: MainScreenViewModel = getViewModel() //If using Koin DI
){
...
}

This way, the navigation doesn't have to know about the viewmodel. You can still set it though, if you do need a different viewModel then the one injected for example.

Huib
  • 214
  • 1
  • 8
  • 1
    yea after reading some articles i figured that i should define my viewmodel in the navigation class and pass it to my mainScreen. there is a lot of other things you need to know while using viewmodel with navigation! thanks for the answer – jaskaran singh Aug 29 '22 at 08:19