Tips for using flutter provider and setState

 # A

```dart

final appModel = Provider.of<AppModel>(context, listen: true);

```

Whenever you change variables under `appModel`, `didChangeDependencies()` will be called again.

If you modify `appModel` under the function `didChangeDependencies()`, you will create a dead loop, it re-renders your component(or widget) over and over again.


# B

```dart

setState(() {

});

```
`setState` also forces the flutter to re-render your widget, but it does it by calling the `build(BuildContext context)` function again. So the `didChangeDependencies()` function won't be called. So no dead loop would be created. It's safer.


# A + B

Normally, you want to just use B, but B has drawbacks: you can't pass data to your children widgets.

What can we do then? We use them together!

But just remember, change your `appModel` variable only when the value got changes.

For example, you can do a check like this:

```dart
String get current_page {
    return this._current_page;
}

set current_page(String value) {
    if (value != this._current_page) {
        this._current_page = value;
        notifyListeners();
    }
```

No more dead loops now, cheers!

# Author
https://yingshaoxo.blogspot.com