简体   繁体   English

Flutter 错误:找不到正确的提供程序<user>在此 Wrapper Widget 上方</user>

[英]Flutter Error: Could not find the correct Provider<User> above this Wrapper Widget

After updating/converting a program to null-safety, i'm presented with the following error:将程序更新/转换为空安全后,出现以下错误:


Error: Could not find the correct Provider above this Wrapper Widget错误:在此 Wrapper 小部件上方找不到正确的提供程序

This happens because you used a BuildContext that does not include the provider of your choice.发生这种情况是因为您使用的BuildContext不包括您选择的提供者。 There are a few common scenarios:有几种常见的场景:

  • You added a new provider in your main.dart and performed a hot-reload.您在main.dart中添加了一个新提供程序并执行了热重载。 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.您使用的BuildContext是您尝试读取的提供程序的祖先。

    Make sure that Wrapper is under your MultiProvider/Provider.确保 Wrapper 在您的 MultiProvider/Provider 下。 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>()), ), }

    consider using builder like so:考虑像这样使用builder

     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) { // No longer throws return Text(context.watch<Example>()), } ), }

If none of these solutions work, consider asking for help on StackOverflow: https://stackoverflow.com/questions/tagged/flutter如果这些解决方案都不起作用,请考虑在 StackOverflow 上寻求帮助: https://stackoverflow.com/questions/tagged/flutter


The error also points to the "relevant error-causing widget" for me it was my call to my Wrapper() , Highlighted below:对我来说,该错误还指向“相关的导致错误的小部件”,这是我对Wrapper()的调用,在下面突出显示:

The relevant error-causing widget was: 
  Wrapper Wrapper:file:///home/AlphaUser/AndroidStudioProjects/test/lib/main.dart:78:20

The stack had more lines I didn't think were relevant.堆栈中有更多我认为不相关的行。 (I can add if needed) (如果需要我可以添加)

Current Code in use:当前使用的代码:

Main.dart:主.dart:

import {...};

void main() async {
 WidgetsFlutterBinding.ensureInitialized();
 FirebaseApp app = await Firebase.initializeApp();
 SystemChrome.setPreferredOrientations(
     [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
 Stripe.publishableKey =
     'stripe_publishableKey';
 await Stripe.instance.applySettings();
 runApp(MyApp());
}

class MyApp extends StatelessWidget {
 // This widget is the root of your application.

 @override
 Widget build(BuildContext context) {
   return MultiProvider(
     providers: [
       ChangeNotifierProvider(
         create: (ctx) => Shippments(),
       ),
       ChangeNotifierProvider(
         create: (ctx) => Orders(),
       ),
       ChangeNotifierProvider(
         create: (ctx) => Products(),
       ),
     ],
   
     child: StreamProvider<User>.value(
       
       value: AuthService().user,
       initialData: null,
       child: new MaterialApp(
         title: 'Test',
      

         theme: ThemeData(
           primarySwatch: Colors.grey,
           //   accentColor: Colors.green,
         ),

         debugShowCheckedModeBanner: false,
         //* Login Options **//
         home: Wrapper(), //***<-- Error points to this line.***
         //home: Home(),  //<-- **Works Fine if I use this instead of Wrapper().** //
         //* Login Options **//
         routes: {
           TestLogin.id: (context) => TestLogin(),
           TestSignup.id: (context) => TestSignup(),
           TestForgot.id: (context) => TestForgot(),
           ProductDetailScreen.routeName: (context) => ProductDetailScreen(),
           UserProductsScreen.routeName: (context) => UserProductsScreen(),
           EditProductScreen.routeName: (context) => EditProductScreen(),
           TestPostImageScreen.routeName: (context) => TestPostImageScreen(),
           ProductCheckoutScreen.routeName: (context) =>
               ProductCheckoutScreen(),
           PurchasedProductsScreen.routeName: (context) =>
               PurchasedProductsScreen(),
           SearchProductsScreen.routeName: (context) => SearchProductsScreen(),
           TestFeed.routeName: (context) => TestFeed(),
           ReviewPurchaseScreen.routeName: (context) => ReviewPurchaseScreen(),
           ProfileScreen.routeName: (context) => ProfileScreen(),
           FAQScreen.routeName: (context) => FAQScreen()
         },
       ),
     ),
   );
 }
}

wrapper.dart包装器.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test/home/home.dart';
import 'package:test/home/homeUser.dart';
import 'package:test/models/user.dart' as model;

import '../screens/authenticate/test_login.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_spinkit/flutter_spinkit.dart';

class Wrapper extends StatefulWidget {
  @override
  _WrapperState createState() => _WrapperState();
}

class _WrapperState extends State<Wrapper> {
  get lists => null;
  bool currentAdmin;
  bool loading = false;


  Widget build(BuildContext context) {
    final user = Provider.of<User>(context);


    return FutureBuilder(
      future: _checkUser(user),
      builder: (context, snapshot) {
        String profile = snapshot.data;
        print("profile!!!: $profile");
        if (profile == 'true') {
          print("Snapshot has data: ${snapshot.data}");
          return Home();
        } else if (profile == 'false') {
          print("Snapshot has no data: ${snapshot.data}");
          return HomeUser();
        } else if (user == null) {
          return TestLogin();
        } else {
          //return CircularProgressIndicator();
          return SpinKitFadingCube(
            color: Colors.black,
            size: 25.0,
          );
        }
        //return null;
      },
    );
  }

  _checkUser(User user) async {
     ...
  } //_checkUser()

}

Just want to add that if I replace Wrapper() with Home() the program works, but that will bypass my "user login/register/forgot password" functionality.只想补充一点,如果我用 Home() 替换 Wrapper() 程序可以工作,但这将绕过我的“用户登录/注册/忘记密码”功能。

Any help or guidance will be much appreciated.任何帮助或指导将不胜感激。

you are using the User Provider and didn't create the user provider yet您正在使用用户提供程序,但尚未创建用户提供程序

add the User Provider in the MultiProvider in main在 main 的 MultiProvider 中添加 User Provider

return MultiProvider(
 providers: [
   ChangeNotifierProvider(
     create: (ctx) => Shippments(),
   ),
   ChangeNotifierProvider(
     create: (ctx) => Orders(),
   ),
   ChangeNotifierProvider(
     create: (ctx) => Products(),
   ),
   ChangeNotifierProvider( // add this
     create: (ctx) => User(),
   ),
 ],

 child: StreamProvider<User>.value(

暂无
暂无

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

相关问题 Flutter 中的提供程序出现错误“无法在此 X Widget 上方找到正确的提供程序” - Provider in Flutter with error "Could not find the correct provider above this X Widget" 颤振提供者错误:在此小部件上方找不到正确的提供者 - flutter provider error : Could not find the correct provider above this widget 在此小部件上方找不到正确的提供程序 - Flutter - Could not find the correct Provider above this Widget - Flutter Flutter 错误:找不到正确的提供程序<MyUser>在这个 SettingsForm 小部件上方 - Flutter Error: Could not find the correct Provider<MyUser> above this SettingsForm Widget Flutter 错误:找不到正确的提供程序<cart>在此 ProductLandingPage 小部件上方</cart> - Flutter Error : Could not find the correct Provider<Cart> above this ProductLandingPage Widget 错误:在此小部件 Flutter [PropertiesGrid] 上方找不到正确的提供程序 - Error: Could not find the correct Provider above this widget Flutter [PropertiesGrid] 错误:找不到正确的提供者<User>在此方向器小部件上方 - Error: Could not find the correct Provider<User> above this Directioner Widget StreamProvider:错误:找不到正确的提供者<User>在此应用小部件上方 - StreamProvider: Error: Could not find the correct Provider<User> above this App Widget 错误:在此小部件上方找不到正确的提供者 - Error: Could not find the correct Provider above this widget 错误无法在此小部件上方找到正确的提供程序 - Error could not find the correct provider above this widget
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM