forked from Cretezy/flutter_linkify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflutter_linkify.dart
120 lines (104 loc) · 2.66 KB
/
flutter_linkify.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:linkify/linkify.dart';
export 'package:linkify/linkify.dart'
show
LinkifyElement,
LinkableElement,
LinkElement,
EmailElement,
TextElement,
LinkType,
TelephoneElement;
/// Callback clicked link
typedef LinkCallback = Function(LinkableElement link);
/// Turns URLs into links
class Linkify extends StatelessWidget {
/// Text to be linkified
final String text;
/// Enables some types of links (URL, email).
/// Will default to all (if `null`).
final List<LinkType> linkTypes;
/// Callback for tapping a link
final LinkCallback onOpen;
/// Removes http/https from shown URLS.
/// Will default to `false` (if `null`)
final bool humanize;
// TextSpan
/// Style for non-link text
final TextStyle style;
/// Style of link text
final TextStyle linkStyle;
// RichText
/// How the text should be aligned horizontally.
final TextAlign textAlign;
/// Text direction of the text
final TextDirection textDirection;
const Linkify({
Key key,
this.text,
this.linkTypes,
this.onOpen,
this.humanize,
// TextSpawn
this.style,
this.linkStyle,
// RichText
this.textAlign = TextAlign.start,
this.textDirection,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final elements = linkify(
text,
humanize: humanize,
linkTypes: linkTypes,
);
return RichText(
textAlign: textAlign,
textDirection: textDirection,
text: buildTextSpan(
elements,
style: Theme.of(context).textTheme.body1.merge(style),
onOpen: onOpen,
linkStyle: Theme.of(context)
.textTheme
.body1
.merge(style)
.copyWith(
color: Colors.blueAccent,
decoration: TextDecoration.underline,
)
.merge(linkStyle),
),
);
}
}
/// Raw TextSpan builder for more control on the RichText
TextSpan buildTextSpan(
List<LinkifyElement> elements, {
TextStyle style,
TextStyle linkStyle,
LinkCallback onOpen,
}) {
return TextSpan(
children: elements.map<TextSpan>(
(element) {
if (element is LinkableElement) {
return TextSpan(
text: element.text,
style: linkStyle,
recognizer: onOpen != null
? (TapGestureRecognizer()..onTap = () => onOpen(element))
: null,
);
} else {
return TextSpan(
text: element.text,
style: style,
);
}
},
).toList(),
);
}