颤振:'(DocumentSnapshot<MyObject>) => MyObject' 型不是 '(DocumentSnapshot<Object>) =>



我很难从firebase数据库读取(和显示(数据。我收到以下警告:type'(DocumentSnapshot(=>GivitUser"不是类型"的子类型(DocumentSnapshot(=>GivitUser的

我真的不知道我做错了什么,我试图从DocumentSnapshot转换到DocumentSnapshot,但没有成功。这是我的数据库.dart文件:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:givit_app/models/givit_user.dart';
class DatabaseService {
final String uid;
DatabaseService({@required this.uid});
final CollectionReference userCollection =
FirebaseFirestore.instance.collection('Users');
Future<void> updateGivitUserData(
String email, String fullName, String password, int phoneNumber) async {
return await userCollection.doc(uid).set({
'Email': email,
'Full Name': fullName,
'Password': password,
'Phone Number': phoneNumber,
});
}
Future<GivitUser> getGivitUser(String uid) async {
return await userCollection.doc(uid).get().then((user) => user.data());
}
GivitUser _userDataFromSnapshot(DocumentSnapshot<GivitUser> snapshot) {
return GivitUser(
uid: uid,
email: snapshot.data().email,
fullName: snapshot.data().fullName,
phoneNumber: snapshot.data().phoneNumber,
);
}
Stream<GivitUser> get userData {
return userCollection.doc(uid).snapshots().map(_userDataFromSnapshot);
}
}

这就是我尝试使用database.dart文件并显示数据的地方:

Widget build(BuildContext context) {
GivitUser user = Provider.of<GivitUser>(context);
final DatabaseService db = DatabaseService(uid: user.uid);
return StreamBuilder<GivitUser>(
stream: db.userData,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Loading();
}
print('after getter');
print(snapshot.data);
GivitUser givitUser = snapshot.data;
return Scaffold(
....
....
....

提前感谢,我将感谢任何帮助:(

编辑:错误的屏幕截图:错误屏幕截图

我遇到了这个确切的问题,帮助我的是首先尝试获取集合,然后处理这个特定的文档,也许可以尝试更改此代码:

final DatabaseService db = DatabaseService(uid: user.uid);
return StreamBuilder<GivitUser>(
stream: db.userData,

到此代码:

final DatabaseService db = DatabaseService(uid: user.uid);
return StreamBuilder<GivitUser>(
stream: db.userCollection.doc(db.uid).get(),

文件上说https://firebase.flutter.dev/docs/firestore/usage/#one-时间读取

然后你就可以进入这个领域,比如:

builder: (context, snapshot) {
/...
Map<String, dynamic> data = snapshot.data.data();

我希望它也能帮助你!:(

此行userCollection.doc(uid).snapshots()返回Stream<DocumentSnapshot>,而不是_userDataFromSnapshot参数中声明的Stream<DocumentSnapshot<GivitUser>>

参考

流<文档快照>快照({boolincludeMetadataChanges=false}(

您需要更改以下代码块:

GivitUser _userDataFromSnapshot(DocumentSnapshot<GivitUser> snapshot) {
//...
}

到此:

GivitUser _userDataFromSnapshot(DocumentSnapshot snapshot) {
//...
}

CCD_ 5返回Map<字符串,动态>对象因此,您可以像从Map对象中获取数据一样获取数据。

_userDataFromSnapshot方法可以更新为:

GivitUser _userDataFromSnapshot(DocumentSnapshot snapshot) {
var snapshotData = snapshot.data() as Map;
return GivitUser(
uid: uid,
email: snapshotData['Email'],
fullName: snapshotData['Full Name'],
phoneNumber: snapshotData['Phone Number'],
);
}

相关内容

  • 没有找到相关文章

最新更新