上下文不包含块 [英] Context does not contain bloc

查看:108
本文介绍了上下文不包含块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下测试代码中,当单击应用程序栏中的按钮时,我试图将事件发送到TestBloc.我将BlocBuilder向外移动到支架周围.但是,当调用_reloadData方法时,会弹出以下错误

in the following test code, I am trying to send an event to the TestBloc, when a button in the app bar is clicked. I moved the BlocBuilder outwards around the scaffold. But when the _reloadData method is called, then the following error pops up

 "BlocProvider.of() called with a context that does not contain a Bloc/Cubit of type TestBloc"

代码

class _TestPageState extends State<TestPage> with UiPresenter {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => sl<TestBloc>()..add(GetDataEvent()),
      child: Scaffold(
        appBar: AppBar(
            title: AppBarTitleWidget(
          title: 'Test',
          onRefreshPressed: () => _reloadData(context),
        )),
        drawer: MainMenuDrawer(),
        body: ContentContainer(
          header: Text(
            'Test',
            style: Theme.of(context).textTheme.headline1,
          ),
          child: _buildBody(context),
    ),
      ),
    );
  }


_reloadData(BuildContext context) {
    BlocProvider.of<TestBloc>(context).add(GetDataEvent());
}

推荐答案

您可以在
下复制粘贴运行完整代码我使用以下完整代码来模拟这种情况
您可以使用 Builder
包装 AppBarTitleWidget 代码段

    appBar: AppBar(title: Builder(builder: (BuildContext context) {
          return AppBarTitleWidget(
            title: "Test",
            onRefreshPressed: () => _reloadData(context),
          );
        }))

工作演示

完整代码

import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class TestBloc extends Cubit<int> {
  /// {@macro counter_cubit}
  TestBloc() : super(0);

  /// Add 1 to the current state.
  void GetDataEvent() => emit(state + 1);

  /// Subtract 1 from the current state.
  void decrement() => emit(state - 1);
}

/*class CounterPage extends StatelessWidget {
  /// {@macro counter_page}
  const CounterPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => CounterCubit(),
      child: CounterView(),
    );
  }
}*/

/// {@template counter_observer}
/// [BlocObserver] for the counter application which
/// observes all [Cubit] state changes.
/// {@endtemplate}
class CounterObserver extends BlocObserver {
  @override
  void onChange(Cubit cubit, Change change) {
    print('${cubit.runtimeType} $change');
    super.onChange(cubit, change);
  }
}

void main() {
  Bloc.observer = CounterObserver();
  runApp(CounterApp());
}

class CounterApp extends MaterialApp {
  /// {@macro counter_app}
  CounterApp({Key key}) : super(key: key, home: TestPage());
}

_reloadData(BuildContext context) {
  BlocProvider.of<TestBloc>(context).GetDataEvent();
}

class TestPage extends StatefulWidget {
  @override
  _TestPageState createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  @override
  Widget build(BuildContext context) {
    final textTheme = Theme.of(context).textTheme;
    return BlocProvider(
      create: (_) => TestBloc(),
      child: Scaffold(
        appBar: AppBar(title: Builder(builder: (BuildContext context) {
          return AppBarTitleWidget(
            title: "Test",
            onRefreshPressed: () => _reloadData(context),
          );
        })),
        body: Center(
          child: BlocBuilder<TestBloc, int>(
            builder: (context, state) {
              return Text('$state', style: textTheme.headline2);
            },
          ),
        ),
        floatingActionButton: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            FloatingActionButton(
              key: const Key('counterView_increment_floatingActionButton'),
              child: const Icon(Icons.add),
              onPressed: () => context.read<TestBloc>().GetDataEvent(),
            ),
            const SizedBox(height: 8),
            FloatingActionButton(
              key: const Key('counterView_decrement_floatingActionButton'),
              child: const Icon(Icons.remove),
              onPressed: () => context.read<TestBloc>().decrement(),
            ),
          ],
        ),
      ),
    );
  }
}

class AppBarTitleWidget extends StatelessWidget {
  final String title;
  final VoidCallback onRefreshPressed;
  const AppBarTitleWidget({
    Key key,
    this.title,
    this.onRefreshPressed,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
        onTap: () {
          onRefreshPressed();
        },
        child: Text(title));
  }
}

这篇关于上下文不包含块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆