繁体   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