简体   繁体   中英

When to provide a bloc in a BlocBuilder()?

I'm trying to use cubit for flutter counter app. I wanted to know when to provide a Bloc/Cubit to the bloc parameter in the BlocBuilder(). 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.

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:

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

Then, inside the BlocBuilder , you won't need to specify the bloc property:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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