LoginSignup
0
0

More than 1 year has passed since last update.

Firebase Firestore Flutterでの環境設定

Posted at

Firebaseのプロジェクトを作成したら、FirebaseコンソールCloud Firestoreに移動し、ワークフローに従って開始モードの選択(テストモードorロックモード)→ロケーションの設定完了ボタンの順に進めて頂いたら、

1.FlutterとFirebaseの初期化と紐付け
2.プラグインのインストール

flutter pub add cloud_firestore

3.flutter runで再ビルド
4.CocoaPods1.9.1以降にアップグレードされているか確認。

gem install cocoapods

5.パッケージの追加

pubspec.yaml
dependencies:
  flutter:
    sdk: flutter

  cloud_firestore: ^X.X.X

6.iOSのエラーが出ていなければインスタンスを初期化し使用可能。

import 'package:cloud_firestore/cloud_firestore.dart';

final db = FirebaseFirestore.instance;

それではいくつかメソッドを紹介していきます。
スクリーンショット 2022-09-30 16.39.38.png
こちらのボタンから("dbs")コレクションを作成し、

データを追加(.add( ))

import 'package:cloud_firestore/cloud_firestore.dart';
// Firestoreの("dbs")コレクションを参照
final db = FirebaseFirestore.instance.collection("dbs");

// 別で作成したStopWatchオブジェクトをもとにデータを入れ保存
Future<String> createTimer(String uid, StopWatch db) async {
  final timer = await db.add({
    "uid": uid,
    "category": db.category,
    "minutes": db.minutes,
    "startedAt": DateTime.now(),
  });
  return timer.id;
}

追加したデータを取り出す(.get( ))

Future<StopWatch?> findTimer(String id) async {
  final timer = await dbs.doc(id).get();
  if (!timer.exists) return null;
  return StopWatch(
      category: timer['category'],
      minutes: timer['minutes'],
      startedAt: (timer['startedAt'] as Timestamp).toDate());
}

データの上書き(.update( ))

Future<void> updateTimer(
    String id, num minutes, DateTime startedAt, String category) async {
  await dbs.doc(id).update(
      {'category': category, 'minutes': minutes, 'startedAt': startedAt});
}

データの削除(.delete( ))

Future<void> deleteTimer(String id) async {
  await dbs.doc(id).delete();
}

と、まだまだドキュメントを読むと色々な組み合わせで応用できます。

0
0
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
0
0