Firebase Firestore 错误:未为“Object"类定义运算符“[]" [英] Firebase Firestore Error: The operator '[]' isn't defined for the class 'Object'
问题描述
我正在通过这个视频学习如何将 Flutter 应用程序连接到 Firebase
im learning how to connect flutter app to firebase from this video
对我来说一切都完全一样,但在 Android Studio 中出现了错误.
For me everything is exactly the same, but in Android Studio there is an error.
错误:未为类型Object"定义运算符[]".(undefined_operator at [firebase_test] libservicesdatabase.dart:24)
error: The operator '[]' isn't defined for the type 'Object'. (undefined_operator at [firebase_test] libservicesdatabase.dart:24)
错误代码:
List<Brew> _brewListFromSnapshot(QuerySnapshot snapshot) {
return snapshot.docs.map((doc) {
return Brew(
name: doc.data()['name'] ?? '',
strength: doc.data()['strength'] ?? 0,
sugars: doc.data()['sugars'] ?? '0',
);
}).toList();}
酿造课:
class Brew {
final String name;
final String sugars;
final int strength;
Brew({ this.name, this.sugars, this.strength });
}
有人可以帮我解决这个问题吗?这是 Android Studio 的问题吗?
Can someone help me fix this? Is this a problem with Android Studio?
推荐答案
您正在使用最新的 Firestore 依赖项 2.0.0 版,该版本于 2021 年 5 月 4 日发布.有重大更改,请在此处阅读.
You are using the latest Firestore dependency, version 2.0.0, which was released May 4th, 2021 days ago. There are breaking changes, read about them here.
添加 withConverter",来自文档:
"Add withConverter", From the documentation:
将 withConverter 函数添加到 CollectionReference、DocumentReference 和 Query (#6015).这种新方法允许以类型安全的方式与集合/文档交互:
Add withConverter function to CollectionReference, DocumentReference and Query (#6015). This new method allows interacting with collections/documents in a type-safe way:
final modelsRef = FirebaseFirestore
.instance
.collection('models')
.withConverter<Model>(
fromFirestore: (snapshot, _) => Model.fromJson(snapshot.data()!),
toFirestore: (model, _) => model.toJson(),
);
Future<void> main() async {
// Writes now take a Model as parameter instead of a Map
await modelsRef.add(Model());
final Model model = await modelsRef.doc('123').get().then((s) => s.data());
}
或者,您可以简单地使用:
Or, you can use simply:
String name = snapshot.data.get('name');
//instead of
String name = (snapshot.data.data() as Map<String,dynamic>)['name']
如果你想要整个地图:
Map<String,dynamic> data = snapshot.data.data() as Map<String,dynamic>);
String name = data['name'] ?? '';
这篇关于Firebase Firestore 错误:未为“Object"类定义运算符“[]"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!