Harmeet Singh
Harmeet Singh

Reputation: 620

How to create a reusable widget which is wrapped by multiple Selectors in Flutter

Is it possible to build a widget which can be reused and also listens to only one specific ChangeNotifier? Let me explain with an example:

I have 3 ChangeNotifier: NotifierA, NotifierB and NotifierC and I have a widget named MyLikeWidget which shows like count and all three ChangeNotifier contain a variable representing that like count. If I want to reuse MyLikeWidget I can do this:

 class ReusableWidget extends StatelessWidget {
   const ReusableWidget({Key? key, required this.changeNotifierType}) : super(key: key);
   final int changeNotifierType;

   @override
   Widget build(BuildContext context) {
     return changeNotifierType == 0 
        ? Selector<NotifierA, int>(
            selector: (c, notifierA) => notifierA.likeCount
            builder: (context, likeCount, child) => MyLikeWidget(likeCount: likeCount),
          )
        : changeNotifierType == 0
        ? Selector<NotifierB, int>(
            selector: (c, notifierB) => notifierB.likeCount
            builder: (context, likeCount, child) => MyLikeWidget(likeCount: likeCount),
          )
        : Selector<NotifierC, int>(
            selector: (c, notifierC) => notifierC.likeCount
            builder: (context, likeCount, child) => MyLikeWidget(likeCount: likeCount),
          );
   }
 }

class MyLikeWidget extends StatelessWidget {
  const MyLikeWidget({Key? key, required this.likeCount}) : super(key: key);
  final int likeCount;

  @override
  Widget build(BuildContext context) {
    return ComplexWidget(
      ....
    );
  }
}

The above approach can work if we have only a few reusable widgets and few ChnageNotfiers, but for large complex apps this approach will result in a lot of boilerplate code, we can solve this by using Selctor3 but this approach will rebuild MyLikeWidget every time like count changes in any ChangeNotifier this approach can create problems for complex reusable widgets like a reusable video widget which will rebuild even it is playing a video if the value it is listening to changes in any ChangeNotfier.

Is there any other way we can approach this problem without writing a lot of boilerplate code?

Upvotes: 0

Views: 123

Answers (1)

Andrija
Andrija

Reputation: 1899

Would this work - simply use the generics with your class:

class ReusableWidget<T extends ChangeNotifierProvider> extends StatelessWidget {
   const ReusableWidget<T>({super.key});
   

   @override
   Widget build(BuildContext context) {
     return Selector<T, int>(
            selector: (c, notifierA) => notifierA.likeCount
            builder: (context, likeCount, child) => MyLikeWidget(likeCount: likeCount),
          );
   }
 }

And use it like this:

return ReusableWidget<NotifierA>(
...

Upvotes: 2

Related Questions