generateShortLink method

Future<BitLyLinkData> generateShortLink({
  1. required String longUrl,
  2. String domain = "bit.ly",
  3. String? groupGuid,
})

Official Documentation:- Converts a long url to a Bitlink.

It will Return BitLyLinkData after successful operation. And throws BitLyException on unsuccessful operation.

Example:--

try{
  final shortener = BitLyShortener(
    accessToken: "YOUR_TOKEN",
  );
  BitLyLinkData linkData=await shortener.generateShortLink(longUrl: 'ANY_URL');
  print(linkData.link);
}
on BitLyException catch(e){ //For handling BitLyException
  print(e);
}
on Exception catch(e){ // For handling other Exceptions related to http package
  print(e);
}

Check out official documentation for more info.

Implementation

Future<BitLyLinkData> generateShortLink({
  ///Url which you want to generate shortLink of
  ///link must be a valid link
  required String longUrl,

  ///Your Custom Domain.
  ///
  /// By Default " bit.ly "
  String domain = "bit.ly",

  /// group_guid
  /// can be null
  String? groupGuid,
}) async {
  final _body = jsonEncode({
    "long_url": longUrl,
    "domain": domain,
    "group_guid": groupGuid,
  });
  final response = await post(
    Uri.parse(_shortUri),
    body: _body,
    headers: {
      _contentTypeHeader: _jsonContentType,
      _authHeader: "Bearer $accessToken",
    },
  );
  if (response.statusCode == 200 || response.statusCode == 201) {
    final _linkData = jsonDecode(response.body);
    return BitLyLinkData.fromMap(_linkData);
  } else {
    final _errorData = jsonDecode(response.body);
    throw BitLyException(_errorData);
  }
}