Flutter provider 中的 read 和 watch 有甚麼差異

在 Flutter 的 Provider 套件中,read 和 watch 有以下的差異:

  • context.read<T>()
    這個方法會回傳 T 的值,但不會監聽它的變化。也就是說,它只會讀取一次(one-time read)。這個方法不建議在 build() 方法中使用。
  • context.watch<T>()
    這個方法會回傳 T 的值,並且會在值變化時重新構建 widget。也就是說,它會在初次讀取值以及每次值變化時都會讀取(like subscribing to the provider)。

簡言之,如果需要在值變化時重新構建 widget,使用 watch。如果只需要讀取一次值,並且不需要在值變化時做出反應,使用 read。

留言

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.