[Flutter] Firestoreからデータを取得する コード全文

記事

Firestoreからデータを取得する

コード

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static final FirebaseFirestore db = FirebaseFirestore.instance;
  static final CollectionReference users = db.collection('users');

  Future<void> action() async {
    users.add({'name': 'dog', 'age': 3});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: StreamBuilder<QuerySnapshot>(
        stream: users.snapshots(),
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.hasError) {
            return Text("エラーが発生しました: ${snapshot.error}");
          }
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Text("読み込み中...");
          }
          // ドキュメントからデータのリストを作成
          List<QueryDocumentSnapshot> usersList = snapshot.data!.docs;

          return ListView.builder(
            itemCount: usersList.length,
            itemBuilder: (context, index) {
              // nameフィールドを取得
              String username = usersList[index]['name'];
              return ListTile(
                title: Text(username),
              );
            },
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: action,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}