How to access Provided (Provider.of()) value inside showModalBottomSheet?

前端 未结 5 1460
长情又很酷
长情又很酷 2021-01-01 23:50

I have a FloatingActionButton inside a widget tree which has a BlocProvider from flutter_bloc. Something like this:

BlocProvider(
  builder: (co         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-02 00:18

    InheritedWidgets, and therefore Providers, are scoped to the widget tree. They cannot be accessed outside of that tree.

    The thing is, using showDialog and similar functions, the dialog is located in a different widget tree – which may not have access to the desired provider.

    It is therefore necessary to add the desired providers in that new widget tree:

    void myShowDialog() {
      final myModel = Provider.of(context, listen: false);
      showDialog(
        context: context,
        builder: (_) {
          return Provider.value(value: myModel, child: SomeDialog());
        },
      );
    }
    

提交回复
热议问题