简体   繁体   中英

Flutter snapshot.data() always null

I'm trying to display my Data from Firestore in my Flutter Web App, but I don't get any data.

Basically I just adjusted this example: https://firebase.flutter.dev/docs/firestore/usage#realtime-changes

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

class DataList extends StatefulWidget {
  @override
  _DataListState createState() => _DataListState();
}

class _DataListState extends State<DataList> {
  @override
  Widget build(BuildContext context) {
    CollectionReference collectionReference = FirebaseFirestore.instance.collection('data');

    return StreamBuilder<QuerySnapshot>(
      stream: collectionReference.snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        print('HasData: ${snapshot.hasData}');

        if (snapshot.hasError) {
          print(snapshot.error);
          return Text('Error: ${snapshot.error}');
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return Text("Loading");
        }
        return new ListView(
           children: snapshot.data.docs.map((DocumentSnapshot document) {
              return new ListTile(
              title: new Text(document.data()['name']),
              subtitle: new Text(document.data()['description']),
              );
          }).toList(),
        );
      },
    );
  }
}

But snapshot.hasData is always null and I get this error: [cloud_firestore/unknown] NoSuchMethodError: invalid member on null: 'includeMetadataChanges'

Getting a single Document works fine:

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

class GetData extends StatelessWidget {
  final String documentId;

  GetData(this.documentId);

  @override
  Widget build(BuildContext context) {
    CollectionReference collectionReference = FirebaseFirestore.instance.collection('data');

    return FutureBuilder<DocumentSnapshot>(
      future: collectionReference.doc(documentId).get(),
      builder:
          (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {

        if (snapshot.hasError) {
          return Text("Something went wrong");
        }

        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> data = snapshot.data.data();
          return Text("Name: ${data['name']}, Description: ${data['description']}");
        }

        return Text("loading");
      },
    );
  }
}

What am I doing wrong?

I don't really need it to be Realtime, btw.

Try replacing your firestore script in index.html file with this:

<script src="https://www.gstatic.com/firebasejs/7.20.0/firebase-firestore.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM