首页 > 解决方案 > 如何使用其 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)
        ],
      ),
    );
  }
}

标签: firebaseflutterdartgoogle-cloud-firestore

解决方案


我刚刚通过替换 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)
        ],
      ),
    );
  }
}



推荐阅读