微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

未处理的异常:错误:在此MyApp小部件上方找不到正确的Provider <User>

如何解决未处理的异常:错误:在此MyApp小部件上方找不到正确的Provider <User>

我正在构建用于注册登录的示例应用程序, 第一页显示的是使用Firebase的移动身份验证,成功身份验证后,我从firebase中获取uid,并尝试与我的云Firestore集合(“用户”)的documenteID匹配。如果它为空,则我想显示SignupScreen(),否则,请显示HomeScreen()。

这是我的简单逻辑,但是我不知道发生这种类型的错误

我也尝试了一些不同的代码

ChangeNotifierProvider(
      create: (BuildContext context) => User(),),

但是它仍然显示错误

这是我的代码

main.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:Flutter/material.dart';
import 'package:phone_auth_example/homePage.dart';
import 'package:phone_auth_example/signup_screen.dart';
import 'package:provider/provider.dart';

import './signUpPage.dart';
import './user.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    final FirebaseAuth auth = FirebaseAuth.instance;

    var checkUser = false;
    void isNewUser() async {
      final FirebaseUser user = await auth.currentUser();
      final uid = user.uid;
      Provider.of<User>(context,listen: false).isUserNew(uid);
      checkUser = Provider.of<User>(context,listen: false).checkUser;
    }

    isNewUser();

    return MultiProvider(
        providers: [
          ChangeNotifierProvider.value(
            value: User(),],child: MaterialApp(
          debugShowCheckedModeBanner: false,home: StreamBuilder(
            // ignore: deprecated_member_use
            stream: FirebaseAuth.instance.onAuthStateChanged,builder: (ctx,usersnapshot) {
              if (usersnapshot.hasData) {
                if (checkUser) {
                  return SignupScreen();
                } else {
                  return HomePage();
                }
              } else if (usersnapshot.hasError) {
                return CircularProgressIndicator();
              }
              return LoginPage();
            },routes: {
            SignupScreen.routeName: (ctx) => SignupScreen(),},);
  }
}

user.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:Flutter/cupertino.dart';

enum UserType {
  Member,HigherAuthority,SecurityGuard,}

enum UserStatus {
  Owner,Renter,}

enum OccupancyStatus {
  CurrentlyResiding,EmptyHouse,}

class User with ChangeNotifier {
  final String id;
  final UserType userType;
  final String mobileNumber;
  final String name;
  final String email;
  final String password;
  final String houseNumberId;
  final UserStatus userStatus;
  final OccupancyStatus occupancyStatus;

  User({
    @required this.id,@required this.userType,@required this.mobileNumber,@required this.name,@required this.email,@required this.password,@required this.houseNumberId,@required this.userStatus,@required this.occupancyStatus,});

  bool checkUser;

  Future<void> isUserNew(String userId) async {
    // Get data from firestore
    DocumentSnapshot user =
        await Firestore.instance.collection('user').document(userId).get();

    //print(variable.data == null);

    // Check whether userId is in collection or not
    checkUser = (user.data == null) ? true : false;
  }
}

首先,它是打开的LoginPage(),它运行良好,然后,无论uid是否匹配,都直接转到HomePage()而不是signupPage(),所以这是一个问题,并且显示错误

错误

I/Choreographer(10505): Skipped 246 frames!  The application may be doing too much work on its main thread.
E/Flutter (10505): [ERROR:Flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: Error: Could not find the correct Provider<User> above this MyApp Widget
E/Flutter (10505):
E/Flutter (10505): This likely happens because you used a `BuildContext` that does not include the provider
E/Flutter (10505): of your choice. There are a few common scenarios:
E/Flutter (10505):
E/Flutter (10505): - The provider you are trying to read is in a different route.
E/Flutter (10505):
E/Flutter (10505):   Providers are "scoped". So if you insert of provider inside a route,then
E/Flutter (10505):   other routes will not be able to access that provider.
E/Flutter (10505):
E/Flutter (10505): - You used a `BuildContext` that is an ancestor of the provider you are trying to read.
E/Flutter (10505):
E/Flutter (10505):   Make sure that MyApp is under your MultiProvider/Provider<User>.
E/Flutter (10505):   This usually happen when you are creating a provider and trying to read it immediately.
E/Flutter (10505):
E/Flutter (10505):   For example,instead of:
E/Flutter (10505):
E/Flutter (10505):   ```
E/Flutter (10505):   Widget build(BuildContext context) {
E/Flutter (10505):     return Provider<Example>(
E/Flutter (10505):       create: (_) => Example(),E/Flutter (10505):       // Will throw a ProviderNotFoundError,because `context` is associated
E/Flutter (10505):       // to the widget that is the parent of `Provider<Example>`
E/Flutter (10505):       child: Text(context.watch<Example>()),E/Flutter (10505):     ),E/Flutter (10505):   }
E/Flutter (10505):   ```
E/Flutter (10505):
E/Flutter (10505):   consider using `builder` like so:
E/Flutter (10505):
E/Flutter (10505):   ```
E/Flutter (10505):   Widget build(BuildContext context) {
E/Flutter (10505):     return Provider<Example>(
E/Flutter (10505):       create: (_) => Example(),E/Flutter (10505):       // we use `builder` to obtain a new `BuildContext` that has access to the provider
E/Flutter (10505):       builder: (context) {
E/Flutter (10505):         // No longer throws
E/Flutter (10505):         return Text(context.watch<Example>()),E/Flutter (10505):       }
E/Flutter (10505):     ),E/Flutter (10505):   }
E/Flutter (10505):   ```
E/Flutter (10505):
E/Flutter (10505): If none of these solutions work,consider asking for help on StackOverflow:

解决方法

您的问题是,您正在尝试调用Provider.of<User>(context,listen: false).checkUser,而上下文中尚未提供任何提供者(因为您使用MultiProvider在树的下方)。

您应该向上移动MultiProvider。这是一个实现示例:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:phone_auth_example/homePage.dart';
import 'package:phone_auth_example/signup_screen.dart';
import 'package:provider/provider.dart';

import './signUpPage.dart';
import './user.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    @override
    Widget build(BuildContext context) {
      return MultiProvider(
        providers: [
          ChangeNotifierProvider<User>(
            create: (context) => User(),),],builder: (BuildContext context,Widget child) {
          final FirebaseAuth auth = FirebaseAuth.instance;

          var checkUser = false;
          void isNewUser() async {
            final FirebaseUser user = await auth.currentUser();
            final uid = user.uid;
            Provider.of<User>(context,listen: false).isUserNew(uid);
            checkUser = Provider.of<User>(context,listen: false).checkUser;
          }

          isNewUser();

          return child;
        },child: MaterialApp(
          debugShowCheckedModeBanner: false,home: StreamBuilder(
            // ignore: deprecated_member_use
            stream: FirebaseAuth.instance.onAuthStateChanged,builder: (ctx,userSnapshot) {
              if (userSnapshot.hasData) {
                if (checkUser) {
                  return SignupScreen();
                } else {
                  return HomePage();
                }
              } else if (userSnapshot.hasError) {
                return CircularProgressIndicator();
              }
              return LoginPage();
            },routes: {
            SignupScreen.routeName: (ctx) => SignupScreen(),},);
    }
  }
}

此外,还有2种对ChangeNotifier的滥用:

1 User类应该扩展 ChangeNotifier。

替换

class User with ChangeNotifier

使用

class User extends ChangeNotifier
如果已经创建了ChangeNotifier实例(在您的情况下为User):here is a great explaination of the use cases,则应使用

2 ChangeNotifierProvider.value。既然没有,那么您应该像这样使用ChangeNotifierProvider:

ChangeNotifierProvider<User>(
      create: (context) => User(),child: ...
)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。