![]() ![]() While the goal is commendable, it is important to note that you can achieve theĮxact same effect (reducing the number of builds) using ref.watch instead. This is the first method called when the widget is created (after the class constructor, of course.) initState is called once and only once. If you use ref.watch to begin with, you will have fewer problems when refactoring.īut I wanted to use ref.read to reduce the number of times my widget rebuilds Which is error prone and you are likely to forget some cases. To go through your entire codebase to change ref.read into ref.watch – If you use ref.read, when that value needs to change, you have That previously never changed will need to change. Software tends to change a lot, and it is likely that in the future, a value Its value, there is no guarantee that tomorrow will be the same. Stateful widget provides initstate() method. Provider is one of the most popular and mature methods for state management in Flutter. With this assumption is that, while today that provider may indeed never update to handle REST API requests in flutter with provider for state management. Using ref.read this way is commonly associated with the thought "The valueĮxposed by a provider never changes so using 'ref.read' is safe". The ref.listen method can be used inside the body of a provider:īut this is a very bad practice and can cause bugs that are difficult to track. The callback function when called will be passed 2 values, the value of the previous State and the value of the new State. The ref.listen method needs 2 positional arguments, the first one is the Provider and the second one is the callback function that we want to execute when the state changes. That can be useful for performing actions when a certain change happens, suchĪs showing a snackbar when an error happens. If the listened to provider changes, using ref.listen will instead call a custom function. The main difference between them is that, rather than rebuilding the widget/provider Similarly to ref.watch, it is possible to use ref.listen to observe a provider. Using ref.listen to react to a provider change In those cases, consider using ref.read instead. Inside initState and other State life-cycles. ABC Learning Program, it will go into Screen 2 to show the details of this program. Like inside an onPressed of an ElevatedButton. ![]() The watch method should not be called asynchronously, ![]()
0 Comments
Leave a Reply. |