异常:错误状态:无法在不存在的 DocumentSnapshotPlatform 上获取字段

时间:2021-02-12 15:08:36

标签: firebase flutter dart google-cloud-firestore

此线程中提到的方法 https://stackoverflow.com/a/50867881/13153574 我正在尝试从 Firestore 获取数据。但得到以下异常。 'name' 字段是一个字符串,'overview' 字段是一个字符串列表。

Bad state: cannot get a field on a DocumentSnapshotPlatform which does not exist

我的代码如下:

import 'package:firebaseAuth/firebaseAuthDemo.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class FindDiseases extends StatefulWidget {
  final User user;

  const FindDiseases({Key key, this.user}) : super(key: key);
  @override
  _FindDiseasesState createState() => _FindDiseasesState();
}

class _FindDiseasesState extends State<FindDiseases> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  FirebaseAuth _auth = FirebaseAuth.instance;

  List diseasesList = [];
  //dynamic data;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.teal,
        automaticallyImplyLeading: false,
        title: Text(
          "Diseases List",
        ),
      ),
      key: _scaffoldKey,
      body: Center(
        child: FlatButton(
          color: Colors.white,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Text("get Disease Record"),
              StreamBuilder<DiseaseRecord>(
                stream: getDisease(),
                builder: (BuildContext c, AsyncSnapshot<DiseaseRecord> data) {
                  if (data?.data == null) return Text("Error");

                  DiseaseRecord r = data.data;

                  return Text("${r.name}");
                },
              ),
            ],
          ),
          onPressed: () {
            getDisease();
          },
        ),
      ),
    );
  }

  Future _signOut() async {
    await _auth.signOut();
  }
}

Stream<DiseaseRecord> getDisease() {
  return FirebaseFirestore.instance.collection("diseases").doc().get().then(
    (snapshot) {
      try {
        return DiseaseRecord.fromSnapshot(snapshot);
      } catch (e) {
        print(">>> Error:"+e.toString());
        return null;
      }
    },
  ).asStream();
}

class DiseaseRecord {

  String name;
  List<String> overview = new List<String>();

  DiseaseRecord.fromSnapshot(DocumentSnapshot snapshot)
      : name = snapshot['name'],
        overview = List.from(snapshot['overview']);
}

数据如下:

name: "name--"
overview: "['a', 'b', 'c']"

1 个答案:

答案 0 :(得分:0)

问题出在这里:

return FirebaseFirestore.instance.collection("diseases").doc().get()

不带任何参数调用 doc() 会创建对新的、不存在的文档的引用。然后对其调用 get(),为不存在的文档返回 DocumentSnapshot,并尝试从中获取字段是无效操作。

您很可能需要知道您尝试加载的疾病文档的 ID,并将其传递给对 doc(id) 的调用。