gpt4 book ai didi

flutter - 有没有办法帮助我修复类型 null 不是类型 Map 的子类型?

转载 作者:行者123 更新时间:2023-12-02 18:02:20 25 4
gpt4 key购买 nike

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

这是我的问题:

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

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,
});

然后我继续这里

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'],
);
}
}

现在我在这一行收到错误:null type is not a subtype of Map

var snapshot = snap.data() as Map<String, dynamic>;

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

最佳答案

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

var snapshot = snap.data() as Map<String, dynamic>;

试试这个:

var snapshot = snap.data() != null ? 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'] ??[],
);

关于flutter - 有没有办法帮助我修复类型 null 不是类型 Map<string,dynamic> 的子类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74050909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com