简体   繁体   English

何时在 BlocBuilder() 中提供一个块?

[英]When to provide a bloc in a BlocBuilder()?

I'm trying to use cubit for flutter counter app.我正在尝试将 cubit 用于 flutter 计数器应用程序。 I wanted to know when to provide a Bloc/Cubit to the bloc parameter in the BlocBuilder().我想知道何时为 BlocBuilder() 中的 bloc 参数提供 Bloc/Cubit。 I tried to provide one for the below code but it did not work and got the error:我尝试为以下代码提供一个,但它不起作用并出现错误:

Error: Could not find the correct Provider<CounterCubit> above this CounterPage Widget

. .

class CounterPage extends StatelessWidget {
  const CounterPage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
        centerTitle: true,
      ),
      body: BlocBuilder<CounterCubit, int>(
          bloc: CounterCubit(),
          builder: (_, count) => Center(
                child: Text('$count'),
              )),
      floatingActionButton: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: FloatingActionButton(
              onPressed: () => context.read<CounterCubit>().increment(),
              tooltip: 'Increment',
              child: Icon(Icons.add),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: FloatingActionButton(
              onPressed: () => context.read<CounterCubit>().decrement(),
              tooltip: 'Decrement',
              child: Icon(Icons.remove),
            ),
          ),
        ],
      ),
    );
  }
}

This is code for cubit.这是肘的代码。

import 'package:flutter_bloc/flutter_bloc.dart';

class CounterCubit extends Cubit<int> {
  CounterCubit() : super(0);

  void increment() => emit(state + 1);
  void decrement() => emit(state - 1);
}

From the official documentation:来自官方文档:

Only specify the bloc if you wish to provide a bloc that will be scoped to a single widget and isn't accessible via a parent BlocProvider and the current BuildContext.仅当您希望提供一个范围为单个小部件且无法通过父 BlocProvider 和当前 BuildContext 访问的 bloc 时才指定 bloc。

BlocBuilder<BlocA, BlocAState>(
  bloc: blocA, // provide the local bloc instance
  builder: (context, state) {
    // return widget here based on BlocA's state
  }
)

In your case, I would recommend providing your BLoC to the widget tree somewhere above CounterPage like this:在您的情况下,我建议您将 BLoC 提供给CounterPage上方的小部件树,如下所示:

BlocProvider<CounterCubit>(
  create: (BuildContext context) => CounterCubit(),
  child: CounterPage(),
);

Then, inside the BlocBuilder , you won't need to specify the bloc property:然后,在BlocBuilder中,您不需要指定bloc属性:

...
body: BlocBuilder<CounterCubit, int>(
  builder: (_, count) => Center(
    child: Text('$count'),
  )),
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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