我正在学习如何通过此视频将 flutter 应用程序连接到 firebase
对我来说一切都完全相同,但在 Android Studio 中出现错误。
错误:没有为类型“Object”定义运算符“[]”。 ([firebase_test] lib\services\database.dart:24 处的 undefined_operator)
错误代码:
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的问题吗?
您正在使用最新的 Firestore 依赖项版本 2.0.0,该版本于 2021 年 5 月 4 日前发布。有重大变更,请阅读此处。
“添加 withConverter”,来自文档:
将 withConverter 函数添加到 CollectionReference、DocumentReference 和 Query (#6015)。这种新方法允许以类型安全的方式与集合/文档进行交互:
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());
}
或者,您可以简单地使用:
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'] ?? '';
使用这个:
doc.get('name') ?? '',
代替:
doc.data()['name'] ?? '',
第一个解决方案:
您的酿造课程:
class Brew {
final String name;
final String sugars;
final int strength;
Brew({ this.name, this.sugars, this.strength });
Brew.fromJson(Map<String, dynamic> json)
: this(
name: json['name'] as String,
sugars: json['sugars'] as String,
strength: json['strength'] as int,
);
Map<String, Object?> toJson() {
return {
'name': name,
'sugars': sugars,
'strength': strength,
};
}
}
您的服务:
List<Brew> _brewListCollectionReference (CollectionReference<Map<String, dynamic>> collectionReference) {
QuerySnapshot<Object?> snapshot = await collectionReference.withConverter<Brew>(
fromFirestore: (snapshots, _ ) => Recipe.fromJson(snapshots.data()!),
toFirestore: (brew, _ ) => brew.toJson(),
).get();
return snapshot.docs.map((doc) => doc.data() as Brew).toList();
}
注意:您的 “collectionReference” 是您的 firebase 集合中的参考。
例如:
firestore.collection('brewCollection')
第二种解决方案:
List<Brew> _brewListFromSnapshot(QuerySnapshot snapshot) {
return snapshot.docs.map((doc) {
return Brew(
name: doc['name'] ?? '',
strength: doc['strength'] ?? 0,
sugars: doc['sugars'] ?? '0',
);
}).toList();}
第三种解决方案:
List<Brew> _brewListFromSnapshot(QuerySnapshot snapshot) {
return snapshot.docs.map((doc) {
return Brew(
name: doc.get('name') ?? '',
strength: doc.get('strength') ?? 0,
sugars: doc.get('sugars') ?? '0',
);
}).toList();}
使用 doc.get() 而不是 []
例如。名称: doc.get('名称') ?? '' ;