在底部对话框对话框的上下文中扑BlocProvider.of(context)

时间:2020-07-27 08:21:53

标签: flutter bloc flutter-bloc

我在父窗口小部件中提供了bloc,并尝试在底部工作表对话框中访问该bloc实例。在底部的对话框中,我有无法访问bloc实例的bloc生成器。

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<DevicePairBloc>(
      create: (context) => DevicePairBloc(),
      child: DeviceList(),
    );
  }
}

class DeviceList extends StatefulWidget {

  @override
  State<StatefulWidget> createState() => _DeviceListState();
}

class _DeviceListState extends State<DeviceList> {
  void showData(BuildContext context) {
    showModalBottomSheet(
        context: context, builder: (context) => ReadingScreen());
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: <Widget>[
        RaisedButton(onPressed: () => showData(context),),
      ],
    );
  }
}

class ReadingScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<DevicePairBloc, DevicePairState>(
      builder: (context, state) {
        return Text("20 mg");
      },);
  }

}

1 个答案:

答案 0 :(得分:0)

如果您也想访问ReadingScreen()中的同一块,则需要用MaterialApp()包装BlocProvider<DevicePairBloc>。目前,您已经将DeviceList()与该bloc提供程序包装在一起,因此它仅对它可用。