Flutter 原生 Linkify
native_linkify 是一个 Flutter 插件。使用它可以查找纯文本中的链接。
该插件为 iOS 和 macOS 使用 NSDataDetector;为 Android 使用 Linkify。这意味着该插件的链接查找方式与大多数原生应用相同,比现有的纯 Dart 包提供了更准确的结果。
该插件开箱即用,没有显示内联链接的任何小部件,但它拥有创建您喜欢的方式所需的一切。
这是一个如何实现将文本 URL、电子邮件和电话转换为可点击链接的小部件的示例。
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:native_linkify/native_linkify.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final entries = await NativeLinkify.linkify(
'text link.com [email protected] and +79990000000');
// Note that this method is asynchronous because the plugin works with native
// functions via MethodChannel and MethodChannel works only in asynchronous way
// in real app it's better to linkify text at the place where you load it from
// your data source
runApp(
MyApp(
entries: entries,
),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key, required this.entries}) : super(key: key);
final List<LinkifyEntry> entries;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Text.rich(
TextSpan(
children: [
for (final l in entries)
if (l is LinkifyText)
// Regular text, text without links
TextSpan(
text: l.text,
)
else if (l is LinkifyUrl)
// Link
TextSpan(
text: l.text,
style: const TextStyle(color: Colors.blue),
recognizer: TapGestureRecognizer()
..onTap = () => launch(l.url),
)
],
),
),
),
),
);
}
}
