有没有办法帮助我修复类型 null 不是类型 Map<string,dynamic> 的子类型?

oli*_*nde 2 dart flutter dart-null-safety

我已经研究 flutter 几个月了,我开始了解如何解决 null 安全问题,但这对我来说真的很复杂,我希望得到帮助。

这是我的问题:

每当我尝试登录时,都会收到此错误: 'Null' 类型不是 Map<string,dynamic> 类型的子类型 我尽力找出问题所在,但我无法,任何帮助都将是拯救生命...

import 'package:cloud_firestore/cloud_firestore.dart';

class User {
 final String email;
 final String uid;
 final String photoUrl;
 final String username;
 final String bio;
 final List followers;
 final List following;

const User({
  required this.email,
  required this.uid,
  required this.photoUrl,
  required this.username,
  required this.bio,
  required this.followers,
  required this.following,
 });
Run Code Online (Sandbox Code Playgroud)

然后我继续在这里

Map<String, dynamic> toJson() => {
    "username": username,
    "uid": uid,
    "email": email,
    "photoUrl": photoUrl,
    "bio": bio,
    "followers": followers,
    "following": following,
  };

   static User fromSnap(DocumentSnapshot snap) {
   var snapshot = snap.data() as Map<String, dynamic>;

  return User(
     username: snapshot['username'],
     uid: snapshot['uid'],
     email: snapshot['email'],
     photoUrl: snapshot['photoUrl'],
     bio: snapshot['bio'],
     followers: snapshot['followers'],
     following: snapshot['following'],
      );
     }
    }
Run Code Online (Sandbox Code Playgroud)

现在我在这一行收到错误: null type is not a subtype of Map<string,dynamic>

var snapshot = snap.data() as Map<String, dynamic>;
Run Code Online (Sandbox Code Playgroud)

这都是我的问题,提前致谢。

eam*_*ein 5

您的snapshot值是nullable,并且您尝试将其转换为map,而不是这样:

\n
var snapshot = snap.data() as Map<String, dynamic>;\n
Run Code Online (Sandbox Code Playgroud)\n

尝试这个:

\n
var snapshot = snap.data() != null ? snap.data() as Map<String, dynamic> : {};\n
Run Code Online (Sandbox Code Playgroud)\n

还将您的回报更改为:

\n
return User(\n     username: snapshot['username']??\xe2\x80\x9d\xe2\x80\x9d,\n     uid: snapshot['uid'] ??\xe2\x80\x9d\xe2\x80\x9d,\n     email: snapshot['email'] ??\xe2\x80\x9d\xe2\x80\x9d,\n     photoUrl: snapshot['photoUrl'] ??\xe2\x80\x9d\xe2\x80\x9d,\n     bio: snapshot['bio'] ??\xe2\x80\x9d\xe2\x80\x9d,\n     followers: snapshot['followers'] ??[],\n     following: snapshot['following'] ??[],\n  );\n
Run Code Online (Sandbox Code Playgroud)\n