fetchAndroid function

Future<AppVersionData> fetchAndroid({
  1. PackageInfo? packageInfo,
  2. String? playStoreId,
})

Implementation

Future<AppVersionData> fetchAndroid(
    {PackageInfo? packageInfo, String? playStoreId}) async {
  playStoreId = playStoreId ?? packageInfo?.packageName;

  final parameters = {
    "id": playStoreId,
  };
  var uri = Uri.https(playStoreAuthority, playStoreUndecodedPath, parameters);
  final response =
      await http.get(uri, headers: headers).catchError((e) => throw e);

  if (response.statusCode == 200) {
    final String htmlString = response.body;
    RegExp regex;
    Iterable<RegExpMatch> matches;
    // Use regex to find all occurrences of version in the format "]]],"<version-number>"
    if (packageInfo!.version.split('.').length == 3) {
      regex = RegExp(r'"\]\]\],null,null,null,\[\[\["(.*?)"\]\]\]');
      matches = regex.allMatches(htmlString);
    } else {
      regex = RegExp(r'"\]\]\],"(.*?)"');
      matches = regex.allMatches(htmlString);
    }

    // Extract the last version found
    if (matches.isNotEmpty) {
      final lastMatch = matches.last;
      String? lastVersion = lastMatch.group(1);
      lastVersion = lastVersion!.split('"').first;
      if (kDebugMode) {
        print(
          'Versão local ${packageInfo.version} Última versão encontrada: $lastVersion',
        );
      }
      return AppVersionData(
        // canUpdate: packageInfo.version < lastVersion ? true : false,
        storeVersion: lastVersion,
        storeUrl: uri.toString(),
        localVersion: packageInfo.version,
        targetPlatform: TargetPlatform.android,
      );
    } else {
      throw "Application not found in Play Store, verify your app id.";
    }
  } else {
    throw "Application not found in Play Store, verify your app id.";
  }
}