主类中的错误:对空值使用了空检查运算符

时间:2021-06-16 07:35:13

标签: flutter dart

之前它工作正常,但是当我在 Main 中进行与检查用户存在相关的更改时,它开始抛出以下错误。请帮我删除它,有时它也会卡在闪屏中,即使用户不为空。我是新手,所以我按照示例检查了身份验证,并且它工作正常。

The following _CastError was thrown building Builder(dirty):
Null check operator used on a null value

The relevant error-causing widget was: 
  MaterialApp file:///Users/gagansingh/FlutterProjects/practiceflutter/lib/main.dart:93:14
When the exception was thrown, this was the stack: 
#0      _WidgetsAppState._onGenerateRoute.<anonymous closure> (package:flutter/src/widgets/app.dart:1196:48)
#1      MaterialPageRoute.buildContent (package:flutter/src/material/page.dart:54:55)
#2      MaterialRouteTransitionMixin.buildPage (package:flutter/src/material/page.dart:107:27)
#3      _ModalScopeState.build.<anonymous closure>.<anonymous closure> (package:flutter/src/widgets/routes.dart:840:53)
#4      Builder.build (package:flutter/src/widgets/basic.dart:7555:48)
...

颤振版本:-

Flutter 2.0.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision c5a4b4029c (3 months ago) • 2021-03-04 09:47:48 -0800
Engine • revision 40441def69
Tools • Dart 2.12.0

主类:- 错误将我带到 MaterialApp。

void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp( new MyApp());

}

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


class _MyAppState extends State<MyApp>  {

  bool isLoading = true;
  bool isAuth = false;
  bool isRegistered = false;

  @override
  void initState() {
    _checkAuth();

  }

  Future _checkAuth()async{
    final User currentUser = FirebaseAuth.instance.currentUser;
    if( currentUser != null ){
      await FirebaseFirestore.instance.collection('users')
          .where('uid',isEqualTo: currentUser.uid).get()
          .then((QuerySnapshot snapshot)async{
            if(snapshot.docs.length > 0){

              if(snapshot.docs[0].data()['location'] != null){
                setState(() {
                  isRegistered = true;
                  isLoading = false;
                });
              }else{
                setState(() {
                  isAuth = true;
                  isLoading = false;
                });
              }
              print("LoggedIn ${currentUser.uid}");
            }else{
              setState(() {
                isLoading = false;
              });
            }
      });
    }else{
      isLoading = false;

    }
  }

@override
  Widget build(BuildContext context) => ChangeNotifierProvider(

    create:(context) => ThemeProvider(),
    builder:(context,_){
      SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
        statusBarColor:mRed,

      ));
      final themeProvider = Provider.of<ThemeProvider>(context,listen: false);
      return MaterialApp(  /// error takes me here

        debugShowCheckedModeBanner: false,
        supportedLocales: []

routes: {
          '/OTPcreateaccount': (context) => OTPCreateAccount(
            phone: (ModalRoute.of(context).settings.arguments as Map)['phone'],
            ext:   (ModalRoute.of(context).settings.arguments as Map)['countryCode'],
          ),
          '/Dateofbirth': (context) => DateofBirth(),
          '/BottomNav':(context) => BottomNav(),
          '/Splash': (context) =>  Splash(),
          '/Welcome': (context) =>  Welcome(),
          '/CreateAccount': (context) => CreateAccount(),
          '/OTPupdatephone': (context) => OTPphoneupdate(
            phone: (ModalRoute.of(context).settings.arguments as Map)['phone'],
            ext:   (ModalRoute.of(context).settings.arguments as Map)['countryCode'],
          ),
          '/OTPphoneLogin': (context) => OTPphoneLogin(
              phone: (ModalRoute.of(context).settings.arguments as Map)['phone'],
              ext:   (ModalRoute.of(context).settings.arguments as Map)['countryCode'],
          ),
        },

         initialRoute: isLoading
             ? '/Splash'
             :isRegistered
             ? '/BottomNav':
             isAuth ? '/Welcome':
             '/Dateofbirth',
        
      );
    }

1 个答案:

答案 0 :(得分:0)

final User currentUser = FirebaseAuth.instance.currentUser;

您不知何故将 null 作为 currentUser 的值。这就是您收到此错误的原因 Null check operator used on a null value

要解决此错误,您可以使用 await 关键字。

final User currentUser = await FirebaseAuth.instance.currentUser;