Flutter Riverpod ref.read() vs ref.listen() vs ref.watch()

Created At: 2023-03-06 06:13:04 Updated At: 2023-03-06 06:25:47

What is the purpose and difference between these functions?


Use read to the get the value of/in provider just once (one-time read). It's not recommened to use inside build() method.


Use watch to the get the value of/in provider the first time and every time the value changes (see it like you're subscribing to the provider, so you get notified any time there's a change)


listen is similar to watch. The main difference is the return type. watch returns the new value directly, listen returns a void but gives access to the new value and the old value with a callback (See examples below)


Where and where not can I use these functions?

You can use read in places like initState , callbacks like onPressed etc. watch and listen should not be called asynchronously, like inside an onPressed of an ElevatedButton. Nor should it be used inside initState and other State life-cycles.


When should I use these functions?


Use read when you want to value of the provider only once.


Use watch when you want to always get the value.


Add Reviews