2020/10/26 Firebase : Cloud Firestore/Usageの訳パート2

 

<<パート1へ

Querying

Cloud Firestoreは、コレクションをクエリするための高度な機能を提供します。 クエリは、1回限りの読み取りまたは変更のサブスクライブの両方で機能します。


Filtering

コレクション内のドキュメントをフィルタリングするには、whereメソッドをコレクション参照にチェーンできます。 フィルタリングは、同等性チェックと「in」クエリをサポートします。 たとえば、年齢が20歳を超えるフィルターユーザーの場合:

FirebaseFirestore.instance
  .collection('users')
  .where('age', isGreaterThan: 20)
  .get()
  .then(...);

 

firestoreデータベースbcffの状況↓

(‘users’コレクションに4つのドキュメントがあります。)

//main.dart
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_signin_button/button_builder.dart';

import './register_page.dart';
import './signin_page.dart';

import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(AuthExampleApp());
}

/// The entry point of the application.
///
/// Returns a [MaterialApp].
class AuthExampleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Firebase Example App',
        theme: ThemeData.dark(),
        home: Scaffold(
          body: AuthTypeSelector(),
        ));
  }
}

/// Provides a UI to select a authentication type page
class AuthTypeSelector extends StatelessWidget {
  // Navigates to a new page
  void _pushPage(BuildContext context, Widget page) {
    Navigator.of(context).push(
      MaterialPageRoute<void>(builder: (_) => page),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Firebase Example App"),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          UserInformationOver29(),
        ],
      ),
    );
  }
}

class UserInformationOver29 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    CollectionReference users = FirebaseFirestore.instance.collection('users');

    FirebaseFirestore.instance
        .collection('users')
        .where('age', isGreaterThan: 29)
        .get()
        .then((qs){
          qs.docs.forEach((doc) {
        print(doc.data()["full_name"]);
      });
    });

    final usersOver29=FirebaseFirestore.instance
        .collection('users')
        .where('age', isGreaterThan: 29);

    users.doc('CzyuXDo6TQuKATaOuKeU')
        .get()
        .then((DocumentSnapshot documentSnapshot) {
      if (documentSnapshot.exists) {
        print('Document exists:${documentSnapshot.data()}');
      }else{
        print('Document does not exist on the database');
      }
    });

    return StreamBuilder<QuerySnapshot>(
      stream: usersOver29.snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) {
          return Text('Something went wrong');
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return Text("Loading");
        }

        //ListViewをColumnの中に入れようとするとエラーが出るので、
        //↓Expandedでラップする必要がある。
        return Expanded(
          child: new ListView(
            children: snapshot.data.docs.map((DocumentSnapshot document) {
              if(document['full_name'] is String) {
                print('👼👼');
                return new ListTile(
                  title: new Text(document.data()['full_name']),
                  subtitle: new Text(document.data()['company']),
                );
              }else{
                return Container();
              }
            }).toList(),
          ),
        );
      },
    );
  }
}

//コンソール
flutter: 👼👼
flutter: 👼👼
flutter: 👼👼
flutter: Document exists:{age: 30, company: TesTes.inc, full_name: 'Test Jirou'}
flutter: Document exists:{age: 30, company: TesTes.inc, full_name: 'Test Jirou'}
flutter: 'Test Jirou'
flutter: Test Sabu
flutter: Test Gorouxx
flutter: 'Test Jirou'
flutter: Test Sabu
flutter: Test Gorouxx

‘age’フィールドの値が29を超えるドキュメントのみ取得して、表示できました。


import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_signin_button/button_builder.dart';

import './register_page.dart';
import './signin_page.dart';

import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(AuthExampleApp());
}

/// The entry point of the application.
///
/// Returns a [MaterialApp].
class AuthExampleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Firebase Example App',
        theme: ThemeData.dark(),
        home: Scaffold(
          body: AuthTypeSelector(),
        ));
  }
}

/// Provides a UI to select a authentication type page
class AuthTypeSelector extends StatelessWidget {
  // Navigates to a new page
  void _pushPage(BuildContext context, Widget page) {
    Navigator.of(context).push(
      MaterialPageRoute<void>(builder: (_) => page),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Firebase Example App"),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          UserInformationOver29_41(),
        ],
      ),
    );
  }
}

class UserInformationOver29_41 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    CollectionReference users = FirebaseFirestore.instance.collection('users');

    FirebaseFirestore.instance
        .collection('users')
        .where('age', isGreaterThan: 29)
        .where('age',isLessThan: 41)
        .get()
        .then((qs){
          qs.docs.forEach((doc) {
        print(doc.data()["full_name"]);
      });
    });

    final usersOver29_41=FirebaseFirestore.instance
        .collection('users')
        .where('age', isGreaterThan: 29)
        .where('age',isLessThan: 41)
        .where('full_name',isEqualTo: 'Test Sabu');

    users.doc('CzyuXDo6TQuKATaOuKeU')
        .get()
        .then((DocumentSnapshot documentSnapshot) {
      if (documentSnapshot.exists) {
        print('Document exists:${documentSnapshot.data()}');
      }else{
        print('Document does not exist on the database');
      }
    });

    return StreamBuilder<QuerySnapshot>(
      stream: usersOver29_41.snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) {
          return Text('Something went wrong');
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return Text("Loading");
        }

        //ListViewをColumnの中に入れようとするとエラーが出るので、
        //↓Expandedでラップする必要がある。
        return Expanded(
          child: new ListView(
            children: snapshot.data.docs.map((DocumentSnapshot document) {
              if(document['full_name'] is String) {
                print('👼👼');
                return new ListTile(
                  title: new Text(document.data()['full_name']),
                  subtitle: new Text(document.data()['company']),
                );
              }else{
                return Container();
              }
            }).toList(),
          ),
        );
      },
    );
  }
}

一瞬Test Sabuが表示された後

‘Something went wrong’

の表示が出た。


import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_signin_button/button_builder.dart';

import './register_page.dart';
import './signin_page.dart';

import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(AuthExampleApp());
}

/// The entry point of the application.
///
/// Returns a [MaterialApp].
class AuthExampleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Firebase Example App',
        theme: ThemeData.dark(),
        home: Scaffold(
          body: AuthTypeSelector(),
        ));
  }
}

/// Provides a UI to select a authentication type page
class AuthTypeSelector extends StatelessWidget {
  // Navigates to a new page
  void _pushPage(BuildContext context, Widget page) {
    Navigator.of(context).push(
      MaterialPageRoute<void>(builder: (_) => page),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Firebase Example App"),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          UserInformationLoveSoccer(),
        ],
      ),
    );
  }
}

class UserInformationLoveSoccer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    CollectionReference users = FirebaseFirestore.instance.collection('users');

    FirebaseFirestore.instance
        .collection('users')
        .where('age', isGreaterThan: 29)
        .where('age',isLessThan: 41)
        .get()
        .then((qs){
          qs.docs.forEach((doc) {
        print(doc.data()["full_name"]);
      });
    });

    final usersEnOrIt=FirebaseFirestore.instance
        .collection('users')
        .where('language', whereIn:['en','it']);

    final usersLoveSoccer=FirebaseFirestore.instance
        .collection('users')
        .where('hobby',arrayContains:'universe');

    usersLoveSoccer.get()
        .then((qs) {
      qs.docs.forEach((doc) {
        print("📱${doc.data()}");
      });
    });


    users.doc('CzyuXDo6TQuKATaOuKeU')
        .get()
        .then((DocumentSnapshot documentSnapshot) {
      if (documentSnapshot.exists) {
        print('Document exists:${documentSnapshot.data()}');
      }else{
        print('Document does not exist on the database');
      }
    });

    return StreamBuilder<QuerySnapshot>(
      stream: usersLoveSoccer.snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) {
          return Text('Something went wrong');
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return Text("Loading");
        }

        //ListViewをColumnの中に入れようとするとエラーが出るので、
        //↓Expandedでラップする必要がある。
        return Expanded(
          child: new ListView(
            children: snapshot.data.docs.map((DocumentSnapshot document) {
                print('👼👼');
                return new ListTile(
                  title: new Text(document.data()['full_name']),
                  subtitle: new Text(document.data()['hobby']),
                );

            }).toList(),
          ),
        );
      },
    );
  }
}
//コンソール
flutter: 📱{age: 40, full_name: Test Sabu, hobby: [baseball, swimming, universe], company: TesTes.inc, language: jp}
flutter: 'Test Jirou'
flutter: Test Sabu
flutter: 📱{age: 40, full_name: Test Sabu, hobby: [baseball, swimming, universe], company: TesTes.inc, language: jp}
flutter: 👼👼
flutter: 'Test Jirou'

コンソールではフィルタリングできているのだが、画面表示でエラー。

よくわからない。


Limiting

クエリから返されるドキュメントの数を制限するには、コレクション参照でlimitメソッドを使用します。

FirebaseFirestore.instance
  .collection('users')
  .limit(2)
  .get()
  .then(...);

 

limitToLastを使用して、コレクションクエリ内の最後のドキュメントに制限することもできます。

FirebaseFirestore.instance
  .collection('users')
  .orderBy('age')
  .limitToLast(2)
  .get()
  .then(...);

Ordering

ドキュメントを特定の値で並べ替えるには、orderByメソッドを使用します。

 

 

 

参考

https://firebase.flutter.dev/docs/firestore/usage

コメントを残す

メールアドレスが公開されることはありません。