Flutter链接预览生成插件neplox_linkpreviewer的使用
Flutter链接预览生成插件neplox_linkpreviewer的使用
neplox_linkpreviewer
是一个用于从URL中提取并显示丰富链接预览的Flutter插件。它支持自定义样式和行为,非常适合需要展示网页摘要的应用场景。
主要特性
- 自动元数据提取:轻松获取标题、描述、图片和图标等信息。
- 内置预览组件:
NeploxLinkPreviewer
提供了一个预设样式的链接预览。 - 可定制性:
- 控制缩略图位置(
NThumbnailPreviewDirection
)。 - 自定义文本和背景颜色。
- 选择在应用内或外部浏览器中打开链接(
NURLLaunch
,NURLLaunchIn
)。
- 控制缩略图位置(
- 灵活的元数据访问:使用
NeploxMetaDataFetcher
获取元数据以实现自定义UI。 - 缓存机制:通过缓存提高性能。
- 扩展性强:支持自定义小部件构建器,完全控制预览布局。
- 错误处理:优雅地处理无效URL和网络问题。
快速开始
安装
将以下内容添加到您的pubspec.yaml
文件中:
dependencies:
neplox_linkpreviewer: ^1.0.8
使用方法
1. 使用内置预览组件
// 底部方向样式
NeploxLinkPreviewer(
url: 'https://example.com',
linkPreviewOptions: NLinkPreviewOptions(
thumbnailPreviewDirection: NThumbnailPreviewDirection.bottom,
urlLaunch: NURLLaunch.enable,
urlLaunchIn: NURLLaunchIn.browser, // 或者 NURLLaunchIn.app
),
)
// 左至右方向样式
NeploxLinkPreviewer(
url: 'https://example.com',
linkPreviewOptions: NLinkPreviewOptions(
thumbnailPreviewDirection: NThumbnailPreviewDirection.ltr,
urlLaunch: NURLLaunch.enable,
urlLaunchIn: NURLLaunchIn.app,
),
cardStyle:NCardStyle( // 卡片样式
width: 0.95 * MediaQuery.of(context).size.width,
height: 0.45 * MediaQuery.of(context).size.height,
)
)
2. 获取元数据以创建自定义组件
final metaDataFetcher = NeploxMetaDataFetcher.instance;
final elementModel = await metaDataFetcher.fetchData('https://example.com');
// 使用elementModel.title, elementModel.description等构建自己的UI。
3. 属性配置
/// 显示方向 [normal,top,bottom,ltr,rtl]
final NThumbnailPreviewDirection thumbnailPreviewDirection;
/// 配置URL启动属性 [enable,disable]
final NURLLaunch urlLaunch;
/// 配置URL启动位置 [browser,app,none]
final NURLLaunchIn urlLaunchIn;
/// 配置卡片样式 [cardStyle]
final NCardStyle cardStyle;
/// 配置排版样式 [typographyStyle]
final NCTypographyStyle typographyStyle;
示例代码
下面是一个完整的示例项目,演示了如何使用该插件:
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:neplox_linkpreviewer/neplox_linkpreviewer.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
[@override](/user/override)
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> urls = [
"https://ekantipur.com/news/2023/02/05/167556100681196555.html",
"https://www.youtube.com/watch?v=A9hcJgtnm6Q&list=RDRDwrng3YkNU&index=5",
"https://www.youtube.com/watch?v=q_HEQajNwyY&list=RDq_HEQajNwyY&start_radio=1",
"https://www.youtube.com/watch?v=qik_1dDvzEs&list=RDq_HEQajNwyY&index=3",
];
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: ListView.builder(
itemCount: urls.length,
itemBuilder: (context, index) {
return LinkPreviwer(url: urls[index]);
}));
}
}
class LinkPreviwer extends StatefulWidget {
const LinkPreviwer({Key? key, required this.url}) : super(key: key);
final String url;
[@override](/user/override)
State<LinkPreviwer> createState() => _LinkPreviwerState();
}
class _LinkPreviwerState extends State<LinkPreviwer> {
final random = Random();
List<NThumbnailPreviewDirection> directions = [
NThumbnailPreviewDirection.ltr,
NThumbnailPreviewDirection.bottom,
NThumbnailPreviewDirection.rtl,
NThumbnailPreviewDirection.top,
NThumbnailPreviewDirection.normal
];
[@override](/user/override)
Widget build(BuildContext context) {
int randomIndex = random.nextInt(directions.length);
return Padding(
padding: const EdgeInsets.all(10.0),
child: NeploxLinkPreviewer(
url: widget.url,
linkPreviewOptions: NLinkPreviewOptions(
urlLaunch: NURLLaunch.enable,
urlLaunchIn: NURLLaunchIn.browser,
thumbnailPreviewDirection: directions[randomIndex],
),
),
);
}
}
更多关于Flutter链接预览生成插件neplox_linkpreviewer的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter链接预览生成插件neplox_linkpreviewer的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用neplox_linkpreviewer
插件来生成链接预览的示例代码。
首先,确保你已经在pubspec.yaml
文件中添加了neplox_linkpreviewer
依赖项:
dependencies:
flutter:
sdk: flutter
neplox_linkpreviewer: ^最新版本号 # 请替换为最新版本号
然后,运行以下命令以获取依赖项:
flutter pub get
接下来,你可以在你的Flutter应用中使用neplox_linkpreviewer
插件。以下是一个简单的示例,展示如何生成并显示链接预览:
import 'package:flutter/material.dart';
import 'package:neplox_linkpreviewer/neplox_linkpreviewer.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Link Preview Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: LinkPreviewScreen(),
);
}
}
class LinkPreviewScreen extends StatefulWidget {
@override
_LinkPreviewScreenState createState() => _LinkPreviewScreenState();
}
class _LinkPreviewScreenState extends State<LinkPreviewScreen> {
String? link;
LinkPreviewModel? linkPreview;
void fetchLinkPreview(String url) async {
try {
linkPreview = await NeploxLinkPreviewer.fetchPreview(url);
} catch (e) {
print('Error fetching link preview: $e');
}
if (mounted) {
setState(() {});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Link Preview Example'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
decoration: InputDecoration(
labelText: 'Enter URL',
border: OutlineInputBorder(),
),
onEditingComplete: () async {
if (link != null && link!.isNotEmpty) {
fetchLinkPreview(link!);
}
},
onChanged: (value) {
link = value;
},
),
SizedBox(height: 20),
if (linkPreview != null) {
Text('Title: ${linkPreview!.title}'),
Text('Description: ${linkPreview!.description}'),
Text('Thumbnail URL: ${linkPreview!.thumbnailUrl}'),
if (linkPreview!.siteName != null) {
Text('Site Name: ${linkPreview!.siteName!}'),
}
if (linkPreview!.type != null) {
Text('Type: ${linkPreview!.type!}'),
}
SizedBox(height: 20),
Image.network(
linkPreview!.thumbnailUrl,
width: double.infinity,
height: 200,
fit: BoxFit.cover,
loadingBuilder: (context, child, loadingProgress) {
if (loadingProgress == null) return child;
return Center(
child: CircularProgressIndicator(
value: loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes!
: null,
),
);
},
errorWidget: (context, url, error) => Icon(Icons.error),
),
} else {
Text('Please enter a valid URL and press Enter'),
},
],
),
),
);
}
}
class LinkPreviewModel {
String? title;
String? description;
String? thumbnailUrl;
String? siteName;
String? type;
// Add other fields if needed
LinkPreviewModel({
this.title,
this.description,
this.thumbnailUrl,
this.siteName,
this.type,
});
factory LinkPreviewModel.fromJson(Map<String, dynamic> json) {
return LinkPreviewModel(
title: json['title'] as String?,
description: json['description'] as String?,
thumbnailUrl: json['thumbnail_url'] as String?,
siteName: json['site_name'] as String?,
type: json['type'] as String?,
);
}
}
在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个TextField
用于输入URL,并有一个按钮(通过onEditingComplete
触发)来生成链接预览。预览数据(如标题、描述和缩略图URL)会显示在界面上。
注意:
LinkPreviewModel
类用于解析从插件返回的JSON数据。Image.network
用于显示链接预览的缩略图,并包括一个加载指示器和一个错误小部件。
确保在实际应用中处理所有潜在的错误和边界情况,如无效的URL、网络问题等。