프로그래밍/플러터

Google API & Photo

스루나루 2024. 3. 20. 21:51
728x90
728x90

 

출첵

 

 1) 구글 지도 

  - 구글 API 가지고 와서 화면에 지도와 위치 등 랜더링 해주는 API

 

  Expanded( // 2/3만큼 공간 차지
    flex: 2,
    child: GoogleMap(
      initialCameraPosition: CameraPosition(
        target: companyLatLng,
        zoom: 16,
      ),
      myLocationEnabled: true,
      markers: Set.from([marker]),
      circles: Set.from([circle]),
    ),
  ),

 

 - 위치 정보 받아서 원하는 위치와 거리 파악 후 bool타입으로 판단 후 출첵 로직 실행 

ElevatedButton(  // [출근하기] 버튼
                          onPressed: () async {
                            final curPosition = await Geolocator.getCurrentPosition();  // 현재 위치

                            final distance = Geolocator.distanceBetween(
                              curPosition.latitude,  // 현재위치 위도
                              curPosition.longitude,  // 현재위치 경도
                              companyLatLng.latitude,  // 회사위치 위도
                              companyLatLng.longitude,  // 회사위치 경도
                            );
                            bool canCheck =
                                distance < 100;

 

 - 위치 권한 체크 로직 

Future<String> checkPermission() async {
    final isLocationEnabled = await Geolocator.isLocationServiceEnabled();   // 위치 서비스 활성화여부 확인

    if (!isLocationEnabled) {  // 위치 서비스 활성화 안 됨
      return '위치 서비스를 활성화해주세요.';
    }

    LocationPermission checkedPermission = await Geolocator.checkPermission();  // 위치 권한 확인

    if (checkedPermission == LocationPermission.denied) {  // 위치 권한 거절됨

      // 위치 권한 요청하기
      checkedPermission = await Geolocator.requestPermission();

      if (checkedPermission == LocationPermission.denied) {
        return '위치 권한을 허가해주세요.';
      }
    }

    // 위치 권한 거절됨 (앱에서 재요청 불가)
    if (checkedPermission == LocationPermission.deniedForever) {
      return '앱의 위치 권한을 설정에서 허가해주세요.';
    }

    // 위 모든 조건이 통과되면 위치 권한 허가완료
    return '위치 권한이 허가 되었습니다.';
  }

 

 

 

 

 

포토 스티커 

 

  화면에 붙이는 스티커는 Set으로 관리하고 각 스티커를 랜더링할 수 있도록 selectedId를 사용 해당 아이디를 통해서 어떤 스티커가 지금 랜더링 되어 있는지 파악할 수 있으며 추가 및 변경 삭제가 가능해짐 

Widget renderBody() {
    if (image != null) {

      return RepaintBoundary(

        // ➊ 위젯을 이미지로 저장하기 위해 사용
        key: imgKey,
        child: Positioned.fill(
          child: InteractiveViewer(
            child: Stack(
              fit: StackFit.expand,
              children: [
                Image.file(
                  File(image!.path),
                  fit: BoxFit.cover,
                ),
                ...stickers.map(
                      (sticker) => Center(
                    child: EmoticonSticker(
                      key: ObjectKey(sticker.id),
                      onTransform: () {
                        onTransform(sticker.id);
                      },
                      imgPath: sticker.imgPath,
                      isSelected: selectedId == sticker.id,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      );

 

 

 스티커 관련 로직으로 해당 랜더링 한 스티커를 변경 추가 및 삭제 가능 

 void onSaveImage() async {
    RenderRepaintBoundary boundary = imgKey.currentContext!
        .findRenderObject() as RenderRepaintBoundary;
    ui.Image image = await boundary.toImage(); // ➊ 바운더리를 이미지로 변경
    ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png); // ➋ byte data 형태로 형태 변경
    Uint8List pngBytes = byteData!.buffer.asUint8List(); // ➌ Unit8List 형태로 형태 변경

    await ImageGallerySaver.saveImage(pngBytes, quality: 100);

    ScaffoldMessenger.of(context).showSnackBar(  // ➋ 저장 후 Snackbar 보여주기
      SnackBar(
        content: Text('저장되었습니다!'),
      ),
    );
  }

  void onDeleteItem() async {
    setState(() {
      stickers = stickers.where((sticker) => sticker.id != selectedId).toSet();  // ➊ 현재 선택돼 있는 스티커 삭제 후 Set로 변환
    });
  }

  void onTransform(String id){  // 스티커가 변형될 때마다 변형 중인 스티커를 현재 선택한 스티커로 지정
    setState(() {
      selectedId = id;
    });
  }

 

 

이 글은 골든래빗 《Must Have 코드팩토리의 플러터 프로그래밍 2판》의 스터디 내용 입니다.

728x90
728x90