Tutorial and code of Any Link Preview in Flutter. Copy and paste the below code as per your requirements.
any_link_preview: ^2.0.6
import 'package:any_link_preview/any_link_preview.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final String _errorImage =
"https://i.ytimg.com/vi/z8wrRRR7_qU/maxresdefault.jpg";
final String _url1 =
"https://www.nilenpatelinc.com/post/here-is-when-you-can-download-ios-15-and-ipados-15-in-different-timezones-of-world";
final String _url2 =
"https://www.nilenpatelinc.com/post/how-to-delete-your-instagram-account-permanently";
final String _url3 =
"https://twitter.com/NilenPatelInc/status/1458498299837644804?s=20&t=TkSsvbaXVQRbuWxdJol7xg";
final String _url4 = "https://www.youtube.com/watch?v=y_WqWTK8rNM";
@override
void initState() {
super.initState();
_getMetadata(_url4);
}
void _getMetadata(String url) async {
bool _isValid = _getUrlValid(url);
if (_isValid) {
Metadata? _metadata = await AnyLinkPreview.getMetadata(
link: url,
cache: const Duration(days: 7),
proxyUrl: "https://cors-anywhere.herokuapp.com/", // Needed for web app
);
debugPrint(_metadata?.title);
debugPrint(_metadata?.desc);
} else {
debugPrint("URL is not valid");
}
}
bool _getUrlValid(String url) {
bool _isUrlValid = AnyLinkPreview.isValidLink(
url,
protocols: ['http', 'https'],
hostWhitelist: ['https://youtube.com/'],
hostBlacklist: ['https://facebook.com/'],
);
return _isUrlValid;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(title: const Center(child: Text('Any Link Preview'),)),
body: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnyLinkPreview(
link: _url1,
displayDirection: uiDirection.uiDirectionHorizontal,
cache: const Duration(hours: 1),
backgroundColor: Colors.grey[300],
errorWidget: Container(
color: Colors.grey[300],
child: const Text('Oops!'),
),
errorImage: _errorImage,
),
const SizedBox(height: 25),
AnyLinkPreview(
link: _url2,
displayDirection: uiDirection.uiDirectionHorizontal,
showMultimedia: false,
bodyMaxLines: 5,
bodyTextOverflow: TextOverflow.ellipsis,
titleStyle: const TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 15,
),
bodyStyle: const TextStyle(color: Colors.grey, fontSize: 12),
),
const SizedBox(height: 25),
AnyLinkPreview(
displayDirection: uiDirection.uiDirectionHorizontal,
link: _url3,
errorBody: 'Show my custom error body',
errorTitle: 'Next one is youtube link, error title',
),
const SizedBox(height: 25),
AnyLinkPreview(link: _url4),
],
),
),
),
);
}
}