added hashtag example

This commit is contained in:
Deven Joshi
2021-07-29 15:13:16 +05:30
parent 953d330bbe
commit 4985cb1904
2 changed files with 59 additions and 1 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

@@ -97,4 +97,62 @@ MessageListView(
);
},
)
```
```
### Adding Hashtags
To add elements like hashtags, we can override the `textBuilder` in the MessageWidget:
```
MessageListView(
...
messageBuilder: (context, messageDetails, messageList, defaultWidget) {
return defaultWidget.copyWith(
textBuilder: (context, message) {
final text = _replaceHashtags(message.text).replaceAll('\n', '\\\n');
final messageTheme = StreamChatTheme.of(context).ownMessageTheme;
return MarkdownBody(
data: text,
onTapLink: (
String link,
String href,
String title,
) {
// Do something with tapped hashtag
},
styleSheet: MarkdownStyleSheet.fromTheme(
Theme.of(context).copyWith(
textTheme: Theme.of(context).textTheme.apply(
bodyColor: messageTheme.messageText.color,
decoration: messageTheme.messageText.decoration,
decorationColor: messageTheme.messageText.decorationColor,
decorationStyle: messageTheme.messageText.decorationStyle,
fontFamily: messageTheme.messageText.fontFamily,
),
),
).copyWith(
a: messageTheme.messageLinks,
p: messageTheme.messageText,
),
);
},
);
},
)
String _replaceHashtags(String text) {
RegExp exp = new RegExp(r"\B#\w\w+");
exp.allMatches(text).forEach((match){
text = text.replaceAll(
'${match.group(0)}', '[${match.group(0)}](${match.group(0).replaceAll(' ', '')})');
});
return text;
}
```
We can replace the hashtags using RegEx and add links for the MarkdownBody which is done here in the
`_replaceHashtags()` function.
Inside the textBuilder, we use the `flutter_markdown` package to build our hashtags as links.
![](../assets/hashtag_example.jpg)