Spencer
Spencer

Reputation: 113

How do you build a Reusable and Disposable Provider that shares state across widgets in Flutter?

Problem


Im working on a Flutter app where I need a SelectableProvider that accepts a generic type <T>and manages a list of selected items. The provider is used to manage the state between the GridView and PageView pages.

This Provider should be disposable because this Flutter app will allow multiple scenarios for the user to make selections of item <T>.

What I've Tried


Code


SelectableProvider

class SelectableProvider<T> with ChangeNotifier implements TickerProvider {
 final List<T> _selectedItems = [];
 
 late AnimationController _gridAnimationController;
 late Animation<double> _gridAnimation;

 SelectableProvider() {
  _initAnimationControllers();
  _initAnimations();
 }

 /* rest of code */
}

GridView

ChangeNotifierProvider(
 create: (_) => SelectableProvider<MyItemType>(),
 child: GridView.builder(/* builder */),
)

onPressed To PageView

Navigator.push(
 context, 
 MaterialPageRoute(
  builder: (context) => ChangeNotifierProvider.value(
   value: selectableProvider,
   builder: (context, child) => PageView(),
  ),
 ),
)

Conclusion

So basically, is there any way I can initiate the SelectableProvider inside this specific scope instead of globally above MaterialApp? And how do I prevent the Provider from duplicating itself to cover both Widgets? Or is that completely normal?

Upvotes: 0

Views: 29

Answers (0)

Related Questions