3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Flutter】Firestoreのデータを取得時のエラー

Last updated at Posted at 2021-06-06

Firestoreからドキュメント一覧を取得ときに出てきたエラーの解消法を記述します。

FirebaseFirestore.instance.collection('users').getDocuments();は非推奨で、
Listをsnapshotから取り出すときのdocumentsも非推奨のようです。
古いテキストで時々みるので、.getDocuments()をget()にしましょう。

getDocuments()のエラー

The method 'getDocuments' isn't defined for the type 'CollectionReference'.
Try correcting the name to the name of an existing method, or defining a method named 'getDocuments'.

documentsのエラー

The getter 'documents' isn't defined for the type 'QuerySnapshot<Map<String, dynamic>>'.
Try importing the library that defines 'documents', correcting the name to the name of an existing getter, or defining a getter or field named 'documents'.

非推奨の書き方

main.dart
class _MyFirestorePageState extends State<MyFirestorePage> {
  List<DocumentSnapshot> documentList = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: <Widget>[
            ElevatedButton(
              child: Text('ドキュメント一覧取得'),
              onPressed: () async {
                final snapshot =
                    await FirebaseFirestore.instance.collection('users').getDocuments();
                setState(() {
                  documentList = snapshot.documents;
                });
              },
            ),
          ],
        ),
      ),
    );
  }
}

新しい書き方

main.dart
class _MyFirestorePageState extends State<MyFirestorePage> {
  List<DocumentSnapshot> documentList = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: <Widget>[
            ElevatedButton(
              child: Text('ドキュメント一覧取得'),
              onPressed: () async {
                final snapshot =
                    await FirebaseFirestore.instance.collection('users').get();
                setState(() {
                  documentList = snapshot.doc;
                });
              },
            ),
          ],
        ),
      ),
    );
  }
}

このように書くとエラーがでなくなります。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?