name27 / flutter

0 stars 0 forks source link

firebase #110

Open name27 opened 1 year ago

name27 commented 1 year ago

multidex + image

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:day_34_test_firebase/model/post.dart';
import 'package:flutter/material.dart';

class AssignmentPage extends StatefulWidget {
  const AssignmentPage({super.key});

  @override
  State<AssignmentPage> createState() => _AssignmentPageState();
}

class _AssignmentPageState extends State<AssignmentPage> {
  var ref = FirebaseFirestore.instance.collection('post').withConverter( //post 이름의 컬렉션을 가져와 데이터 형변환한다
    fromFirestore: (snapshot, _) => Post.fromMap(snapshot.data()!), //firestore에서 데이터를 가져와 Post.fromMap 해준다
    toFirestore: (data, _) => data.toMap(), //firestore로 데이터를 Map형으로 보내줌
  );

  Future<List<QueryDocumentSnapshot<Post>>> readData() async {
    var items = await ref.get();
    return items.docs;
  }

  // likesUp(String id) => ref.doc(id).update(...);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: FutureBuilder<List<QueryDocumentSnapshot<Post>>>(
          future: readData(),
          builder: (context, snapshot) {
            if (snapshot.hasData &&
                snapshot.connectionState == ConnectionState.done) {
              return ListView.builder(
                itemCount: snapshot.data!.length,
                itemBuilder: (context, index) => ListTile(
                  title: Text(snapshot.data![index].data().title),
                  subtitle: Text(snapshot.data![index].data().content),
                  trailing: IconButton(
                    icon: const Icon(Icons.favorite),
                    onPressed: (){},
                    // onPressed: () => likesUp(snapshot.data![index].id),
                  ),
                ),
              );
            }
            return const SizedBox();
          },
        ),
      ),
    );
  }
}
....
likesUp(String id) => ref.doc(id).update({
    'likes' : FieldValue.increment(1)
   });
....
....
trailing: IconButton(
                    icon: const Icon(Icons.favorite),
                    onPressed: () => likesUp(snapshot.data![index].id),
                  ),
....