개발하는 두더지

Flutter - Firestore 라이브러리 사용하기 (1) 본문

Flutter

Flutter - Firestore 라이브러리 사용하기 (1)

덜지 2019. 4. 26. 14:18

flutter에서 Firebase, FireStore를 사용하기 위해서는 Android 에서 Gradle에 dependency를 추가하듯이 flutter에서도 추가해줘야 합니다.

pubspec.yaml 파일에서 cloud_firestore 를 추가해줍니다. 최신 버전은 Flutter Pacakages를 검색할 수 있는 pub 에서 확인할 수 있습니다.

IDE 에서 flutter packages get 을 실행시켜 dependency를 추가시켜줍니다.
Visual Studio Code에서는 View -> Command Palette.. 에서 flutter packages get을 검색하여 run 해줍니다.

dependencies:
  flutter:
    sdk: flutter

  cloud_firestore: ^0.8.2     # new

dart 파일에서 사용할 때는 라이브러리를 import 하여 사용합니다.
아래 코드는 mock 형태의 앱입니다. 각각의 행을 클릭하면 이름과 투표값이 콘솔로 출력되는 기능만 가지고 있습니다.
이제 하나하나씩 Cloud Firestore 라이브러리를 연결해보도록 하겠습니다.

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

// 메인 진입점
void main() => runApp(MyApp());

// 더미 데이터를 만들어준다.
final dummySnapshot = [
 {"name": "Filip", "votes": 15},
 {"name": "Abraham", "votes": 14},
 {"name": "Richard", "votes": 11},
 {"name": "Ike", "votes": 10},
 {"name": "Justin", "votes": 1},
];

// 껍데기는 상태가 변하지 않는 위젯
class MyApp extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
   return MaterialApp(
     title: 'Baby Names',
     home: MyHomePage(),
   );
 }
}

class MyHomePage extends StatefulWidget {
 @override
 _MyHomePageState createState() {
   return _MyHomePageState();
 }
}

class _MyHomePageState extends State<MyHomePage> {
 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(title: Text('Baby Name Votes')),
     body: _buildBody(context),
   );
 }

 Widget _buildBody(BuildContext context) {
   // TODO: get actual snapshot from Cloud Firestore
   return _buildList(context, dummySnapshot);
 }

 Widget _buildList(BuildContext context, List<Map> snapshot) {
   return ListView(
     padding: const EdgeInsets.only(top: 20.0),
     children: snapshot.map((data) => _buildListItem(context, data)).toList(),
   );
 }

 Widget _buildListItem(BuildContext context, Map data) {
   final record = Record.fromMap(data);

   return Padding(
     key: ValueKey(record.name),
     padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
     child: Container(
       decoration: BoxDecoration(
         border: Border.all(color: Colors.grey),
         borderRadius: BorderRadius.circular(5.0),
       ),
       child: ListTile(
         title: Text(record.name),
         trailing: Text(record.votes.toString()),
         onTap: () => print(record),
       ),
     ),
   );
 }
}

class Record {
 final String name;
 final int votes;
 final DocumentReference reference;

 Record.fromMap(Map<String, dynamic> map, {this.reference})
     : assert(map['name'] != null),
       assert(map['votes'] != null),
       name = map['name'],
       votes = map['votes'];

 Record.fromSnapshot(DocumentSnapshot snapshot)
     : this.fromMap(snapshot.data, reference: snapshot.reference);

 @override
 String toString() => "Record<$name:$votes>";
}
Comments