Home > Back-end >  BlocProvider Error: Could not find the correct Provider<CounterBloc>
BlocProvider Error: Could not find the correct Provider<CounterBloc>

Time:05-25

I wrote basic BlocProvider where there is no navigation, but still, I am getting below error

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

Here is the link to the reproducible project on GitHub.

CodePudding user response:

In short, you can just wrap the child in Builder as follows or create a new StatelessWidget or StatefulWidget for the child.

Providers injects the objects to the child element. It turns out the Context object from build() is before the CounterBloc is injected.

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:japa_counter/counter_widget/counter_widget.dart';
import 'counter_widget/model/counter_model.dart';
import 'counter_widget/bloc/counter_bloc.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Japa Counter',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const CounterPage(),
    );
  }
}

class CounterPage extends StatelessWidget {
  const CounterPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return  BlocProvider<CounterBloc>(
      create: (_) => CounterBloc(),
      // -------------------- Wrapped in Builder ----------------------
      child: Builder(
        builder: (context) => Scaffold(
            appBar: AppBar(
              title: const Text("Japa Counter"),
            ),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  FloatingActionButton(
                    onPressed: () =>
                        context.read<CounterBloc>().add(IncrementCounter()),
                    tooltip: 'Increment',
                    child: const Icon(Icons.add),
                  ),
                  const SizedBox(width: 60.0, child: Divider()),
                  FloatingActionButton(
                    onPressed: () =>
                        context.read<CounterBloc>().add(DecrementCounter()),
                    tooltip: 'Decrement',
                    child: const Icon(Icons.remove),
                  ),
                  const CounterWidget(),
                ],
              ),
            ),
          )
      ),
// This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

  • Related