簡體   English   中英

可空值和不可空值

[英]Nullable and non-nullable values

我正在使用 flutter 和 firebase 進行用戶身份驗證。

我遇到的問題是以下代碼段:

import 'package:flutter/material.dart';

class AuthClass {

  final FirebaseAuth auth = FirebaseAuth.instance;

//Signing in a user
  Future<String> signIn({String email, String password}) async {
    try {
      await auth.signInWithEmailAndPassword(
          email: email,
          password: password
      );
      return "Welcome!";
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        return 'No user found for that email.';
      } else if (e.code == 'wrong-password') {
        return 'Wrong password provided for that user.';
      }
    }
  }
}

我調用 signIn function 的上下文就在這里:

import 'package:flutter_client_app/Provider/auth_provider.dart';
import 'package:flutter_client_app/Screens/home.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  TextEditingController _email = TextEditingController();
  TextEditingController _password = TextEditingController();

  bool isLoading = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text("Login"),),

        body: isLoading == false ? Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              TextFormField(
                  controller: _email,
                  decoration: InputDecoration(
                      hintText: "Email"
                  )
              ),
              const SizedBox(height: 30,),

              TextFormField(
                  controller: _password,
                  decoration: InputDecoration(
                      hintText: "Password"
                  )
              ),

              FlatButton(     <=============================================================
                  color: Colors.blue,
                  onPressed: () {
                    print (_email.text);
                    print (_password.text);
                    setState(() {
                      isLoading = true;
                    });
                    AuthClass()
                        .signIn(
                          email: _email.text.trim(),
                          password: _password.text.trim())
                        .then((value) {
                      if (value == "Welcome!") {
                        setState(() {
                          isLoading = false;
                        });
                        Navigator.pushAndRemoveUntil(
                            context,
                            MaterialPageRoute(builder: (context) => HomePage()),
                                (route) => false);
                      } else {
                        setState(() {
                          isLoading = false;
                        });
                        ScaffoldMessenger.of(context)
                            .showSnackBar(SnackBar(content: Text(value)));
                      }
                    }); <==============================================================
                  },
                  child: Text("Login to account")),
              SizedBox(
                height: 20,
              ),
              // GestureDetector(
              //   onTap: () {
              //     Navigator.pushAndRemoveUntil(
              //         context,
              //         MaterialPageRoute(
              //             builder: (context) => RegisterPage()), (route) => false);
              //   },
              //   child: Text("Don't have an account? Register"),
              // ),
              //
              // const SizedBox(
              //   height: 10,
              // ),
              // GestureDetector(
              //   onTap: () {
              //     Navigator.pushAndRemoveUntil(
              //         context, MaterialPageRoute(builder: (context) => ResetPage()), (route) => false);
              //   },
              //   child: Text("Forgot Password? reset"),
              //),
            ],
          ),
        ) : Center(
            child: CircularProgressIndicator(),
        )
    );
  }
}

我得到的錯誤如下:

29:33:錯誤:參數“email”的值不能為“null”,因為它的類型為“String”,但隱含的默認值為“null”。

29:47:錯誤:參數“password”的值不能為“null”,因為它的類型為“String”,但隱含的默認值為“null”。

29:18:錯誤:必須返回非空值,因為返回類型“字符串”不允許 null。

我已經成功打印出記錄在 TextFormField 中的值,但是當調用 signIn async function 時,我的問題就出現了。

您正在使用null-safety功能。 You can disable it by change dart sdk in pubspec.yaml to environment: sdk: ">=2.7.0 <3.0.0" instead of environment: sdk: ">=2.12.0 <3.0.0" or make a your class null-safety 此外,您應該在catch部分返回ifelse值。

import 'package:flutter/material.dart';

class AuthClass {

  final FirebaseAuth auth = FirebaseAuth.instance;

  //Signing in a user with nullable parameters
  Future<String> signIn({String? email, String? password}) async {
    try {
      await auth.signInWithEmailAndPassword(
          email: email as String,
          password: password as String,
      );
      return "Welcome!";
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        return 'No user found for that email.';
      } else if (e.code == 'wrong-password') {
        return 'Wrong password provided for that user.';
      }
      else return "No Clear Error"
    }
  }
  //Signing in a user with default value parameters
  Future<String> signIn({String email = "", String password = ""}) async {
    try {
      await auth.signInWithEmailAndPassword(
          email: email,
          password: password,
      );
      return "Welcome!";
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        return 'No user found for that email.';
      } else if (e.code == 'wrong-password') {
        return 'Wrong password provided for that user.';
      }
      else return "No Clear Error"
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM