簡體   English   中英

上下文不包含塊

[英]Context does not contain bloc

在下面的測試代碼中,當單擊應用欄中的按鈕時,我試圖向 TestBloc 發送一個事件。 我將 BlocBuilder 圍繞腳手架向外移動。 但是當調用_reloadData方法時,則彈出如下錯誤

 "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));
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM