Don't think! Just do it!

종합 IT 기술 정체성 카오스 블로그! 이... 이곳은 어디지?

Flutter/Flutter Project

[소셜차트] 앱 제작기 #14. 프로필 수정 화면

방피터 2022. 12. 7. 12:35

사진이나 소개 같은 프로필 정보를 수정하는 화면을 만들었어. 별건 아닌데 ㅎ 은근 짜증 ㅎ

프로필 수정화면

text 업로드하는 건 뭐 크게 난이도 있는 건 아니니까 스킵하고 사진 업로드하는 것만 전체적으로 설명하자면

  1. image picker로 갤러리나 카메라로 사진 선택 후 로컬 변수에 저장.
  2. 로컬 변수에 저장된 이미지를 image cropper로 보내서 유저가 size 변경.
  3. 최종 파일을 firebase storage로 보내고 다운로드 url 확보
  4. firestore userDB에 업데이트

이런 순서가 되겠지? 여기에 사용한 package는 image_picker와 image_cropper야 👇👇👇

https://pub.dev/packages/image_picker

 

image_picker | Flutter Package

Flutter plugin for selecting images from the Android and iOS image library, and taking new pictures with the camera.

pub.dev

https://pub.dev/packages/image_cropper

 

image_cropper | Flutter Package

A Flutter plugin for Android, iOS and Web supports cropping images

pub.dev

일단 지금은 그냥 쓰는데 나중에는 image picker를 따로 구현하는게 좋을 것 같아. 다른 앱들의 image picker는 갤러리 첫번째 사진이 카메라로 전환할 수 있는 버튼으로 채워져 있어. 그래서 유치하게 갤러리에서 선택할지 사진을 촬영할지 선택하는 dialog 박스를 보여줄 필요가 없지.... 뭐 그러고 싶은데.. ㅠㅠ 지금은 시간이 너무 부족하므로 다음 기회에 해보자구..

twitter image picker
아.. 이 dialog 박스를 없애고 싶다... ㅠㅠ

image를 선택하는 코드부터 보면 👇 와 같고(설명은 대강 주석 달아놨으니 참고하시고)

  Future setUserImage(ImageSource imageSource) async {
    try {
      //image picker를 통해 image 선택
      var tempImage = await imagePicker.pickImage(source: imageSource);
      if (tempImage != null) {
        ImageCropper().cropImage( //image cropper 열고 
          cropStyle: CropStyle.circle,
          sourcePath: tempImage.path, //image path로 image 전달
          aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1),//crop 비율 1:1
          uiSettings: [
            AndroidUiSettings(//android setting
                toolbarTitle: 'Cropper',
                toolbarColor: Colors.deepOrange,
                toolbarWidgetColor: Colors.white,
                initAspectRatio: CropAspectRatioPreset.original,
                lockAspectRatio: true,
                ),
            IOSUiSettings(//ios setting
              title: 'Cropper',
              aspectRatioLockEnabled: true,//비율 고정
              resetAspectRatioEnabled: false,
            ),
          ],
        ).then((croppedImage) {//image 자르기가 완료됬으면
          if (croppedImage != null) {
            //잘린 이미지를 저장
            _userNewImage.value = File(croppedImage.path);
          }
          Get.back();
        });
      }
    } catch (e) {
      print(e);
      Get.back();
    }
  }

이제 유저가 저장하기 버튼을 누르면 👇 아래를 실행시켜 이미지를 firestore에 저장하고 이미지 link를 유저 DB에 저장하면 끝이야.

...
Reference storageRef =
  firestorage.ref("/userImage/${firebaseAuth.currentUser!.uid}");
...
if (userNewImage != null) {
  //userImage/[userId]/profileImage path 설정
  var userImageRef = storageRef.child("profileImage");
  await userImageRef.putFile(userNewImage!);//저장
  userNewImageUrl = await userImageRef.getDownloadURL();//download url 가져오기
  userUpdateData["profileImageUrl"] = userNewImageUrl;
}
...
...
await userDataColRef()//userData update
  .doc(firebaseAuth.currentUser!.uid)
  .update(userUpdateData)
  .then(
    (value) {},
    onError: (e) => print(e),
  );
...

이 과정이 잘 완료되면 firebase storage에는 userImage/유저id/profileImage라는 이름으로 파일이 잘 생성되겠지 👇

Firebase Storage user profile image 생성.

아직 핵심이 되는 기능은 하나도 개발을 못하고 있네 ㅠㅠ 갈길이 멀다! 얼른!!!!! 가즈아!!!!!!

반응형