Home > Enterprise >  How to pass generic provider to child?
How to pass generic provider to child?

Time:05-06

I want to create a universal alert that I will use several times in my app.

class SelectIconAlertDialogWidget extends StatelessWidget {
  const SelectIconAlertDialogWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final model = Provider.of<IncomeViewModel>(context, listen: true).state;

    return AlertDialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(40),
      ),

Problem is that I can not figure out how to pass type of parent ChangeNotifier

                  showDialog<String>(
                    context: context,
                    builder: (_) =>
                        ChangeNotifierProvider<IncomeViewModel>.value(
                      value: view,
                      child: const SelectIconAlertDialogWidget(),
                    ),
                  );

I have a lot of ViewModels that will use this alert so dont want to repeat this code and write generic Alert that I can use with any ViewModel. How can I achieve this?

CodePudding user response:

check this video, add MultiProvider in your main.dart file, so all the widgets under the tree can access these provider values

CodePudding user response:

Add type parameter for your class

 class SelectIconAlertDialogWidget<T extends ChangeNotifier> extends StatelessWidget {
  const SelectIconAlertDialogWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // and you can use generic type T like this:
    final model = Provider.of<T>(context, listen: true).state;

    return AlertDialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(40),
      ),

And call it passing type parameter SelectIconAlertDialogWidget<IncomeViewModel>()

showDialog<String>(
                    context: context,
                    builder: (_) =>
                        ChangeNotifierProvider<IncomeViewModel>.value(
                      value: view,
                      child: const SelectIconAlertDialogWidget<IncomeViewModel>(),
                    ),
                  );
  • Related