繁体   English   中英

找不到正确的提供者<StateStreamable<Object?> &gt; 在此 BlocBuilder 上方<StateStreamable<Object?> , 对象?&gt; 小部件

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

我在颤振中遇到了问题......我的应用程序中有两条路线。 第一个用于 HomePage,第二个用于 AuthScreen,即登录和注册。 我在 main() 函数中有一个负责 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(),
        );
      }
    );
  }
}

在第一条路线(HomeScreen)中,我有一个 BlocProvider 并且工作正常,但在第二条路线(AuthScreenWidget)中,我有一个 BlocProvider,但是当我运行应用程序并调试我的代码时,它不会在 BlocProvider 中运行 Create(当我使用断点)它只运行 BlocProvider 并在其中跳转创建。

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: 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());
      }
    );
  }
 

我解决了这个问题......问题是我打电话 BlocProvider 但我不打电话 BlocBuilder 。 我不知道为什么颤动会这样,但是当颤动运行 BlocBuilder 时,然后调用 BlocProvider。 这真的很奇怪,因为首先应该调用 BlocProvider 然后 BlocProvider ...

暂无
暂无

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

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