Pass Type as a Constructor and use it as a generic for provider package

I have a child widget:


class MyWidget extends StatelessWidget {
  final provider;

  MyWidget({Key key, @required this.provider});

  Widget build(BuildContext context) {
    final data = Provider.of<provider>(context);
  }

}

That I use multiple times from a parent widget:

class Parent extends StatelessWidget {

  ...
  children: <Widget>[
    ChangeNotifierProvider<Myproviderone>(
      builder: (context) => Myproviderone(),
      child: MyWidget(MyProviderone),
    ),
    ChangeNotifierProvider<Myprovidertwo>(
      builder: (context) => Myprovidertwo(),
      child: MyWidget(MyProvidertwo),
    ),
  ],
  ...

}

I am using provider package. Basically I want to pass the Type Myproviderone/Myprovidertwo to be used as a generic inside Provider.of<> How can this be achieved?

1 answer

  • answered 2019-11-08 15:03 dubace

    Make your MyWidget a generic class:

    class MyWidget<T> extends StatelessWidget {    
      MyWidget({Key key});
    
      Widget build(BuildContext context) {
        final data = Provider.of<T>(context);
      }
    }
    

    and then build it from the outside like that:

    class Parent extends StatelessWidget {
      children: <Widget>[
        ChangeNotifierProvider<Myproviderone>(
          builder: (context) => Myproviderone(),
          child: MyWidget<MyProviderone>(),
        ),
      ],
    }