Flutter 从Firestore Flatter中的数组中提取数据
我需要从地图中提取数据,我遇到了一些奇怪的问题,我正在使用下面的代码Flutter 从Firestore Flatter中的数组中提取数据,flutter,Flutter,我需要从地图中提取数据,我遇到了一些奇怪的问题,我正在使用下面的代码 return StreamBuilder( stream: Firestore.instance.collection('busquedas').snapshots(), builder: (context, AsyncSnapshot snapshot) { if (snapshot.hasError) { return Center( child: Circu
return StreamBuilder(
stream: Firestore.instance.collection('busquedas').snapshots(),
builder: (context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
return Center(
child: CircularProgressIndicator(),
);
}
DocumentSnapshot _list =
Busquedas.fromMap(snapshot.data.documents) as DocumentSnapshot;
print(_list);
return Container(
child: Text(_list.toString()),
);
});
在我的模型中,我使用了下面的代码,其目的是实时获取数据,并能够在将来进行更新。我留下了一些错误的照片
class-Busquedas{
列出参数;
布斯克达斯({
这个,帕拉米特罗斯,
});
工厂Busquedas.fromJson(字符串str)=>Busquedas.fromMap(json.decode(str));
字符串toJson()=>json.encode(toMap());
工厂Busquedas.fromMap(MapJSON)=>Busquedas(
parametros:List.from(json[“parametros”].map((x)=>Parametro.fromMap(x)),
);
映射toMap()=>{
“parametros”:List.from(parametros.map((x)=>x.toMap()),
};
}
类参数{
参数({
这是奥菲西奥,
这个,费查,
});
一串CIO;
字符串fecha;
工厂Parametro.fromJson(String str)=>Parametro.fromMap(json.decode(str));
字符串toJson()=>json.encode(toMap());
factory Parametro.fromMap(Map json)=>Parametro(
oficio:json[“oficio”],
fecha:json[“fecha”],
);
映射toMap()=>{
“oficio”:oficio,
“费查”:费查,
};
}
该错误表示快照.数据为null
,这就是为什么在null
上调用了documents
您没有检查快照是否确实包含所需的数据。只需添加此检查,并在不可用时返回要显示的内容
此示例使用当前用于在数据不可用时出错的进度指示器。当然,这可以通过添加单独的if
块来修改
返回StreamBuilder(
流:Firestore.instance.collection('busquedas').snapshots(),
生成器:(上下文,异步快照){
if(snapshot.hasrerror | | | |!snapshot.hasData){//如果数据不可用,则添加条件以返回进度指示器
返回中心(
子对象:CircularProgressIndicator(),
);
}
文档快照列表=
Busquedas.fromMap(snapshot.data.documents)作为DocumentSnapshot;
打印(_列表);
返回容器(
子项:文本(_list.toString()),
);
});
此builder
和snapshot
的目的是,您可以根据异步函数的进度精确控制显示的内容
class Busquedas {
List<Parametro> parametros;
Busquedas({
this.parametros,
});
factory Busquedas.fromJson(String str) => Busquedas.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Busquedas.fromMap(Map<String, dynamic> json) => Busquedas(
parametros: List<Parametro>.from(json["parametros"].map((x) => Parametro.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"parametros": List<dynamic>.from(parametros.map((x) => x.toMap())),
};
}
class Parametro {
Parametro({
this.oficio,
this.fecha,
});
String oficio;
String fecha;
factory Parametro.fromJson(String str) => Parametro.fromMap(json.decode(str));
String toJson() => json.encode(toMap());
factory Parametro.fromMap(Map<String, dynamic> json) => Parametro(
oficio: json["oficio"],
fecha: json["fecha"],
);
Map<String, dynamic> toMap() => {
"oficio": oficio,
"fecha": fecha,
};
}