在Flutter中使用FirebaseAuth类获取当前用户数据时出现了空安全问题。

huangapple go评论52阅读模式
英文:

Null safety Problem while getting current user data using FirebaseAuth class in Flutter

问题

以下是您要的代码翻译部分:

我是Flutter的新手,正在尝试学习Firebase。在下面的代码中,我尝试获取已登录用户的数据。但我得到了**_CastError (Null check operator used on a null value)**。我尝试解决它,但未能完成。我该如何解决它?

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    final user = FirebaseAuth.instance.currentUser!;
    var useremail = "Error";
    if (user.email != null) {   //********问题出现在这里**********
      var useremail = user.email;
    }
    print("$user");
    return Scaffold(
        appBar: AppBar(
            title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("HomeScreen"),
          ],
        )),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(useremail),
              ElevatedButton(
                  onPressed: () {
                    FirebaseAuth.instance.signOut(); 
                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) => MyHomePage(),
                    ));
                  },
                  child: Text("Sign Out")),
            ],
          ),
        ));
  }
}
英文:

I am new in Flutter and trying to learn Firebase. In the given below code,I am trying to get data of currentUser that is logged in. But I get _CastError (Null check operator used on a null value). I tried to solve it but couldn't accomplished it. How can I solve it?

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State&lt;HomeScreen&gt; createState() =&gt; _HomeScreenState();
}

class _HomeScreenState extends State&lt;HomeScreen&gt; {
  @override
  Widget build(BuildContext context) {
    final user = FirebaseAuth.instance.currentUser!; 
    var useremail = &quot;Error&quot;;
    if (user.email != null) {   //********Problem occurs here**********
      var useremail = user.email;
    }
    print(&quot;$user&quot;);
    return Scaffold(
        appBar: AppBar(
            title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(&quot;HomeScreen&quot;),
          ],
        )),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(useremail),
              ElevatedButton(
                  onPressed: () {
                    FirebaseAuth.instance.signOut(); 
                    Navigator.of(context).push(MaterialPageRoute(
                      builder: (context) =&gt; MyHomePage(),
                    ));
                  },
                  child: Text(&quot;Sign Out&quot;)),
            ],
          ),
        ));
  }
}

```

</details>


# 答案1
**得分**: 2

将上面的代码块替换为以下内容:

```dart
final User? user = FirebaseAuth.instance.currentUser; 
var useremail = "Error";
if (user?.email != null) {
  useremail = user!.email!;
}
```

问题在于你在`FirebaseAuth.instance.currentUser`后面加了一个感叹号,表示用户不能为null。

此外,在注销用户之前不要忘记检查用户是否为null。

要了解更多关于空安全的信息,请访问:https://dart.dev/null-safety

<details>
<summary>英文:</summary>

Replace the above block of code by this:

    final User? user = FirebaseAuth.instance.currentUser; 
    var useremail = &quot;Error&quot;;
    if (user?.email != null) {
      useremail = user!.email!;
    }

The problem is that you gave an exclamation after FirebaseAuth.instance.currentUser, that stated that the user can&#39;t be null.

Also, don&#39;t forget to check if user is null or not before signing him out.

To learn more about null safety, visit: https://dart.dev/null-safety

</details>



# 答案2
**得分**: 0

除了检查 user.email != null 外,还要验证 user 对象不为 null。

<details>
<summary>英文:</summary>

In addition to checking that user.email != null , also verify that the user object is not null.

</details>



huangapple
  • 本文由 发表于 2023年2月16日 19:19:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75471513.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定