How can I check to see if provided class exists

427

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.

Share:
427
Scorb
Author by

Scorb

Updated on December 31, 2022

Comments

  • Scorb
    Scorb over 1 year

    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.

    • Calvin Gonsalves
      Calvin Gonsalves almost 3 years
      you can try implementing the second point mentioned in pub.dev/packages/provider/versions/6.0.0-dev/changelog of the latest provider version
    • Scorb
      Scorb almost 3 years
      @CalvinGonsalves. You have provided the correct answer. The way to do this is to call Provider.of<MyChangeNotifier?>(context) with nullable types language feature enabled. If you want to write that as the answer, you can get some internet points.
  • quantum apps
    quantum apps over 2 years
    hahaha, how did I not figure this one out myself
  • felix-ht
    felix-ht about 2 years
    note that you will have to use provider 6.0.0 or later for this to work