5

I am using Provider package in my flutter app.

I am conditionally providing a ChangeNotifier class using provider.

A subsequent build method down the tree wants to check to see if the class exists, and it is not a failure case if it doesn't.

How can I do this using Provider package. Currently when I call...

Provider.of<MyChangeNotifier>(context);

It throws if MyChangeNotifier does not exist up the tree. All I want is a quick and simple check for MyChangeNotifier existence, because it is an expected case.

Scorb
  • 1,654
  • 13
  • 70
  • 144
  • 1
    you can try implementing the second point mentioned in https://pub.dev/packages/provider/versions/6.0.0-dev/changelog of the latest provider version – Calvin Gonsalves Jul 13 '21 at 20:44
  • @CalvinGonsalves. You have provided the correct answer. The way to do this is to call Provider.of(context) with nullable types language feature enabled. If you want to write that as the answer, you can get some internet points. – Scorb Jul 13 '21 at 20:54

1 Answers1

11

As @Scorb mentioned, calling Provider.of<MyChangeNotifier?>(context) with null safety enabled will try to obtain the matching provider and if none are found null will be returned instead of throwing.

Calvin Gonsalves
  • 1,738
  • 11
  • 15