Autocomplete Triggers
Adding Custom Autocomplete Triggers
Introduction
The StreamMessageInput widget provides a way to add custom autocomplete triggers using the StreamMessageInput.customAutocompleteTriggers
property.
By default we provide autocomplete triggers for mentions and commands, but it's very easy to add your custom ones.
Add Emoji Autocomplete Trigger
To add a custom emoji autocomplete trigger, you must first create an AutoCompleteOptions
widget.
This widget will be used to show the autocomplete options.
For this example we're using two external dependencies:
import 'package:emojis/emoji.dart';
import 'package:flutter/material.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import 'package:substring_highlight/substring_highlight.dart';
/// Overlay for displaying emoji that can be used
class StreamEmojiAutocompleteOptions extends StatelessWidget {
/// Constructor for creating a [StreamEmojiAutocompleteOptions]
const StreamEmojiAutocompleteOptions({
super.key,
required this.query,
this.onEmojiSelected,
});
/// Query for searching emoji.
final String query;
/// Callback called when an emoji is selected.
final ValueSetter<Emoji>? onEmojiSelected;
@override
Widget build(BuildContext context) {
final emojis = Emoji.all().where((it) {
final normalizedQuery = query.toUpperCase();
final normalizedShortName = it.shortName.toUpperCase();
return normalizedShortName.contains(normalizedQuery);
});
if (emojis.isEmpty) return const SizedBox.shrink();
return StreamAutocompleteOptions<Emoji>(
options: emojis,
optionBuilder: (context, emoji) {
final themeData = Theme.of(context);
return ListTile(
dense: true,
horizontalTitleGap: 0,
leading: Text(
emoji.char,
style: themeData.textTheme.titleLarge!.copyWith(
fontSize: 24,
),
),
title: SubstringHighlight(
text: emoji.shortName,
term: query,
textStyleHighlight: themeData.textTheme.titleLarge!.copyWith(
color: Colors.yellow,
fontSize: 14.5,
fontWeight: FontWeight.bold,
),
textStyle: themeData.textTheme.titleLarge!.copyWith(
fontSize: 14.5,
),
),
onTap: onEmojiSelected == null ? null : () => onEmojiSelected!(emoji),
);
},
);
}
}
Now it's time to use the StreamEmojiAutocompleteOptions
widget.
StreamMessageInput(
customAutocompleteTriggers: [
StreamAutocompleteTrigger(
trigger: ':',
minimumRequiredCharacters: 2,
optionsViewBuilder: (
context,
autocompleteQuery,
messageEditingController,
) {
final query = autocompleteQuery.query;
return StreamEmojiAutocompleteOptions(
query: query,
onEmojiSelected: (emoji) {
// accepting the autocomplete option.
StreamAutocomplete.of(context).acceptAutocompleteOption(
emoji.char,
keepTrigger: false,
);
},
);
},
),
],
),