사진을 불러와 위젯에 넣기

Clean Code Big Poo·2023년 3월 19일
0

Flutter

목록 보기
22/38
post-thumbnail

Overview

image_picker라는 flutter 패키지를 이용해 사진을 가져오고, 화면에 보여주자.

IOS-info.plist

ios>Runner>info.plist에 추가하기

<key>NSPhotoLibraryUsageDescription</key>
<string>권한 요청 메세지를 여기에 작성!</string>
<key>NSCameraUsageDescription</key>
<string>권한 요청 메세지를 여기에 작성!</string>
<key>NSMicrophoneUsageDescription</key>
<string>권한 요청 메세지를 여기에 작성!</string>

Android-AndroidManifest.xml

No configuration required! 안드로이드 버전에 따라 다른 듯 하니 이곳을 참고하자.

사용법

import 'package:image_picker/image_picker.dart';

    ...
    final ImagePicker _picker = ImagePicker();
    // 갤러리로 사진 가져오기
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    // 카메라로 사진 가져오기
    final XFile? photo = await _picker.pickImage(source: ImageSource.camera);
    // 갤러리에서 동영상 가져오기
    final XFile? image = await _picker.pickVideo(source: ImageSource.gallery);
    // 카메라로 동영상 가져오기
    final XFile? video = await _picker.pickVideo(source: ImageSource.camera);
    // 다중 이미지 가져오기
    final List<XFile>? images = await _picker.pickMultiImage();
    ...

위젯 업데이트 하기

  Future picImage() async {
    try {
      var img = await ImagePicker().pickImage(source: ImageSource.gallery);//원하는 방식으로 변경

      if (img == null) return;

      setState(() {
        this.image = File(img.path);
      });
    } on PlatformException catch (e) {
      print('[ERROR] pickImage error : $e');
    }
  }

위젯을 업데이트 해야 하므로 StatefulWidget으로 설정하고 File? image 를 전역 변수로 하여 핸들링 하면 된다. 그리고 onEvent() 에서 picImage() 호출하면 끝!

위젯 업데이트 하기 - GetX

//GetController 내부
  Rx<File?> _thumnailImage = Rx<File?>(null);
  Rx<File?> get thumnailImage => _thumnailImage;

  /// 썸네일 에러문
  Rx<String> thumnailError = ''.obs;

  Future picImage() async {
    try {
      var img = await ImagePicker().pickImage(source: ImageSource.gallery);

      if (img == null) return;

      _thumnailImage.value = File(img.path);
    } on PlatformException catch (e) {
      print('[ERROR] pickImage error : $e');
    }
  }

GetController 에서 핸들링을 하면 어떨까? Rx로 값 변경을 Notify하므로 따로 update()를 호출할 필요는 없다.

...
GestureDetector(
	child: controller.thumnailImage.value == null
		? Container(
			decoration: BoxDecoration(
				color: Color(0xfff3f3f3),
				borderRadius: BorderRadius.circular(8.r),
			),
			width: double.infinity,
			height: 200,
			child: Column(
				mainAxisAlignment: MainAxisAlignment.center,
				children: [
					Padding(
						padding: const EdgeInsets.all(10.0),
						child: Image.asset('assets/images/photo.png'),
						),
					Text(
						'화면을 눌러 썸네일을 추가해주세요.',
						style: TextStylePath.small12w400.copyWith(
                        	color: Color(0xff98908e),
                            ),
						),
					],
				),
			)
		: ClipRRect(
			borderRadius: BorderRadius.circular(8.r),
			child: Image.file(
				controller.thumnailImage.value!,
				width: double.infinity,
				height: 200,
				fit: BoxFit.cover,
			),
		),
		onTap: () {
			controller.picImage();
		},
	),
...

controller의 thumnailImage 이 null이면 '섬네일 추가' 문구, 있으면 이미지를 화면에 보여주었다.

컨테이너로 감싸도 Image.file에 영향이 안 간다. 모서리 둥글게 안되더라고..
ClipRRect은 Image.file을 둥글게 만들어 준다!

참고

이미지 가져오기

0개의 댓글