我在显示Firebase的数据时遇到问题。下面是我在FutureBuilder中使用的代码。
这是我得到的错误
"The following _CastError was thrown building FutureBuilder<QuerySnapshot<Object?>>(dirty, state: _FutureBuilderState<QuerySnapshot<Object?>>#c8a1c):
type '_JsonQuerySnapshot' is not a subtype of type 'Map<String, dynamic>' in type cast"
验证码
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:errandkaba_app/widgets/custom_action_bar.dart';
import 'package:flutter/material.dart';
class ServicePage extends StatefulWidget {
final String? serviceId;
const ServicePage({Key? key, this.serviceId}) : super(key: key);
@override
_ServicePageState createState() => _ServicePageState();
}
class _ServicePageState extends State<ServicePage> {
final CollectionReference _servicesRef =
FirebaseFirestore.instance.collection("cleaning");
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
FutureBuilder (
future: _servicesRef.get(),
builder: (context, snapshot){
//if has error
if (snapshot.hasError) {
return Scaffold(
body: Center(
child: Text("Error ${snapshot.error}"),
),
);
}
if(snapshot.connectionState == ConnectionState.done){
Map<String, dynamic> documentData = snapshot.data as Map<String, dynamic>;
return ListView(
children: [
Image.network(
"${documentData['images'][0]}"
),
],
);
}
6条答案
按热度按时间ghg1uchk1#
我做了这个
FutureBuilder<DocumentSnapshot<Object?>>(future: _servicesRef.doc(widget.serviceId).get()
并使用了这个Map<String, dynamic> documentData = snapshot.data!.data() as Map<String, dynamic>;
,它工作了。fzwojiic2#
提供类型,然后它将按预期工作,否则你将不得不在使用
data.data()
prop 和乐趣之前将其转换为正确的类型。j8ag8udp3#
创建此函数
然后像这样调用函数
不要忘记将'snapshot'更改为_JsonQuerySnapshot数据
eivgtgni4#
让你的FurtureBuilder像这样FurtureBuilder然后snapshot.data.data()
nc1teljy5#
尝试
snapshot.data
到snapshot.data!.data()
3okqufwl6#
将
FutureBuilder
更改为FutureBuilder<QuerySnapshot>
(或将StreamBuilder
更改为StreamBuilder< QuerySnapshot>
)然后这样转换数据