Google cloud firestore 如何在Flatter中从CloudFireStore加载阵列和对象
我有一个类,它有几个嵌入式数组和几个对象。我正在使用flifter,无法理解如何读取/写入Cloud Firestore 我可以读取/写入默认类型的数据成员,如String和Int。下面是我试图用于从DocumentSnapshot实例化对象的构造函数:Google cloud firestore 如何在Flatter中从CloudFireStore加载阵列和对象,google-cloud-firestore,flutter,Google Cloud Firestore,Flutter,我有一个类,它有几个嵌入式数组和几个对象。我正在使用flifter,无法理解如何读取/写入Cloud Firestore 我可以读取/写入默认类型的数据成员,如String和Int。下面是我试图用于从DocumentSnapshot实例化对象的构造函数: class GameReview { String name; int howPopular; List<String> reviewers; } class ItemCount { int item
class GameReview {
String name;
int howPopular;
List<String> reviewers;
}
class ItemCount {
int itemType;
int count;
ItemCount.fromMap(Map<dynamic, dynamic> data)
: itemType = data['itemType'],
count = data['count'];
}
class GameRecord {
// Header members
String documentID;
String name;
int creationTimestamp;
List<int> ratings = new List<int>();
List<String> players = new List<String>();
GameReview gameReview;
List<ItemCount> itemCounts = new List<ItemCount>();
GameRecord.fromSnapshot(DocumentSnapshot snapshot)
: documentID = snapshot.documentID,
name = snapshot['name'],
creationTimestamp = snapshot['creationTimestamp'],
ratings = snapshot['ratings'], // ERROR on run
players = snapshot['players'], // ERROR on run
gameReview = snapshot['gameReview']; // ERROR on run
itemCount = ????
}
更新2:
我没有把整个类的定义放进去,因为我认为如何做其余的事情对我来说是显而易见的,但遗憾的是事实并非如此
我有一个要加载的对象列表。vbandrade的答案是“砰”的一声,但我不太明白应该如何创建对象列表。from(…)正在查找迭代器,而不是创建的类。我确信这是创建一个新对象然后将其添加到列表中的一些变化,但我有点困惑。(请参见上面类中的编辑,特别是“itemCounts”成员。Firebase软件包返回快照中存在的数组/列表类型的列表类型。请尝试将列表转换为列表或列表,然后再分配给变量。 对于GameReview对象,当前,您正在尝试将地图对象指定给该对象, 如果您在GameReview类中编写静态fromMap方法,它将接受map参数并将其转换为所需的对象结构,这将是有益的,正如您在许多Flatters示例代码中看到的那样
class GameReivew{
static GameReivew fromMap(Map<String, dynamic> map){
GameReivew gameReivew = new GameReivew();
gameReivew.name = map["name"];
gameReivew.howPopular = map["howPopular"];
....
return gameReivew;
}
}
class游戏回顾{
静态游戏查看从地图(地图地图){
GameReivew GameReivew=新GameReivew();
gameReivew.name=map[“name”];
gameReivew.howPopular=map[“howPopular”];
....
返回gameReivew;
}
}
从数组加载列表,让框架处理类型转换
对象只是一个映射,就像你在Json中写的那样。我也使用命名构造函数。((仍在学习,不知道如何使用静态构造函数@ganapat))
这是工作代码。我不使用firebase auth,而是使用StreamBuilder小部件
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'model/firebase_auth_service.dart';
void main() async {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
final firebaseAuth = new FirebaseAuthService();
MyApp() {
firebaseAuth.anonymousLogin();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: FlatButton(
color: Colors.amber,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text("get Game Record"),
StreamBuilder<GameRecord>(
stream: getGame(),
builder: (BuildContext c, AsyncSnapshot<GameRecord> data) {
if (data?.data == null) return Text("Error");
GameRecord r = data.data;
return Text("${r.creationTimestamp} + ${r.name}");
},
),
],
),
onPressed: () {
getGame();
},
))));
}
}
Stream<GameRecord> getGame() {
return Firestore.instance
.collection("games")
.document("zZJKQOuuoYVgsyhJJAgc")
.get()
.then((snapshot) {
try {
return GameRecord.fromSnapshot(snapshot);
} catch (e) {
print(e);
return null;
}
}).asStream();
}
class GameReview {
String name;
int howPopular;
List<String> reviewers;
GameReview.fromMap(Map<dynamic, dynamic> data)
: name = data["name"],
howPopular = data["howPopular"],
reviewers = List.from(data['reviewers']);
}
class GameRecord {
// Header members
String documentID;
String name;
int creationTimestamp;
List<int> ratings = new List<int>();
List<String> players = new List<String>();
GameReview gameReview;
GameRecord.fromSnapshot(DocumentSnapshot snapshot)
: documentID = snapshot.documentID,
name = snapshot['name'],
creationTimestamp = snapshot['creationTimestamp'],
ratings = List.from(snapshot['ratings']),
players = List.from(snapshot['players']),
gameReview = GameReview.fromMap(snapshot['gameReview']);
}
你可以用
将以下依赖项添加到pubspec.yaml
dependencies:
# Your other regular dependencies here
json_annotation: ^2.0.0
dev_dependencies:
# Your other dev_dependencies here
build_runner: ^1.0.0
json_serializable: ^2.0.0
并使您的类JsonSerializable()
现在,您可以使用jsonEncode()和jsonDecode()来存储和检索firestore中的对象
对于设置数据:
Firestore.instance
.collection("games")
.document("zZJKQOuuoYVgsyhJJAgc")
.setData(jsonDecode(jsonEncode(gameRecord)));
用于检索数据:
GameRecord.fromJson(jsonDecode(jsonEncode(snapshot.data)));
如果您在从firestore读取数据时由于
List不是List类型的错误而来到这里,您可以使用List.castFrom
例如:
List cards=List.castFrom(cardsListFromFirebase);
签出如果您发布了收藏中的示例文档(以便我们可以看到架构),它可能会帮助人们回答问题。vbandrade,我编辑了问题以添加类的最后一部分。我正在尝试加载对象数组/列表,但我仍然有点困惑(请参见上面编辑的问题).你回答中的其他内容都很棒。你能帮我们这些迷路的人完成这个吗?谢谢!很棒!谢谢你的帮助。@vbandrade当我尝试你的getGame()时方法作为流,除非重新启动应用程序,否则我的StreamBuilder似乎不会听取我的Firebase更改。我来这里是为了了解如何获取字符串列表,如上面代码中的玩家。有人能详细说明为什么列表。from
可以工作,而简单的演员阵容不会工作吗?在这里花了好几个小时….列表。from
是j吗ust从firestore将列表转换为列表需要什么…希望我能早点找到你的答案“尝试将列表转换为列表或在分配变量之前转换列表”>eh?为什么它应该是一个静态方法?为什么我们不为此创建一个命名构造函数:GameReivew.fromMap(Map-Map){//此处的代码相同,但没有返回}
你能回答这个问题吗,兄弟?我用你的代码检索,快照.数据
,这是什么?
import 'package:json_annotation/json_annotation.dart';
part 'game.g.dart';
@JsonSerializable()
class GameReview {
String name;
int howPopular;
List<String> reviewers;
GameReview();
factory GameReview.fromJson(Map<String, dynamic> json) => _$GameReviewFromJson(json);
Map<String, dynamic> toJson() => _$GameReviewToJson(this);
}
@JsonSerializable()
class ItemCount {
int itemType;
int count;
ItemCount();
factory ItemCount.fromJson(Map<String, dynamic> json) => _$ItemCountFromJson(json);
Map<String, dynamic> toJson() => _$ItemCountToJson(this);
}
class GameRecord {
// Header members
String documentID;
String name;
int creationTimestamp;
List<int> ratings = new List<int>();
List<String> players = new List<String>();
GameReview gameReview;
List<ItemCount> itemCounts = new List<ItemCount>();
GameRecord();
factory GameRecord.fromJson(Map<String, dynamic> json) => _$GameRecordFromJson(json);
Map<String, dynamic> toJson() => _$GameRecordToJson(this);
}
flutter packages pub run build_runner build
Firestore.instance
.collection("games")
.document("zZJKQOuuoYVgsyhJJAgc")
.setData(jsonDecode(jsonEncode(gameRecord)));
GameRecord.fromJson(jsonDecode(jsonEncode(snapshot.data)));