1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ViewModelに依存しているComposableをPreviewできるようにする。

Last updated at Posted at 2024-01-21

ViewModel をコンストラクタ引数に取る Composable で Preview が使用できなくて困った(そして意外と情報が見つからなかった)ので、覚書きの意味も込めて書いておこうと思います。

ViewModelをコンストラクタで受け取っているComposableはそのままではPreviewできない。

ViewModelをコンストラクタで受け取っているComposable メソッドを直接 @Preview アノテーション付きのメソッドの中で呼ぶと、

Failed to instantiate a ViewModel
This preview uses a ViewModel. ViewModels often trigger operations not supported by Compose Preview, such as database access, I/O operations, or network requests. You can read more about preview limitations in our external documentation.

という感じのエラーが出てプレビューが表示されません。
「ViewModelはしばしばコンポーズプレビューでサポートされていない処理を行うのでプレビューは利用できませんよ」って感じでしょうか。

解決方法

まあ要するに、ViewModelが担っている値の提供や処理を一つ一つ個別に受け取るようにしておいてそのコンポーザブルを、ViewModelを持っているコンポーザブルから呼んであげるようにする、という感じです。
使用する値や処理が多くなるとちょっと面倒ですが、最初にこうゆう風にしておけば、値や処理が増えた時にそれの要素だけ追加していけば良いので。

TestFragmentComoose.kt

// こちらがフラグメントなどから呼ぶ方のコンポーザブル
@Composable
fun TestFragmentComoose(
    viewModel: TestViewModel = viewModel()
) {
    TestFragmentContent(
        comment = viewModel.comment.value,
        onChange = viewModel.onCommentChange()
    )
}

// 実際の表示内容のコンポーザブル
@Composable
fun TestFragmentContent(
    comment: String = "",
    onChange: (String) -> Unit = {}
) {
    TextField(value = comment, onValueChange = onChange)
}

@Preview()
@Composable
fun Preview() {
    // ViewModelを必要としない方をPreviewする
    TestFragmentContent(comment = "コメント")
}

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?