简体   繁体   中英

Flutter BlocProvider.of() called with a context that does not contain a Bloc of type

I am Navigating from first screen to second screen. I am using Bloc Pattern in the second screen. I am getting the below error:

 BlocProvider.of() called with a context that does not contain a Bloc of type 
   No ancestor could be found starting from the context that was passed to BlocProvider.of<MyBloc>().

    This can happen if:
    1. The context you used comes from a widget above the BlocProvider.
    2. You used MultiBlocProvider and didn't explicity provide the BlocProvider types.

Below is my code of navigation

 BlocProvider<MyBloc>(
            create: (context) => MyBloc());
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          
          return SecondScreen(context);
        }));

and below is my SecondScreen class

  class SecondScreen extends StatefulWidget {
  @override
  _SecondScreenState createState() => _SecondScreenState();
   }

class _SecondScreenState extends State<SecondScreen> {
  MyBloc myBloc;

  @override
  void initState() {
    super.initState();
    myBloc = BlocProvider.of<MyBloc>(context);
    myBloc.add(FetchEvents());
 }

  @override
  Widget build(BuildContext context) {
  return MaterialApp(
  home: Builder(
    builder: (context) {
      return Material(
        child: Scaffold(
          appBar: AppBar(
            title: Text("New Screen"),
            actions: <Widget>[
              IconButton(
                icon: Icon(Icons.refresh),
                onPressed: () {
                  myBloc.add(FetchEvents());
                },
              ),
              IconButton(
                icon: Icon(Icons.info),
                onPressed: () {
                },
              )
            ],
          ),
          body: Container(
            child: BlocListener<MyBloc, MyState>(
              listener: (context, state) {
                if (state is MyErrorState) {
                  Scaffold.of(context).showSnackBar(
                    SnackBar(
                      content: Text(state.message),
                    ),
                  );
                }
              },
              child: BlocBuilder<MyBloc, MyState>(
                builder: (context, state) {
                  if (state is MyInitialState) {
                    return buildLoading();
                  } else if (state is MyLoadingState) {
                    return buildLoading();
                  } else if (state is MyLoadedState) {
                    return buildArticleList(state.yList);
                  } else if (state is MyErrorState) {
                    return buildErrorUi(state.message);
                  }
                },
              ),
            ),
          ),
        ),
      );
    },
  ),
  );
   }

 Widget buildLoading() {
  return Center(
  child: CircularProgressIndicator(),
   );
 }

  Widget buildErrorUi(String message) {
 return Center(
  child: Padding(
    padding: const EdgeInsets.all(8.0),
    child: Text(
      message,
      style: TextStyle(color: Colors.red),
    ),
  ),
  );
 }

  Widget buildArticleList(List<Data> data) {
  return ListView.builder(
  itemCount: data.length,
  itemBuilder: (ctx, pos) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: InkWell(
        child: ListTile(
         
          title: Text(data[pos].title),
          subtitle: Text(data[pos].shortDesc),
        ),
        onTap: () {
          // navigateToArticleDetailPage(context, articles[pos]);
        },
      ),
    );
  },
  );
  }
 }

I have just started learning bloc and stuck here.. Can anyone please help.

I have not added anything related to bloc in main.dart. Is that needed?

The problem lies in this part:

 BlocProvider<MyBloc>(
            create: (context) => MyBloc());
        Navigator.push(context, MaterialPageRoute(builder: (context) {
          
          return SecondScreen(context);
        }));

Change it to this will presumably fix it:

 BlocProvider<MyBloc>(
            create: (context) => MyBloc());
        Navigator.push(context, MaterialPageRoute(
          builder: (routeContext) => SecondScreen(),
        }));

Wrap Used widget inside BlocProvider which will provide the right context to be used.

BlocProvider(
      create: (BuildContext context) {
          return _yourBloc;
      },
      child: Widget(

To use the same bloc in the page you are navigating to use BlocProvider.value().

Change

    Navigator.push(context, MaterialPageRoute(builder: (context) {  
        return SecondScreen(context);
    }));

to

Navigator.push(context, MaterialPageRoute(builder: (context) {
  return BlocProvider<MyBloc>.value(
    value: BlocProvider.of<MyBloc>(context),
    child: SecondScreen(context),
  );
}));

Make sure there is a parent BlocProvider of type MyBloc. Simple Example:

BlocProvider<MyBloc>(
  create: (context) => MyBloc(),
  child: Builder(
    builder: (context) => YourWidget(),//Wrap with Builder to access BlocProvider's context
  ),
);

I also highly recommend checking out this video for better explanation.

Also, this issue might help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM