Firebaseを使ってみる(Firestore編)

2023年5月27日

開発環境
OS:Windows 11
SDK:VS Code + flutter 3.7.5

概要

アプリを作るうえで欠かすことのできない存在であるデータベース。

Firebaseなら簡単で気軽に利用することができます。

今回はFirebaseでデータの参照、更新を行います。

Firestoreを更新する

Firebaseのセットアップが済んだら、flutterでFirestoreを更新してみます。

入力ボックスとボタンを用意し、ボタン押下時に入力ボックスに入力された文字を

Firestoreに登録する処理を必要部分だけ抜粋しました。

import 'package:firebase_database/firebase_database.dart';

 final strComment = TextEditingController();

 //入力ボックス
  TextField(         
    controller: strComment,             
    decoration: InputDecoration(
      hintStyle: const TextStyle(fontSize: 10),
      hintText: 'コメントを入力する'
    ),
    maxLines: 1,
    style: const TextStyle(fontSize: 10),
  )

  //ボタン
	ElevatedButton(
	  onPressed: () async {
	    await setComment(strComment.text);
	  }, 
	  child: Text('コメント更新')
	))

  //更新処理
  Future<void> setComment(String comment) async {
    DatabaseReference comRef = FirebaseDatabase.instance.ref('comment').child('sample');
    comRef.set(comment);
  }

Firestoreは、No SQLデータベースです。

上記は、ドキュメント「comment」のフィールド「sample」に入力値をセットしています。

Firestoreを参照する

参照処理も更新処理と同様、参照パスを定義し、そのリファレンスをゲットするだけです。


 final strComment = TextEditingController();

  //ボタン
	ElevatedButton(
	  onPressed: () async {
	    strComment.text = await getComment();
      setState((){});
	  }, 
	  child: Text('コメント参照')
	))

  //参照処理
  Future<String> getComment() async {
    var rtnval = "";  
    DatabaseReference dbRef = FirebaseDatabase.instance.ref('comment').child('sample');
    final snapshot = await dbRef.get();
    if (snapshot.exists) {
      rtnval = snapshot.value.toString();
    }
    return rtnval;
  }

今回は以上です。