Could not find the correct Provider<StateStreamable<Object?>> above this BlocBuilder<StateStreamable<Object?>, Object?> Widget

Viewed 29

I faced with a problem in flutter... I have two routes in my app. in the first one is for HomePage and second is for AuthScreen that is to login and register . I have a provider in main() function that responsible to DI.

Future<void> main() async {
   JustAudioBackground.init(
    androidNotificationChannelId: 'com.ryanheise.bg_demo.channel.audio',
    androidNotificationChannelName: 'Audio playback',
    androidNotificationOngoing: true,
  );
  runApp(Provider<Repository>(
    create: (context) => Repository(
        RemoteDataSource(ApiService.dioInstance()), LocalDataSource()),
    child: MyApp(),
  ));

}

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

  static const defaultFontFamily = 'iran_sans';

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    const primaryTextColor = Color(0xff0D253C);
    const secondaryTextColor = Color(0xff2D4379);
    return Builder(
      builder: (context) {
        return MaterialApp(
          initialRoute: '/auth',
          routes: {
            '/': (context) => const HomeScreen(),
            '/auth': (context) => AuthScreenWidget(),
          },
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            textTheme: const TextTheme(
              subtitle1: TextStyle(
                  fontFamily: defaultFontFamily,
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                  fontSize: 16),
              subtitle2: TextStyle(
                  fontFamily: defaultFontFamily,
                  color: Colors.white,
                  fontWeight: FontWeight.w700,
                  fontSize: 18),
              headline5: TextStyle(
                  fontFamily: defaultFontFamily,
                  color: Colors.black,
                  fontWeight: FontWeight.w700,
                  fontSize: 16),
              headline6: TextStyle(
                  fontFamily: defaultFontFamily,
                  fontWeight: FontWeight.bold,
                  fontSize: 18,
                  color: primaryTextColor),
              headline4: TextStyle(
                  fontFamily: defaultFontFamily,
                  fontWeight: FontWeight.w700,
                  fontSize: 24,
                  color: primaryTextColor),
              bodyText2: TextStyle(
                  fontFamily: defaultFontFamily,
                  color: secondaryTextColor,
                  fontSize: 12),
              bodyText1: TextStyle(
                  fontFamily: defaultFontFamily,
                  color: Color.fromARGB(255, 33, 0, 122),
                  fontSize: 20),
            ),
          ),
          builder: EasyLoading.init(),
        );
      }
    );
  }
}

In the first route(HomeScreen) i have a BlocProvider and that works fine but in the second route(AuthScreenWidget) i have a BlocProvider but when i run the app and debug my code it dose not run the Create inside BlocProvider (when i debug with Break Point) it only runs the BlocProvider and jump the create inside it.

class AuthScreenWidget extends StatefulWidget {
  @override
  State<AuthScreenWidget> createState() => AuthScreenWidgetState();
}

class AuthScreenWidgetState extends State<AuthScreenWidget> {
  String dropdownValue = '+98';
  late final TextEditingController phoneNumber;


  @override
  void initState() {
    super.initState();
    phoneNumber = TextEditingController();
  }

  @override
  void dispose() {
    phoneNumber.dispose();
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Builder(

      builder: (context) {

        return BlocProvider<AuthBloc>(
          create: (context) {
            final authBloc = AuthBloc(
                context.read<Repository>(),
                phoneNumber.text);
            authBloc.add(AuthStarted());
            return authBloc;
          },
          child: Scaffold(
            body: Column(
              children: [
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.fromLTRB(18, 18, 18, 0),
                    child: Align(
                      alignment: Alignment.bottomCenter,
                      child: Directionality(
                        textDirection: TextDirection.rtl,
                        child: TextField(
                          controller: phoneNumber,
                          keyboardType: TextInputType.phone,
                          style: TextStyle(color: Colors.black),
                          decoration: const InputDecoration(
                              border: OutlineInputBorder(),
                              hintText: 'شماره تلفن',
                              contentPadding: EdgeInsets.all(18),
                              icon: Icon(CupertinoIcons.phone)),
                        ),
                      ),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(18, 18, 18, 18),
                  child: Align(
                    alignment: Alignment.bottomCenter,
                    child: Directionality(
                      textDirection: TextDirection.rtl,
                      child: SizedBox(
                        width: double.infinity,
                        height: 53,
                        child: ElevatedButton(
                          style: ButtonStyle(
                            shape: MaterialStateProperty.all<
                                RoundedRectangleBorder>(
                              RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(18.0),
                              ),
                            ),
                          ),
                          child: const Text(
                            'ورود',
                          ),
                          onPressed: () {
                            if (phoneNumber.text != "") {
                              BlocProvider<AuthBloc>(
                                  create: (BuildContext context) {
                                    final authBloc = AuthBloc(
                                        context.read<Repository>(),
                                        phoneNumber.text);
                                    authBloc.add(AuthStarted());
                                    return authBloc;
                                  });
                            }
                          },
                        ),
                      ),
                    ),
                  ),
                ),
                Container(
                  width: double.infinity,
                  child: Column(
                    children: [
                      Padding(
                        padding: const EdgeInsets.fromLTRB(0, 0, 0, 32),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: const [
                            Text("ورود با ایمیل"),
                            Icon(Icons.email, size: 20),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                DropdownButton<String>(
                  value: dropdownValue,
                  icon: const Icon(Icons.phone),
                  elevation: 16,
                  style: const TextStyle(color: Colors.black),

                  onChanged: (String? newValue) {
                    setState(() {
                      dropdownValue = newValue!;
                    });
                  },
                  items: <String>['+98']
                      .map<DropdownMenuItem<String>>((String value) {
                    return DropdownMenuItem<String>(
                      value: value,
                      child: Text(value),
                    );
                  }).toList(),
                ),

                BlocBuilder(builder: (context, state) {
                  if (state is AuthSuccess) {
                    print("success auth");
                    return Container();
                  }
                  return Container();
                })
              ],
            ),
          ),
        );
      }
    );
  }
}

Error :

Error: Could not find the correct Provider<StateStreamable<Object?>> above this BlocBuilder<StateStreamable<Object?>, Object?> Widget

This happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:

- You added a new provider in your `main.dart` and performed a hot-reload.
  To fix, perform a hot-restart.

- The provider you are trying to read is in a different route.

  Providers are "scoped". So if you insert of provider inside a route, then
  other routes will not be able to access that provider.

- You used a `BuildContext` that is an ancestor of the provider you are trying to read.

  Make sure that BlocBuilder<StateStreamable<Object?>, Object?> is under your MultiProvider/Provider<StateStreamable<Object?>>.
  This usually happens when you are creating a provider and trying to read it immediately.

  For example, instead of:

  ```
  Widget build(BuildContext context) {
    return Provider<Example>(
      create: (_) => Example(),
      // Will throw a ProviderNotFoundError, because `context` is associated
      // to the widget that is the parent of `Provider<Example>`
      child: Text(context.watch<Example>().toString()),
    );
  }
  ```

  consider using `builder` like so:

  ```
  Widget build(BuildContext context) {
    return Provider<Example>(
      create: (_) => Example(),
      // we use `builder` to obtain a new `BuildContext` that has access to the provider
      builder: (context, child) {
        // No longer throws
        return Text(context.watch<Example>().toString());
      }
    );
  }
 
1 Answers

I solved the problem... It problem was i call BlocProvider but i don't call BlocBuilder . I don't know why flutter acting like this but when flutter runs the BlocBuilder then call BlocProvider. It's really strange becuses first of all it should be call the BlocProvider and then BlocProvider ...

Related