getter 'auth' 被调用为 null。接收方:null 尝试调用:auth 我该如何解决这个错误?

时间:2020-12-28 10:32:08

标签: firebase flutter dart firebase-authentication

所以实际上这是我第一次使用 firebase 作为后端我正在构建一个笔记应用程序并尝试使用电子邮件和密码访问身份验证我正在浏览 youtube 视频,因为我是新来的,并遵循了 thid 的步骤视频enter link description here

我的代码是这样的

ma​​in.dart

import 'package:flutter/material.dart';
import 'package:notepad/screens/firstview.dart';
import 'package:notepad/services/auth.dart';
import 'package:notepad/transitions/loading.dart';
import 'authentication/signup.dart';
import 'screens/home.dart';
import 'package:provider/provider.dart';

void main(List<String> args) {
  // SystemChrome.setEnabledSystemUIOverlays([]);
  runApp(
    NotePad(),
  );
}

class NotePad extends StatefulWidget {
  NotePad({Key key}) : super(key: key);

  @override
  _NotePadState createState() => _NotePadState();
}

class _NotePadState extends State<NotePad> {
  @override
  Widget build(BuildContext context) {
    return Provider(
      auth: AuthMethods(),
      child: MaterialApp(
        theme: ThemeData(primaryColor: Colors.white),
        home: HomeController(),
        routes: <String, WidgetBuilder>{
          '/signUp': (BuildContext context) => SignUp(
                authFormType: AuthFormType.signUp,
              ),
          '/LogIn': (BuildContext context) => SignUp(
                authFormType: AuthFormType.signIn,
              ),
          '/home': (BuildContext context) => HomeController(),
        },
        debugShowCheckedModeBanner: false,
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    final AuthMethods auth = Provider.of(context).auth;
    return StreamBuilder(
        stream: auth.onAuthStateChanged,
        builder: (context, AsyncSnapshot<String> snapshot) {
          if (snapshot.connectionState == ConnectionState.active) {
            final bool signedIn = snapshot.hasData;
            // ignore: missing_required_param
            return signedIn ? Home() : FirstView();
          }
          return Loading();
        });
  }
}

class Provider extends InheritedWidget {
  final AuthMethods auth;
  Provider({Key key, Widget child, this.auth}) : super(key: key, child: child);

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) {
    return true;
  }

  static Provider of(BuildContext context) =>
      (context.dependOnInheritedWidgetOfExactType(aspect: Provider)
          as Provider);
}

身份验证方法

import 'package:firebase_auth/firebase_auth.dart';


class AuthMethods {
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  Stream<String> get onAuthStateChanged => _firebaseAuth.onAuthStateChanged.map(
        (FirebaseUser user) => user?.uid,
      );

  // Email password signup
  Future<String> createUserWithEmailAndPassword(
      String email, String password, String name) async {
    final currentUser = await _firebaseAuth.createUserWithEmailAndPassword(
        email: email, password: password);
    //user name
    var userUpdateInfo = UserUpdateInfo();
    userUpdateInfo.displayName = name;
    await currentUser.updateProfile(userUpdateInfo);
    await currentUser.reload();
    return currentUser.uid;
  }

  //Email and password sign in
  Future<String> signInWithEmailAndPassword(
      String email, String password) async {
    return (await _firebaseAuth.signInWithEmailAndPassword(
            email: email, password: password))
        .uid;
  }

  //sign out
  signOut() {
    return _firebaseAuth.signOut();
  }
}

注册页面

import 'package:flutter/material.dart';
import 'package:gradient_widgets/gradient_widgets.dart';
import 'package:notepad/authentication/textfield.dart';
import 'package:notepad/transitions/loading.dart';

enum AuthFormType { signIn, signUp }

class SignUp extends StatefulWidget {
  final AuthFormType authFormType;
  SignUp({Key key, @required this.authFormType}) : super(key: key);

  @override
  _SignUpState createState() => _SignUpState(authFormType: this.authFormType);
}

class _SignUpState extends State<SignUp> {
  AuthFormType authFormType;
  _SignUpState({this.authFormType});
  bool isLoading = false;
  bool _obscureText = true;

  final formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      body: isLoading
          ? Loading()
          : Column(
              children: [
                Container(
                  padding: EdgeInsets.fromLTRB(20.0, 110.0, 20.0, 0.0),
                  child: Stack(
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          buildHeaderText(),
                          Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Form(
                              key: formKey,
                              child: Column(
                                children: [
                                  Column(
                                    children: buildInputs(),
                                  ),
                                  buildTextField(
                                    validator: (val) {
                                      return val.length > 6
                                          ? null
                                          : "Please provide a password more than 6 characters";
                                    },
                                    //controller: passwordTextEditingController,
                                    labelText: 'Password',
                                    obscureText: _obscureText,
                                    suffixIcon: IconButton(
                                      icon: Icon(
                                          _obscureText
                                              ? Icons.remove_red_eye
                                              : Icons.security,
                                          color: Colors.grey),
                                      onPressed: () {
                                        setState(
                                          () {
                                            _obscureText = !_obscureText;
                                          },
                                        );
                                      },
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                          SizedBox(height: 70),
                          Container(
                            child: GradientButton(
                              increaseHeightBy: 10.0,
                              increaseWidthBy: 200.0,
                              child: Text(
                                'Sign Up',
                                style: TextStyle(fontWeight: FontWeight.bold),
                              ),
                              callback: () {
                                //signMeUp();
                              },
                              //TODO: LOGIN KA CALLBACK JAYEGA YAHA PR
                              gradient: LinearGradient(
                                colors: [
                                  Color(0xFFFD7F2C),
                                  Color(0xFFFF6200),
                                  Color(0xFFFD9346),
                                ],
                              ),
                              shadowColor: Gradients.backToFuture.colors.last
                                  .withOpacity(0.25),
                            ),
                          ),
                          SizedBox(
                            height: 10.0,
                          ),
                          Container(
                            child: GradientButton(
                              increaseHeightBy: 10.0,
                              increaseWidthBy: 200.0,
                              child: Text(
                                'Go Back',
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Colors.black),
                              ),
                              callback: () {
                                // Navigator.push(
                                //     context,
                                //     BouncyPageRout(
                                //       widget: LogIn(),
                                //     ));
                              },
                              gradient: LinearGradient(
                                  colors: [Colors.white, Colors.white]),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
    );
  }

  List<Widget> buildInputs() {
    List<Widget> textFields = [];

    // if were in the sign up state
    if (authFormType == AuthFormType.signUp) {
      textFields.add(SizedBox(
        height: 50.0,
      ));
      textFields.add(
        buildTextField(
          validator: (val) {
            return val.isEmpty || val.length < 5
                ? "Please provide a valid User Id."
                : null;
          },
          // controller: userIdTextEditingController,
          labelText: 'User Id',
        ),
      );
    }
    //emailand password
    textFields.add(SizedBox(
      height: 30.0,
    ));
    textFields.add(
      buildTextField(
        validator: (val) {
          return RegExp(
                      r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
                  .hasMatch(val)
              ? null
              : "Please provide a valid Email Id";
        },
        //controller: emailTextEditingController,
        labelText: 'Email',
      ),
    );
    textFields.add(SizedBox(
      height: 30.0,
    ));
    return textFields;
  }

  Stack buildHeaderText() {
    Widget _headerText;
    if (authFormType == AuthFormType.signUp) {
      _headerText = Stack(children: [
        Text(
          'WELCOME\nTO,',
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 45.0,
          ),
        ),
        Text(
          ' Note Pad',
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 20.0,
            color: Colors.grey,
          ),
        ),
      ]);
    } else {
      _headerText = Stack(
        children: [
          Text(
            'HELLO,',
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 65.0,
            ),
          ),
          Text(
            'Nice to see you back',
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 20.0,
              color: Colors.grey,
            ),
          ),
        ],
      );
    }
    return Stack(children: [
      Text(
        'WELCOME\nTO,',
        style: TextStyle(
          fontWeight: FontWeight.bold,
          fontSize: 45.0,
        ),
      ),
      Text(
        ' Note Pad',
        style: TextStyle(
          fontWeight: FontWeight.bold,
          fontSize: 20.0,
          color: Colors.grey,
        ),
      ),
    ]);
  }
}

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  auto_size_text: ^2.1.0
  cloud_firestore: ^0.12.6
  cupertino_icons: ^1.0.0
  firebase_auth: ^0.11.1+10
  flutter_spinkit: ^4.1.2
  gradient_widgets: ^0.5.2
  provider: ^4.3.2+3

我检查了我的代码两次以上我不知道是什么导致了这个错误我试图添加 到这行代码

然后我得到一个新的错误类型 说不能添加到这个

我遇到的主要错误是这个 enter image description here

The following NoSuchMethod Error was thrown building HomeController(dirty):

The getter 'auth' was called on null.
Receiver : null.
Tried Calling: auth

The relevant error-causing widget was HomeController
When the exception was thrown this was the stack

#0 Object.nosuchMethod(dart:carepatch/object_patch.dart:5)
#1 HomeController.build.
#2 StatelessElements.build.
#3 Component Element.performRebuild.
#4 Element.rebuild

...

请看看有没有人能帮忙解决这个错误

0 个答案:

没有答案