BlocProvider.of() 调用的上下文不包含 MyBloc 类型的 Bloc/Cubit

Posted

技术标签:

【中文标题】BlocProvider.of() 调用的上下文不包含 MyBloc 类型的 Bloc/Cubit【英文标题】:BlocProvider.of() called with a context that does not contain a Bloc/Cubit of type MyBloc 【发布时间】:2021-04-26 10:48:12 【问题描述】:

我尝试使用 BlocProvider 添加 MyBloc,但遇到了上下文问题。错误如下:

在调试模式下在 sdk gphone x86 arm 上启动 lib\main.dart... lib\main.dart:1 √ 内置 build\app\outputs\flutter-apk\app-debug.apk。 在 ws://127.0.0.1:64346/zfCDazZFoQI=/ws

连接到 VM 服务
════════ Exception caught by gesture ═══════════════════════════════════════════
The following assertion was thrown while handling a gesture:
        BlocProvider.of() called with a context that does not contain a Bloc/Cubit of type MyBloc.

        No ancestor could be found starting from the context that was passed to BlocProvider.of<MyBloc>().

        This can happen if the context you used comes from a widget above the BlocProvider.

        The context used was: BlocAddPage(state: _BlocAddPageState#43fc1)

When the exception was thrown, this was the stack
#0      BlocProvider.of
package:flutter_bloc/src/bloc_provider.dart:121
#1      _BlocAddPageState.build.<anonymous closure>
package:example/…/examples/bloc_add.dart:53
#2      _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:993
#3      _InkResponseState.build.<anonymous closure>
package:flutter/…/material/ink_well.dart:1111
#4      GestureRecognizer.invokeCallback

我有以下 UI 类。

class BlocAddPage extends StatefulWidget 
      BlocAddPage(Key key) : super(key: key);
      static const routeName = '/addBloc';
    
      @override
      _BlocAddPageState createState() => _BlocAddPageState();
    
    
    class _BlocAddPageState extends State<BlocAddPage> 
      final Repository repository = Repository();
     
      @override
      Widget build(BuildContext context) 
        return Scaffold(
          appBar: AppBar(
            title: Text(
              'Add',
            ),
          ),
          body: BlocProvider<MyBloc>(
            create: (context) => MyBloc(
                repository: context.read<Repository>(),
    
            child: ElevatedButton(
                onPressed: () 
                  BlocProvider.of<MyBloc>(context)
                      .add(AddEvent());
                ,
                child: const Text('Submit'),
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.all(15),
                  shape: const RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(
                      Radius.circular(40),
                    ),
                  ),
                )),

【问题讨论】:

请显示错误。 添加异常 【参考方案1】:

问题是你的上下文。用Builder 包裹起来。

原因:当调用 BlocProvider.of&lt;MyBloc&gt;(context) 时,of 希望您的 context 在某个位置低于提供者。但在您的情况下,上下文是 _BlocAddPageState 的上下文,它是提供者的祖先。于是我找了个builder来解决。

class BlocAddPage extends StatefulWidget 
      BlocAddPage(Key key) : super(key: key);
      static const routeName = '/addBloc';
    
      @override
      _BlocAddPageState createState() => _BlocAddPageState();
    
    
    class _BlocAddPageState extends State<BlocAddPage> 
      final Repository repository = Repository();
     
      @override
      Widget build(BuildContext context) 
        return Scaffold(
          appBar: AppBar(
            title: Text(
              'Add',
            ),
          ),
          body: BlocProvider<MyBloc>(
            create: (context) => MyBloc(
                repository: context.read<Repository>(),
    
            child: Builder( // this!!!
              builder: (context) => ElevatedButton(
                onPressed: () 
                  BlocProvider.of<MyBloc>(context)
                      .add(AddEvent());
                ,
                child: const Text('Submit'),
                style: ElevatedButton.styleFrom(
                  padding: EdgeInsets.all(15),
                  shape: const RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(
                      Radius.circular(40),
                    ),
                  ),
                ))),

【讨论】:

谢谢兄弟,我也遇到了同样的问题。恭喜你们俩 @SebastianCorradi 很高兴听到这个消息!

以上是关于BlocProvider.of() 调用的上下文不包含 MyBloc 类型的 Bloc/Cubit的主要内容,如果未能解决你的问题,请参考以下文章

BlocProvider.of() 调用的上下文不包含 CounterBloc 类型的 Cubit

使用不包含 PhoneAuthenticationBloc 类型的 Bloc 的上下文调用 BlocProvider.of()。扑

使用不包含 Bloc 类型的上下文调用 Flutter BlocProvider.of()

使用不包含 Bloc 类型的上下文调用 Flutter BLoC BlocProvider.of()

Flutter / BLoC - 使用不包含 ArticlesBloc 类型的 Bloc 的上下文调用 BlocProvider.of()

BlocProvider.of() 使用不包含 Bloc<dynamic,dynamic> 类型的 Bloc 的上下文调用