name27 / flutter

0 stars 0 forks source link

프로필 사진 업데이트 #115

Open name27 opened 1 year ago

name27 commented 1 year ago

image image

image

main.dart

import 'package:day_34_test_firebase/controller/auth_controller.dart';
import 'package:day_34_test_firebase/controller/login_controller.dart';
import 'package:day_34_test_firebase/controller/main_controller.dart';
import 'package:day_34_test_firebase/controller/sign_up_controller.dart';
import 'package:day_34_test_firebase/firebase_options.dart';
import 'package:day_34_test_firebase/view/pages/login_page.dart';
import 'package:day_34_test_firebase/view/pages/main_page.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

enum Pagestate { login, main }

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

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Pagestate pagestate = Pagestate.login;
  _buildPage(state) {
    switch (state) {
      case Pagestate.login:
        return const LoginPage();
      case Pagestate.main:
        return const MainPage();
    }
  }

  _onAuthStateChanged(User? user) => setState(() {
        Get.find<AuthController>().user(user);
        pagestate = user != null ? Pagestate.main : Pagestate.login;

      });

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    FirebaseAuth.instance.authStateChanges().listen(_onAuthStateChanged);
    FirebaseAuth.instance.userChanges().listen((event) {
      Get.find<AuthController>().user(event);
      return setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialBinding: BindingsBuilder(() {
        Get.put(AuthController());
        Get.lazyPut(() => LoginController());
        Get.lazyPut(() => MainController(), fenix: true);
        Get.lazyPut(() => SignUpController(), fenix: true);
      }),
      home: _buildPage(pagestate),
    );
  }
}

main_page.dart

import 'package:day_34_test_firebase/controller/auth_controller.dart';
import 'package:day_34_test_firebase/controller/main_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class MainPage extends GetView<MainController> {
  const MainPage({super.key});

  @override
  Widget build(BuildContext context) {
    var auth = Get.find<AuthController>().user;
    return Scaffold(
        body: Center(
      child: SingleChildScrollView(
          child: Obx(
        () => Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const Text('메인페이지'),
            GestureDetector(
              onTap: controller.handleOnTap,
              child: CircleAvatar(
                  radius: 100,
                  backgroundImage: auth.value!.photoURL != null
                      ? NetworkImage(auth.value!.photoURL!)
                      : null),
            ),
            Card(
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(controller.user!.email!),
                    ElevatedButton(
                        onPressed: Get.find<AuthController>().signOut,
                        child: const Text('로그아웃'))
                  ],
                ),
              ),
            ),
          ],
        ),
      )),
    ));
  }
}

auth_controller.dart

import 'package:day_34_test_firebase/view/pages/login_page.dart';
import 'package:day_34_test_firebase/view/pages/main_page.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:get/get.dart';

class AuthController extends GetxController {
  final Rxn<User> user = Rxn<User>();

  sendEmail() => FirebaseAuth.instance.currentUser?.sendEmailVerification();

  signOut() => FirebaseAuth.instance.signOut();

  signUp(String email, String pw) => FirebaseAuth.instance
      .createUserWithEmailAndPassword(email: email, password: pw);

  login(String email, String pw) async {
    FirebaseAuth.instance
        .signInWithEmailAndPassword(email: email, password: pw);
  }

  // @override
  // void onInit() {
  //   // TODO: implement onInit
  //   super.onInit();
  //   FirebaseAuth.instance.authStateChanges().listen((value) {
  //     user(value);

  //     if (value != null) {
  //       print(value.email);
  //       Get.to(MainPage());
  //     } else {
  //       print('로그인 회원가입 필요');
  //       Get.to(LoginPage());
  //     }
  //   });
  // }
}

main_controller.dart

import 'dart:io';

import 'package:day_34_test_firebase/controller/auth_controller.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

class MainController extends GetxController {
  User? get user => Get.find<AuthController>().user.value;

  handleOnTap() async {
    var picker = ImagePicker();
    var res = await picker.pickImage(source: ImageSource.gallery);
    if (res != null) {
      //storage 올리기
      var ref = FirebaseStorage.instance.ref('profile/${user!.uid}');
      ref.putFile(File(res.path)).then((p0) => null);
      var downloadUrl = await ref.getDownloadURL();
      //downloadUrl 받기
      await user!.updatePhotoURL(downloadUrl);
    }
  }
}