0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Flutter】FirebaseFirestoreにデータを追加する

0
Posted at

リストの表示周りを行ったのででーたを追加してみます。

  • Flutter + Firebase
  • コレクション名: items
  • パッケージ: cloud_firestore
# pubspec.yaml
dependencies:
  firebase_core: ^4.6.0
  cloud_firestore: ^6.2.0
  firebase_auth: ^6.4.0

バージョンは各自適切なものを使用してください。

main.dart
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

追加処理の実装

商品名とカテゴリを入力し、add() で Firestore に保存します。ID は Firestore が自動生成します。

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';

Future<void> addItem() async {
  final user = FirebaseAuth.instance.currentUser;
  final displayName = user?.displayName;
  final firestore = FirebaseFirestore.instance;

 // 保存したいデータになります。
  final docRef = await firestore.collection('items').add({
    'name': controller.text.trim(),
    'category': selectedCategory.name, // "food" or "daily"
    'isChecked': false,
    'createdBy': displayName,
    'createdAt': FieldValue.serverTimestamp(),
    'lastBoughtAt': FieldValue.serverTimestamp(),
  });

  // docRef.id で作成されたドキュメントIDを取得できる
}

UI から呼び出す例

入力 → 追加ボタン押下 → Firestore に保存という流れです。

FilledButton.icon(
  onPressed: () {
    if (controller.text.trim().isEmpty) {
      setState(() => errorText = '入力してください');
      return;
    }
    addItem();
  },
  icon: const Icon(Icons.add),
  label: const Text('追加'),
),

add()を使うとドキュメントIDが自動生成される
FieldValue.serverTimestamp() でサーバー側の時刻を保存できる(端末時刻のズレを防げる)
trim() で前後の空白を除去してから保存する
Firestoreへの追加はcollection('items').add({...})の1行が核心です

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?