[Flutter] app_version_update 앱버전 업데이트 알림창 구현하기

겨레·2025년 2월 6일
0

app_version_update 6.0.0


app_version_update 플러터 공식 문서 코드 그대로 작성했을 경우

Future<void> checkForUpdate() async {
  await AppVersionUpdate.checkForUpdates(
    appleId: '123456', // 애플 ID 예시
    playStoreId: 'com.flutter.korea', // 플레이스토어 ID 예시
  ).then((result) async {
    if (result.canUpdate!) {
      await AppVersionUpdate.showAlertUpdate(
        appVersionResult: result,
        context: context,
        backgroundColor: Colors.grey[200],
        title: '새 버전이 있습니다.'
        titleTextStyle: const TextStyle(color: Colors.black, fontWeight: FontWeight.w600, fontSize: 24.0),
        content: '최신 버전으로 업데이트하시겠습니까?', 
        contentTextStyle: const TextStyle(
          color: Colors.black,
          fontWeight: FontWeight.w400,
        ),
         updateButtonText: '업데이트',
          cancelButtonText: '나중에',
      );
    }
  });
}

app_version_update 라이브러리를 이용하면 생각보다 쉽게 한번에 플랫폼이랑 앱 버전을 확인해서 각각 플랫폼에 맞는 스토어로 이동시켜준다.

하지만, 단점으로는 디테일한 커스텀이 어렵다는 점...
앱 디자인에 맞춰 만들어야 할 경우에는 showDialog를 커스텀해 활용하는 게 좋다.


showDialog를 활용한 app_version_update

  • 메인 화면에 들어 왔을 때 바로 떠야 하기 때문에 initState에 코드를 작성해준다.

  void initState() {
    super.initState();
    FlutterNativeSplash.remove();
    WidgetsBinding.instance.addObserver(this);
    init();
    
    // WidgetsBinding.instance.addPostFrameCallback((_) {
    //   if (mounted) {
    //     showUpdateDialog();
    //   }
    // });

    checkForUpdate();

 
  }

  • showUpdateDialog 커스텀
// 앱 버전 업데이트 알림창
  void showUpdateDialog() {
    showDialog(
      useRootNavigator: true, // true => BottomNavigationWidget 비활성화
      barrierDismissible: false,
      context: context,
      builder: (_) {
        return ShowAlertWidget(
          titleText: '업데이트 안내',
          descTextSpan: TextSpan(
            text: '최적의 사용 환경을 위해 최신 버전의\n앱으로 업데이트해주세요.',
            style: SpoqaHansNeoText.body3.copyWith(
              color: AppColor.grey400,
            ),
          ),
          cancelBodyColor: AppColor.transparent,
          cancelFunc: () {},
          cancelText: '',
          cancelTextColor: AppColor.transparent,
          actionBodyColor: AppColor.transparent,
          actionFunc: () async {
            context.pop();
            await openStore();
          },
          actionText: '업데이트하기',
          actionTextColor: AppColor.deepPurple500,
        );
      },
    );
  }

  • 플랫폼을 확인해서 앱스토어, 플레이스토어로 이동
 Future<void> openStore() async {
    // 애플
    const String appStoreUrl =
        'https://apps.apple.com/(예시)';

    // 안드로이드(구글)
    const String playStoreUrl =
        'https://play.google.com/store/apps/(예시)';

    /* 원래는 이런 식으로 이동을 하게 하고, 앱 버전을 비교하는 함수를 구현하려고 했었음 */
    // if (Platform.isIOS) {
    //   if (await canLaunchUrlString(appStoreUrl)) {
    //     launchUrlString(appStoreUrl, mode: LaunchMode.externalApplication);
    //   }
    // } else if (Platform.isAndroid) {
    //   if (await canLaunchUrlString(playStoreUrl)) {
    //     launchUrlString(playStoreUrl, mode: LaunchMode.externalApplication);
    //   }
    // }

    final storeUrl = Platform.isAndroid ? playStoreUrl : appStoreUrl;
    await launchUrlString(storeUrl, mode: LaunchMode.externalApplication);
  }

  • 앱 버전 비교해서 업데이트 필요하면 showUpdateDialog 표시
Future<void> checkForUpdate() async {
    final packageInfo = await PackageInfo.fromPlatform();
    final currentVersion = packageInfo.version;
    // print('================✅ 현재 버전: $currentVersion');
    print('================✅ 패키지 정보: $packageInfo');

    final result = await AppVersionUpdate.checkForUpdates(
      // appleId에 무슨 값이 필요한지 모름
      // 비워두면 라이브러리가 알아서 찾아줌
      // 나중에 찾아보기
      // appleId: '1234567',
      playStoreId: 'com....예시',
    );

    final latestVersion = result.storeVersion ?? currentAppVersion;

    if (currentVersion != latestVersion) {
      showUpdateDialog();
    }
  }

profile
호떡 신문지에서 개발자로 환생

0개의 댓글