This was asked for by
and I thought it could be a useful widget for many of us, so I threw it together.
Name your widget:
Then set the definition as follows:
and here is the code:
import 'package:flutter/services.dart';
import 'package:flutter_link_previewer/flutter_link_previewer.dart' as preview;
import 'package:flutter_chat_types/flutter_chat_types.dart' show PreviewData;
class LinkPreviewWidget extends StatefulWidget {
const LinkPreviewWidget({
Key? key,
this.width,
this.height,
required this.link,
}) : super(key: key);
final double? width;
final double? height;
final String link;
@override
_LinkPreviewWidgetState createState() => _LinkPreviewWidgetState();
}
class _LinkPreviewWidgetState extends State<LinkPreviewWidget> {
Map<String, PreviewData> datas = {};
@override
Widget build(BuildContext context) {
return Container(
width: widget.width,
height: widget.height,
child: preview.LinkPreview(
enableAnimation: true,
onPreviewDataFetched: (data) {
setState(() {
// Save preview data to the state
datas = {
...datas,
widget.link: data,
};
});
},
previewData: datas[widget.link], // Pass the preview data from the state
text: widget.link,
width: widget.width!,
),
);
}
}
Just add it to a page like so:
And this is the result:
IMPORTANT: Links will NOT preview in FF run mode. You will only see the correct preview on real devices or in emulators.
Happy Fluttering!