今回はFirebaseFirestoreを使用してCloud Firestoreで保存されているドキュメントを更新する方法を紹介します。
目次
下準備
- Firebaseプロジェクトを作成
- Cloud Firestoreでコレクションを作成(コレクション名は「messages」)
- コレクションにドキュメントを追加
- pubspec.yamlにFirebaseプラグインを追加
- DartファイルにFirebaseパッケージをインポート
- main()でinitializeApp()を呼び出す
これらが済んでいる程で解説を進めていきます。
Cloud Firestoreのドキュメントを更新する
記事下の完成コードで示している「ステップ○」を参考にして読んでみて下さい。
ステップ1:FirebaseFirestoreをインスタンス化する
//ステップ1
final _firestore = FirebaseFirestore.instance;
FirebaseFirestoreをインスタンス化します。
ステップ2:ドキュメントを指定してデータを更新
//ステップ2
_firestore
.collection('messages')
.doc('document_demo')
.update(
{
'text': message,
},
)
.then((value) => print('ドキュメントを更新しました!'))
.catchError((e) => print(e));
doc()で更新したいドキュメントを指定し、update()で変更したいドキュメントのフィールドを指定します。
ドキュメントが存在しない場合はエラーがスローされ、指定したフィールドが存在しない場合は新しいフィールドが追加されます。
今回の場合は「messages(コレクション)」>「document_demo(ドキュメント)」>「text(フィールド)」の値に「message(変数)」で更新または追加しています。
完成コード

import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
//ステップ1
final _firestore = FirebaseFirestore.instance;
String? message; //TextFieldのvalueを入れる
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Chat'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
onChanged: (value) {
setState(() {
message = value;
});
},
),
),
),
TextButton(
child: Text('Send'),
onPressed: () {
//ステップ2
_firestore
.collection('messages')
.doc('document_demo')
.update(
{
'text': message,
},
)
.then((value) => print('ドキュメントを更新しました!'))
.catchError((e) => print(e));
},
),
],
)
],
),
),
);
}
}
以上です。