Flutter – Cant find bloc in the parent tree when using showDialog

Issue

Im using Flutter and flutter_bloc for a small app, and i used MultiBlocProvider to use multiple BlocProviders that i need in the main home page, and under the home page, there is a MainWidget, which can access the given Bloc easily by: BlocProvider.of<OldBloc>(context)
The MainWidget calls NewWidget as a dialog by: showDialog(context: context, builder: (context) => NewWidget())
The problem is, i cannot access OldBloc from NewWidget(), so i assumed that MainWidget isnt passing its context to NewWidget when using showDialog ?

HomeScreen.dart

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: MultiBlocProvider(
      providers: [
        BlocProvider(
          create: (context) => OldBloc()..add(Initialize()),
        ),
        BlocProvider(
          create: (context) => OtherBloc()..add(Initialize()),
        ),
      ],
      child: Stack(
        children: [
          MainWidget(),
          MenuWidget(),
        ],
      ),
    ));
  }
}

MainWidget.dart

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    return TextField(onTap: () => showDialog(context: context, builder: (context) => NewWidget()));
  }
}

NewWidget.dart

import 'package:flutter/material.dart';

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

  @override
  Widget build(context) {
    return Text(BlocProvider.of<OldBloc>(context).name); // <------- THIS GIVES AN ERROR THAT IT CANT FIND A BLOC OF THE TYPE OldBloc
  }
}

Solution

You have no access to BuildContext in your showDialog method, documentation:

The widget returned by the builder does not share a context with the location that showDialog is originally called from.

The context argument is used to look up the Navigator and Theme for the dialog. It is only used when the method is called.

Its also recommended to use a StatefulBuilder or a custom StatefulWidget, here is an example.

Answered By – Simon Sot

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *