首页 > 解决方案 > 例外:状态不佳:无法获取 DocumentSnapshotPlatform 上不存在的字段

问题描述

此线程中提到的方法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']"

标签: firebaseflutterdartgoogle-cloud-firestore

解决方案


问题在这里:

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

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

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


推荐阅读