๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์›น๊ณต๋ทฐ/flutter

flutter ํ”Œ๋Ÿฌํ„ฐ firestore์—์„œ ๋ฐ์ดํ„ฐ ์ฝ์–ด์˜ค๊ธฐ

by ์ด๋…ธํ‚ค_ 2023. 6. 28.

1. ๋ชจ๋ธ ์ƒ์„ฑ

QuerySnapshot ๋ฐ์ดํ„ฐ๋ฅผ ์ฝ์–ด์˜ฌ๋•Œ, ์›ํ•˜๋Š” ์˜ค๋ธŒ์ ํŠธ ํ˜•ํƒœ๋กœ ๊ฐ€์ ธ์˜ค๊ฒŒ ํ•จ. (Category ์˜ค๋ธŒ์ ํŠธ ํƒ€์ž…์œผ๋กœ ํŒŒ์ด์–ด์Šคํ† ์–ด์— data writing๋œ ์ƒํƒœ)

class HomeModel {
  final Stream<QuerySnapshot<Category>> categoriesStream = FirebaseFirestore.instance
      .collection(Constants().categories)
      .withConverter<Category>(
        fromFirestore: (snapshot, _) => Category.fromJson(snapshot.data()!),
        toFirestore: (category, _) => category.toJson(),
      )
      .snapshots();
}

 

2. ์ถœ๋ ฅ์„ ์›ํ•˜๋Š” ์œ„์ ฏ์—์„œ StreamBuilder๋กœ ๊ฐ์‹ธ๊ธฐ

์›๋ž˜๋Š” Wrap ์œ„์ ฏ์ด์—ˆ์Œ. 

 

3. snapshot ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•ด ์˜ˆ์™ธ์ฒ˜๋ฆฌ ์ถ”๊ฐ€ํ•ด์ฃผ๊ณ , ์•„๋ž˜ text ์ถœ๋ ฅํ•˜๋Š” ๋ถ€๋ถ„์—์„œ ์‹ค์ œ ๋ฐ์ดํ„ฐ ๋ฝ‘์•„๋‚ด์„œ ์ถœ๋ ฅ

StreamBuilder<QuerySnapshot<Category>>(
              stream: model.categoriesStream,
              builder: (context, snapshot) {

                if (snapshot.hasError) {
                  return const Text('Something went wrong');
                }

                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Center(child: CircularProgressIndicator());
                }

                List<Category> categories = snapshot.data!.docs.map((e) => e.data()).toList();

                return Wrap(
                  direction: Axis.horizontal, //๋‚˜์—ด ๋ฐฉํ–ฅ
                  alignment: WrapAlignment.start, //์ •๋ ฌ๋ฐฉ์‹
                  spacing: 5, //์ขŒ์šฐ๊ฐ„๊ฒฉ
                  runSpacing: 5, //์ƒํ•˜๊ฐ„๊ฒฉ
                  children: <Container>[
                    for(var i = 0; i<categories.length; ++i)
                      ...[
                        Container(
                          padding: const EdgeInsets.all(6),
                          decoration: BoxDecoration(
                            color: const Color(0xffdddddd),
                            borderRadius: BorderRadius.circular(6),
                          ),
                          child: Text('#${categories[i].name}'),
                        ),
                      ],
                  ],
                );
              }
            ),

๋Œ“๊ธ€