【问题标题】:How to get a Provider<MyBloc>.of(context) inside my ModalRoute如何在我的 ModalRoute 中获取 Provider<MyBloc>.of(context)
【发布时间】:2020-11-06 12:25:53
【问题描述】:

我正在尝试访问嵌套有 ModalRoute 的 Widget 内的 BloC。

这里是 MultiProvider,它工作正常,因为我可以在 HomeTab 中访问。

 child: MultiProvider(
            providers: [
              StreamProvider<User>(create: (_) => _userBloc.userStream),
            ],
            child: Consumer<User>(
              builder: (context, value, child) => Scaffold(
                body: TabBarView(
                  controller: _tabController,
                  children: [
                    Container(
                      color: Colors.orange,
                    ),
                    Container(
                      color: Colors.red,
                    ),
                    HomeTab(), // Here is the nested Widget, I can access inside it. 
                    Container(
                      color: Colors.green,
                    ),
                    Container(
                      color: Colors.pink,
                    ),
                  ],
                ),

这是带有我的模态处理程序的 HomeTab。

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

  void _showOverlay(BuildContext context) {
    Navigator.of(context).push(UserProfileModal()); // here I call the Modal and I'm passing the context.
  }

  @override
  Widget build(BuildContext context) {
    User _user = Provider.of<User>(context); // Here It's ok! I can access!

问题出在 ModalRoute 内部

class UserProfileModal extends ModalUI {
  UserProfileModal();

  @override
  Widget buildPage(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
  ) {
    User _user = Provider.of<User>(context); // Here I can't access

错误日志:

错误:在此构建器小部件上方找不到正确的提供程序

这可能是因为您使用了不包含提供程序的BuildContext 您的选择。

谁能澄清这个疑问?谢谢!

【问题讨论】:

    标签: flutter dart provider


    【解决方案1】:
    Navigator.of(context).push(
      Provider<User>.value(
        value: Provider.of<User>(context, listen: false),
        child: UserProfileModal()
      )
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-13
      • 2014-04-11
      • 2013-11-25
      • 2020-09-25
      • 2020-01-23
      • 2019-12-26
      • 2020-06-13
      • 2011-03-04
      相关资源
      最近更新 更多