본문 바로가기

카테고리 없음

[flutter 2.0] firestore 연동 및 기본적인 CRUD

별도의 창에서 데이터 값을 입력하는 것이 아닌 hardcoding된 dart파일에서 넘어가는 것이다.

 

데이터 베이스의 예시는 다음과 같다. 

 

main 함수에는 async와 함께 다음 코드를 넣고 MyApp을 구동시켜야 한다.

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

children Widget에 다음과 같이 구동하였다.

 

1. Create

FlatButton(
              color: Color(0xff67666b),
              child: Text("member 추가", style: TextStyle(color: Colors.white)),
              onPressed: () {
                String n_member = "Heo";
                firestore
                    .collection('member')
                    .doc(n_member)
                    .set({'age': 21, 'attendance?': false, 'part': 'Design'});
              },
            ),

 

2. Read - terminal 창에 띄운다

 FlatButton(
              color: Color(0xffaf0022),
              child:
                  Text("member 한명 가져오기", style: TextStyle(color: Colors.white)),
              onPressed: () {
                String title = "";
                firestore
                    .collection("member")
                    .doc("Ryu")
                    .get()
                    .then((DocumentSnapshot ds) {
                  title = ds["part"];
                  print(title);
                  print(ds["age"]);
                });
              },
            ),

 

3. Update

FlatButton(
              color: Color(0xffd1cfd2),
              child: Text("member update",
                  style: TextStyle(color: Colors.black87)),
              onPressed: () {
                firestore
                    .collection("member")
                    .doc("Ryu")
                    .update({"part": "Desgramming"});
              },
            ),

 

4. Delete

FlatButton(
              color: Color(0xff212345),
              child: Text("member 삭제", style: TextStyle(color: Colors.white)),
              onPressed: () {
                //특정 member 삭제
                firestore.collection("member").doc("Heo").delete();
                //특정 member에서 하나의 field만 삭제
                firestore
                    .collection('member')
                    .doc('Ryu')
                    .update({'part': FieldValue.delete()});
              },
            ),