使用Firestore在StreamBuilder上无法首次获得数据

时间:2019-10-17 15:37:34

标签: firebase flutter google-cloud-firestore

我在Flutter应用程序上获得了跟踪代码。我正在编写食谱应用程序。每当我调试它时,快照第一次返回null。但是第二次快照返回正确的数据。当我的“ malzemelerleAra”类运行时,“ malzemeler”字段未获取数据并返回null异常。

import 'package:flutter/material.dart';
import 'package:dropdownfield/dropdownfield.dart';
import 'package:tarifler/utilities/constants.dart';

class MalzemelerleAra extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _MalzemelerleAraState();
}

int _count = 0;

class _MalzemelerleAraState extends State {
  @override
  Widget build(BuildContext context) {
    List<Widget> extractedChildren = <Widget>[
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          GetMalzemeler(),
          FlatButton(
            color: Colors.green,
            onPressed: () => _changeListCount(true),
            child: Icon(Icons.add),
          ),
          FlatButton(
            color: Colors.red,
            onPressed: () => _changeListCount(false),
            child: Icon(Icons.remove),
          ),
        ],
      ),
      _malzemeAlani(),
    ];
    for (var i = 0; i < _count; ++i) {
      extractedChildren.add(_malzemeAlani());
    }

    return Container(
      child: ListView(
        children: extractedChildren,
      ),
    );
  }

  _malzemeAlani() {
    String malzeme_id;
    Constants constt = new Constants();
    List<String> malzemeler;
    if (constt.malzemeler == null) {
      malzemeler = ["example"];
    }
    else{
      malzemeler = constt.malzemeler;
    }
    return DropDownField(
      onValueChanged: (dynamic value) {
        malzeme_id = value;
      },
      value: malzeme_id,
      required: false,
      hintText: "Malzeme Seç",
      labelText: "Malzemeler",
      items: malzemeler,
    );
  }

  _changeListCount(bool value) {
    setState(() {
      if (value) {
        _count++;
      } else if (!value) {
        _count--;
      }
    });
  }
}

常量类:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class Constants {
  List<dynamic> malzemeler;
  DocumentReference reference;
  Constants (){}

  Constants.fromMap(Map<String, dynamic> map, {this.reference})
      : assert(map["malzemeler"] != null),
        malzemeler = map["malzemeler"];

  Constants.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);
}

class GetMalzemeler extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => GetMalzemelerState();
}

class GetMalzemelerState extends State {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection("malzemeler").snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return LinearProgressIndicator();
        } else {
          final getMalzemeler = Constants.fromSnapshot(snapshot.data.documents.elementAt(0));
          print(getMalzemeler.malzemeler);
          return Text("example");
        }
      },
    );

  }


}

这是我的Firebase数据库: enter image description here 谢谢您的支持

当我尝试第一个答案时,我仍然遇到此错误。

════════ Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building StreamBuilder<QuerySnapshot>(dirty, state: _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#f5a3f):
The getter 'documents' was called on null.
Receiver: null
Tried calling: documents
User-created ancestor of the error-causing widget was
    GetMalzemeler 
lib\screens\malzemelerleAra.dart:19
When the exception was thrown, this was the stack
#0      Object.noSuchMethod  (dart:core-patch/object_patch.dart:51:5)
#1      GetMalzemelerState.build.<anonymous closure> 
package:tarifler/utilities/constants.dart:28
#2      StreamBuilder.build 
package:flutter/…/widgets/async.dart:425
#3      _StreamBuilderBaseState.build 
package:flutter/…/widgets/async.dart:125
#4      StatefulElement.build 
package:flutter/…/widgets/framework.dart:4047
...
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
A RenderFlex overflowed by 99765 pixels on the right.
User-created ancestor of the error-causing widget was
    ListView 

1 个答案:

答案 0 :(得分:0)

尝试将!snapshot.hasData替换为

if(snapshot.data.documents.length > 0) {
   final getMalzemeler = Constants.fromSnapshot(snapshot.data.documents.elementAt(0));
      print(getMalzemeler.malzemeler);
      return Text("example");
} else {
     return LinearProgressIndicator();
}