我刚刚更新到Dart2和Flutter sdk:'>2.12.0<3.0.0',现在我得到了一个错误:
return Scaffold(
body: FutureBuilder(
future: usersRef.doc(widget.accountiD).get(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return buildLoading();
}
UserAccount currentUser = UserAccount.fromDocument(snapshot.data);
return ListView(
children: []
);
}
),
);
错误发生在快照上。data说参数类型为"Object?"无法分配给参数类型"DocumentSnapshot">该怎么办?我需要帮助。
将其更改为:
return Scaffold(
body: FutureBuilder<DocumentSnapshot>(
future: usersRef.doc(widget.accountiD).get(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return buildLoading();
}
UserAccount currentUser = UserAccount.fromDocument(snapshot.data.data()); //you need to add "data()" to access the map of objects inside snapshot.data
return ListView(
children: []
);
}
),
);
我不久前遇到了同样的问题,只是又遇到了,忘记了把我带到这里的解决方案。
我发现的解决方案是使用";作为";关键词
示例
snapshot.data as int
或
snapshot.data as String
只需对任何其他数据类型执行相同操作。希望能有所帮助。答复发送自。
return Scaffold(
body: FutureBuilder<DocumentSnapshot>(
future: usersRef.doc(widget.accountiD).get(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return buildLoading();
}
UserAccount currentUser = UserAccount.fromDocument(snapshot.data!); //(Add after snapshot.data)
return ListView(
children: []
);
}
),
);
您可以尝试UserAccount.fromDocument(快照为DocumentSnapshot)这种类型的强制转换可能有助于转换DocumentSnapshot的对象转换需求。
2022年的工作代码。它会监听文档上的更改并对其进行更新:
Widget build(BuildContext context) {
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('tasks')
.doc('B2tRytXodOwoYA1U4gK2')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
TaskModel task =
TaskModel.fromSnapshot(snapshot.data as DocumentSnapshot);
return Text(task.category);
});
}
}
你需要一个如下的模型:
import 'package:cloud_firestore/cloud_firestore.dart';
class TaskModel {
String _category = '';
String get category => _category;
TaskModel.fromSnapshot(DocumentSnapshot snapshot) {
_category = snapshot['category'];
}
}
或者,您可以在没有类的情况下以映射的形式获取值。