getting context.read() functionality inside build

Viewed 354

Calling context.read() inside build is not safe. Thus it raises an error but Provider.of(context, listen = false) is allowed for backwards compatibility but it still is unsafe. How can one get the context.read() functionality inside build.

One solution I found:

In you model add two values, one that will change and the other will not:

class MyModel extends ChangeNotifier {
  double value = 45;
  double thisValueWillNeverChange = 45;
}

In your Widget call value where the value needs to changed and should cause the widget to rebuild but use the thisValueWillNeverChange where you just want to read the initial value and dont want to update the widget.

You can access both values with context.select() or context.watch().

Kind of app where I want to implement this functionality: enter image description here

As you can see that the title in the appBar is going to have the thisValueWillNeverChange so it stays static but the text and the slider will change and will use value.

At the start the app will start with everything having the initial value as 45.0

0 Answers
Related