Skip to content

Instantly share code, notes, and snippets.

@quentin7b
Last active October 4, 2023 12:30
Show Gist options
  • Save quentin7b/b7bf7e7585db109b2ff5a335cb4d84e5 to your computer and use it in GitHub Desktop.
Save quentin7b/b7bf7e7585db109b2ff5a335cb4d84e5 to your computer and use it in GitHub Desktop.
A custom AutoComplete Widget in flutter that makes it more easy to customize the render of the items
import 'package:flutter/material.dart';
class CustomAutoComplete<T extends Object> extends StatelessWidget {
final Iterable<T> options;
final Function(T) onSelected;
final String Function(T)? displayStringForOption;
final Widget Function(BuildContext, T)? optionsItemBuilder;
final Iterable<T> Function(TextEditingValue)? optionsFilter;
const CustomAutoComplete({
super.key,
required this.options,
required this.onSelected,
this.displayStringForOption,
this.optionsItemBuilder,
this.optionsFilter,
});
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) =>
Autocomplete<T>(
onSelected: (item) => onSelected(item),
displayStringForOption: (item) => displayStringForOption != null
? displayStringForOption!(item)
: item.toString(),
optionsViewBuilder: (context, onSelected, options) {
return Align(
alignment: Alignment.topLeft,
child: Material(
elevation: 4.0,
child: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: constraints.maxWidth,
maxHeight: 200,
),
child: ListView.builder(
padding: EdgeInsets.zero,
shrinkWrap: true,
itemCount: options.length,
itemBuilder: (BuildContext context, int index) {
final option = options.elementAt(index);
return InkWell(
onTap: () => onSelected(option),
child: optionsItemBuilder != null
? optionsItemBuilder!(context, option)
: ListTile(
title: Text(
displayStringForOption != null
? displayStringForOption!(option)
: option.toString(),
),
),
);
},
),
),
),
);
},
optionsBuilder: (TextEditingValue text) {
return optionsFilter != null
? optionsFilter!(text)
: options.where((b) => b.toString().contains(text.text)).toList();
},
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment