firebase - 如何使用其 ID 从 Firebase 中的文档中获取数据?
问题描述
我正在尝试从 Firebase 获取产品,其中所有产品都位于具有不同 ID 的不同文档中。IDE提示没有为对象类型定义data(),不知道怎么解决。问题出在 if 块中,我在 Future 构建器中检查 snapshot.connectionState == ConnectionState.done
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_fashion/Constants/text_styles.dart';
import 'package:flutter_fashion/Views/Widgets/action_bar.dart';
class ProductPage extends StatelessWidget {
final String id;
const ProductPage({
Key? key,
required this.id,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final CollectionReference _productsRef =
FirebaseFirestore.instance.collection("Products");
return Scaffold(
body: Stack(
children: [
FutureBuilder(
future: _productsRef.doc(id).get(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Scaffold(
body: Center(
child: Text(
"Error: ${snapshot.error}",
style: Constants.regularDarkText,
),
),
);
}
if (snapshot.connectionState == ConnectionState.done) {
Map<String, dynamic> documentData = snapshot.data!.data();
return ListView(
children: [
Image.network(documentData['Image'])
],
);
}
return Scaffold(
body: Center(
child: CircularProgressIndicator(
valueColor:
new AlwaysStoppedAnimation<Color>(Color(0xFFFF1E00)),
),
),
);
}),
ActionBar(title: "ProductPage", hasBackArrow: true, hasTitle: false)
],
),
);
}
}
解决方案
我刚刚通过替换 StreamBuilder 修改了代码。请检查以下代码片段。
class ProductPage extends StatelessWidget {
final String id;
const ProductPage({
Key? key,
required this.id,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
StreamBuilder(
stream: FirebaseFirestore.instance
.collection("Products")
.doc(id)
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<DocumentSnapshot<Map<String, dynamic>>>
snapshot) {
if (snapshot.hasError) {
return Scaffold(
body: Center(
child: Text(
"Error: ${snapshot.error}",
style: Constants.regularDarkText,
),
),
);
}
if (snapshot.hasData) {
Map<String, dynamic>? documentData = snapshot.data?.data();
return ListView(
children: [Image.network(documentData!['Image'])],
);
}
return Scaffold(
body: Center(
child: CircularProgressIndicator(
valueColor:
new AlwaysStoppedAnimation<Color>(Color(0xFFFF1E00)),
),
),
);
}),
ActionBar(title: "ProductPage", hasBackArrow: true, hasTitle: false)
],
),
);
}
}
推荐阅读
- javascript - 如果 HTML 返回每个引号之前都带有反斜杠会发生什么?
- r - 将列表列中的函数应用于R中的列
- javascript - 可以通过allowClear = true 选择使用哪个AntD 图标吗?
- swift - 如何让 UIPageViewController 使用过渡样式滚动?
- php - 合并两个 JSON php
- ios - 运行后 UIbutton 拉伸
- c++ - 为什么 vector::erase 不能在具有 const 的类元素上工作
- sql - 如何从有条件的数据库中获取行 - 另一个表中存在另一个?
- verilog - 在 for 循环中使用 assign
- typescript - 当只有一张幻灯片时,有没有办法在 ngx-swiper-wrapper 上禁用导航?