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
  • コレクション名: items
  • チェック状態(isChecked)のトグル更新

部分更新(update)

指定フィールドだけ更新する方法。他のフィールドはそのまま残ります。

import 'package:cloud_firestore/cloud_firestore.dart';
Future<void> toggleItemCheck(ShoppingItem item) async {
  await FirebaseFirestore.instance
      .collection('items')
      .doc(item.id)
      .update({
    'isChecked': !item.isChecked,
    'lastBoughtAt': FieldValue.serverTimestamp(),
  });
}

UI から呼び出す:

void _toggleCheck(ShoppingItem item) {
  toggleItemCheck(item);
}
// ListTile の onTap などから
ListTile(
  onTap: () => _toggleCheck(item),
  leading: Checkbox(value: item.isChecked, onChanged: null),
  title: Text(item.name),
)

更新後の UI 反映
snapshots() で監視しているため、更新後は 自動的に UI が反映 されます。

stream: FirebaseFirestore.instance
    .collection('items')
    .snapshots(),

ポイント
FieldValue.serverTimestamp()で更新日時をサーバー時刻で記録
update()は部分更新の定番。存在しないドキュメントには使えない

まとめ
フィールド更新 → update({...})
StreamBuilderと組み合わせれば、更新結果が即座にUIに反映される

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?