【发布时间】:2023-01-29 21:07:55
【问题描述】:
我必须对我之前的问题做一些更改,因为现在用户生日(年、月和日)未显示在 UI 上,并且还在控制台上显示此错误“ E/flutter ( 7311): [ERROR:flutter/runtime /dart_vm_initializer.cc(41)] 未处理的异常:错误状态:DocumentSnapshotPlatform 中不存在字段”
但是当评论生日时,其他数据显示得很好。
我不明白获取生日的错误是什么。
数据库生日参数截图
我只想显示年月日
在显示这个的 UI 上
代码
模型类
class Users {
String? id;
String? name;
String? url;
DateTime? birthday;
Users({
this.id,
this.name,
this.url,
this.birthday,
});
Users.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
url = json['url'];
birthday = json["birthday"]?.toDate();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['url'] = this.url;
data['birthday'] = this.birthday;
return data;
}
}
控制器类
User? user = FirebaseAuth.instance.currentUser;
UserModel loggedInUser = UserModel();
@override
Future<List<Users>> fetchRecords() async {
var records = await FirebaseFirestore.instance.collection('Users').get();
return mapRecords(records);
}
List<Users> mapRecords(QuerySnapshot<Map<String, dynamic>> records) {
var list = records.docs
.map(
(user) => Users(
id: user.id,
name: user['name'],
url: user['url'],
birthday: user['birthday'].toDate(),
),
)
.toList();
return list;
}
用户界面代码
SizedBox(
child: SizedBox(
width: width * 0.94,
height: height * 0.95,
child: FutureBuilder<List<Users>>(
future: fetchRecords(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
List<Users> data = snapshot.data ?? [];
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return (SizedBox(
height: 100,
child: Card(
color:
Colors.white.withOpacity(0.8),
shape: RoundedRectangleBorder(
side: const BorderSide(
color: Colors.greenAccent,
),
borderRadius:
BorderRadius.circular(20.0),
),
child: Column(
children: <Widget>[
ListTile(
leading: Image.network(
'${data[index].url}',
height: 30,
fit: BoxFit.cover,
),
title: Text(
'${data[index].name}' ??
' '),
subtitle: Text(
'${data[index].birthday?.year}/${data[index].birthday?.month}/${data[index].birthday?.day}'),
trailing: ElevatedButton(
child: Text('View'),
onPressed: () {
},
))
],
),
),
));
});
}
}))),
如何解决此错误并获取用户生日?
【问题讨论】:
-
pet这一行birthday: pet['birthday'].toDate()来自哪里? -
哦..对不起我的错,我改变了它但仍然是同样的错误
-
@nibbo 你知道我的代码有什么错误吗
-
您好根据您的错误更新了代码。
标签: flutter firebase datetime google-cloud-firestore