如何在依赖于视图模型的可组合函数中获得预览? [英] How to get preview in composable functions that depend on a view model?
问题描述
我想在我的 HomeScreenPreview
预览函数中预览我的 HomeScreen
可组合函数.但是这是不可能的,因为我收到以下错误:
I would like to have the preview of my HomeScreen
composable function in my HomeScreenPrevieiw
preview function. However this is not being possible to do because I am getting the following error:
java.lang.IllegalStateException: ViewModels creation is not supported in Preview
at androidx.compose.ui.tooling.ComposeViewAdapter$FakeViewModelStoreOwner$1.getViewModelStore(ComposeViewAdapter.kt:709)
at androidx.lifecycle.ViewModelProvider.<init>(ViewModelProvider.kt:105)
at androidx.lifecycle.viewmodel.compose.ViewModelKt.get(ViewModel.kt:82)
at androidx.lifecycle.viewmodel.compose.ViewModelKt.viewModel(ViewModel.kt:72)
at com.example.crud.ui.screens.home.HomeScreenKt.HomeScreen(HomeScreen.kt:53)
at com.example.crud.ui.screens.home.HomeScreenKt.HomeScreenPreview(HomeScreen.kt:43)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
...
我的代码
这是我的HomeScreen
代码:
@Composable
fun HomeScreen(
viewModel: HomeViewModel = hiltViewModel(),
navigateToDetailsAction: () -> Unit,
openCardDetailsAction: (Int) -> Unit
) {
val cities = viewModel.cities.observeAsState(listOf())
Scaffold(
topBar = { HomeAppBar() },
floatingActionButton = { HomeFab(navigateToDetailsAction) }
) {
HomeContent(cities) { id -> openCardDetailsAction(id) }
}
}
这是我的预览功能的代码:
This is the code for my preview function:
@Preview
@Composable
private fun HomeScreenPreview() {
HomeScreen(navigateToDetailsAction = {}, openCardDetailsAction = {})
}
我的视图模型:
@HiltViewModel
class HomeViewModel @Inject constructor(repository: CityRepository) : ViewModel() {
val cities: LiveData<List<City>> = repository.allCities.asLiveData()
}
存储库:
@ViewModelScoped
class CityRepository @Inject constructor(appDatabase: AppDatabase) {
private val dao by lazy { appDatabase.getCityDao() }
val allCities by lazy { dao.getAllCities() }
suspend fun addCity(city: City) = dao.insert(city)
suspend fun updateCity(city: City) = dao.update(city)
suspend fun deleteCity(city: City) = dao.delete(city)
suspend fun getCityById(id: Int) = dao.getCityById(id)
}
应用数据库:
@Database(entities = [City::class], version = 2, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun getCityDao() : CityDao
}
我失败的尝试
我认为作为我的 HomeScreen
的默认参数传递的视图模型可能有问题,所以我决定这样做:
My failed attempt
I thought it might be a problem with the view model being passed as the default parameter of my HomeScreen
and so I decided to do it this way:
@Composable
fun HomeScreen(
navigateToDetailsAction: () -> Unit,
openCardDetailsAction: (Int) -> Unit
) {
val viewModel: HomeViewModel = hiltViewModel()
val cities = viewModel.cities.observeAsState(listOf())
Scaffold(
topBar = { HomeAppBar() },
floatingActionButton = { HomeFab(navigateToDetailsAction) }
) {
HomeContent(cities) { id -> openCardDetailsAction(id) }
}
}
但它仍然不起作用(我一直收到同样的错误),并且不利于测试,因为它会阻止我使用模拟视图模型测试我的 HomeScreen
.
But it still doesn't work (I keep getting the same error), and it's not good for testing as it would prevent me from testing my HomeScreen
with a mocked view model.
推荐答案
这正是视图模型传递默认值的原因之一.在预览中,可以传递一个测试对象:
This is exactly one of the reasons why the view model is passed with a default value. In the preview, you can pass a test object:
@Preview
@Composable
private fun HomeScreenPreview() {
val viewModel = HomeViewModel()
// setup viewModel as you need it to be in the preview
HomeScreen(viewModel = viewModel, navigateToDetailsAction = {}, openCardDetailsAction = {})
}
因为你有一个仓库,你可以像测试视图模型一样做同样的事情.
Since you have a repository, you can do the same thing you would do to test the view model.
- 为
CityRepository
创建接口
interface CityRepositoryI {
val allCities: List<City>
suspend fun addCity(city: City)
suspend fun updateCity(city: City)
suspend fun deleteCity(city: City)
suspend fun getCityById(id: Int)
}
- 为
CityRepository
实现它:
@ViewModelScoped
class CityRepository @Inject constructor(appDatabase: AppDatabase) : CityRepositoryI {
private val dao by lazy { appDatabase.getCityDao() }
override val allCities by lazy { dao.getAllCities() }
override suspend fun addCity(city: City) = dao.insert(city)
override suspend fun updateCity(city: City) = dao.update(city)
override suspend fun deleteCity(city: City) = dao.delete(city)
override suspend fun getCityById(id: Int) = dao.getCityById(id)
}
- 创建
FakeCityRepository
用于测试目的:
- Create
FakeCityRepository
for testing purposes:
class FakeCityRepository : CityRepositoryI {
// predefined cities for testing
val cities = listOf(
City(1)
).toMutableStateList()
override val allCities by lazy { cities }
override suspend fun addCity(city: City) {
cities.add(city)
}
override suspend fun updateCity(city: City){
val index = cities.indexOfFirst { it.id == city.id }
cities[index] = city
}
override suspend fun deleteCity(city: City) {
cities.removeAll { it.id == city.id }
}
override suspend fun getCityById(id: Int) = cities.first { it.id == id }
}
所以你可以将它传递给你的视图模型:HomeViewModel(FakeCityRepository())
So you can pass it into your view model: HomeViewModel(FakeCityRepository())
您可以使用 AppDatabase
而不是存储库来做同样的事情,这完全取决于您的需要.查看有关Hilt 测试
You can do the same with AppDatabase
instead of a repository, it all depends on your needs. Check out more about Hilt testing
附言我不确定这是否会成功,因为我没有你的一些课程,但你应该明白这个想法.
p.s. I'm not sure if this will build, since I don't have some of your classes, but you should have caught the idea.
这篇关于如何在依赖于视图模型的可组合函数中获得预览?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!