LoginSignup
2

More than 1 year has passed since last update.

CloudFirestoreのarrayを使ってみる

Last updated at Posted at 2021-02-16

CloudFirestoreのarrayを使用している記事があまり見つからなかったので、備忘録的に残しておく。

記載すること
CloudFirestoreのフィールドのarray型の使い方(今回は追加)

記載しないこと
Firebaseのプロジェクトの作り方

下の写真のようにfavorite_dogという配列を作り、その中に、好きな犬の名前を入れていくコードを作る。

スクリーンショット 2021-02-16 18.46.15.png

main.dart

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';


Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Firebaseテスト',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyFirestorePage(),
    );
  }
}

class MyFirestorePage extends StatefulWidget {
  @override
  _MyFirestorePageState createState() => _MyFirestorePageState();
}

class _MyFirestorePageState extends State<MyFirestorePage> {
//配列に追加する関数を作る。
  appendArray() {
    DocumentReference ref = FirebaseFirestore.instance
        .collection('male')
        .doc('h1V6VPae89iMno78IiSP');
    ref.update(
      {
        "favorite_dog": FieldValue.arrayUnion(['犬の名前']),
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              child: Text('登録'),
              onPressed: () {
                appendArray();
              },
            ),
          ],
        ),
      ),
      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
ref.update(
      {
        "favorite_dog": FieldValue.arrayUnion(['犬の名前']),
      },
    )

updateはmap形式で書きます。

試しに犬の名前を「hachi」とし、flutter runし、登録ボタンを押すと、
スクリーンショット 2021-02-16 18.58.19.png

無事に配列の[1]にhachiが格納されました。
なお、配列にすでにある要素については重複して追加はされません。

※参考
https://firebase.google.com/docs/firestore/manage-data/add-data#java_10

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
2