今回はFirebaseFirestoreを使用してFlutterアプリからドキュメント(データ)を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')
.add({
'email': _auth.currentUser!.email,
'text': message,
})
.then((value) => print('ドキュメントを追加しました!'))
.catchError((e) => print(e));
collection()でCloud Firestoreのコレクションを指定し、add()でドキュメントをコレクションに追加します。add()の場合ドキュメントパスはランダムで生成されます。
then()でエラーがスローされた場合に「ドキュメントを追加しました!」を出力し、catchError()でエラーを出力しています。
ステップ2:ドキュメントパスを指定してデータを追加
//ステップ2
_firestore
.collection('messages')
.doc('document_demo')
.set(
{
'text': message,
},
)
.then((value) => print('ドキュメントを追加しました!'))
.catchError((e) => print(e));
ドキュメントパスを指定したい場合はdoc()でドキュメントパスを決め、set()でドキュメントをコレクションに追加します。
doc()で指定したドキュメントがデータベースに存在している場合、新しくset()で指定したドキュメントデータと入れ替わります。
完成コード

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')
.set(
{
'text': message,
},
)
.then((value) => print('ドキュメントを追加しました!'))
.catchError((e) => print(e));
},
),
],
)
],
),
),
);
}
}
以上です。