-
Notifications
You must be signed in to change notification settings - Fork 353
/
Copy pathflutter_typeahead.dart
1410 lines (1271 loc) · 50.2 KB
/
flutter_typeahead.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// # Flutter TypeAhead
/// A TypeAhead widget for Flutter, where you can show suggestions to
/// users as they type
///
/// ## Features
/// * Shows suggestions in an overlay that floats on top of other widgets
/// * Allows you to specify what the suggestions will look like through a
/// builder function
/// * Allows you to specify what happens when the user taps a suggestion
/// * Accepts all the parameters that traditional TextFields accept, like
/// decoration, custom TextEditingController, text styling, etc.
/// * Provides two versions, a normal version and a [FormField](https://docs.flutter.io/flutter/widgets/FormField-class.html)
/// version that accepts validation, submitting, etc.
/// * Provides high customizability; you can customize the suggestion box decoration,
/// the loading bar, the animation, the debounce duration, etc.
///
/// ## Installation
/// See the [installation instructions on pub](https://pub.dartlang.org/packages/flutter_typeahead#-installing-tab-).
///
/// ## Usage examples
/// You can import the package with:
/// ```dart
/// import 'package:flutter_typeahead/flutter_typeahead.dart';
/// ```
///
/// and then use it as follows:
///
/// ### Example 1:
/// ```dart
/// TypeAheadField(
/// textFieldConfiguration: TextFieldConfiguration(
/// autofocus: true,
/// style: DefaultTextStyle.of(context).style.copyWith(
/// fontStyle: FontStyle.italic
/// ),
/// decoration: InputDecoration(
/// border: OutlineInputBorder()
/// )
/// ),
/// suggestionsCallback: (pattern) async {
/// return await BackendService.getSuggestions(pattern);
/// },
/// itemBuilder: (context, suggestion) {
/// return ListTile(
/// leading: Icon(Icons.shopping_cart),
/// title: Text(suggestion['name']),
/// subtitle: Text('\$${suggestion['price']}'),
/// );
/// },
/// onSuggestionSelected: (suggestion) {
/// Navigator.of(context).push(MaterialPageRoute(
/// builder: (context) => ProductPage(product: suggestion)
/// ));
/// },
/// )
/// ```
/// In the code above, the `textFieldConfiguration` property allows us to
/// configure the displayed `TextField` as we want. In this example, we are
/// configuring the `autofocus`, `style` and `decoration` properties.
///
/// The `suggestionsCallback` is called with the search string that the user
/// types, and is expected to return a `List` of data either synchronously or
/// asynchronously. In this example, we are calling an asynchronous function
/// called `BackendService.getSuggestions` which fetches the list of
/// suggestions.
///
/// The `itemBuilder` is called to build a widget for each suggestion.
/// In this example, we build a simple `ListTile` that shows the name and the
/// price of the item. Please note that you shouldn't provide an `onTap`
/// callback here. The TypeAhead widget takes care of that.
///
/// The `onSuggestionSelected` is a callback called when the user taps a
/// suggestion. In this example, when the user taps a
/// suggestion, we navigate to a page that shows us the information of the
/// tapped product.
///
/// ### Example 2:
/// Here's another example, where we use the TypeAheadFormField inside a `Form`:
/// ```dart
/// final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
/// final TextEditingController _typeAheadController = TextEditingController();
/// String _selectedCity;
/// ...
/// Form(
/// key: this._formKey,
/// child: Padding(
/// padding: EdgeInsets.all(32.0),
/// child: Column(
/// children: <Widget>[
/// Text(
/// 'What is your favorite city?'
/// ),
/// TypeAheadFormField(
/// textFieldConfiguration: TextFieldConfiguration(
/// controller: this._typeAheadController,
/// decoration: InputDecoration(
/// labelText: 'City'
/// )
/// ),
/// suggestionsCallback: (pattern) {
/// return CitiesService.getSuggestions(pattern);
/// },
/// itemBuilder: (context, suggestion) {
/// return ListTile(
/// title: Text(suggestion),
/// );
/// },
/// transitionBuilder: (context, suggestionsBox, controller) {
/// return suggestionsBox;
/// },
/// onSuggestionSelected: (suggestion) {
/// this._typeAheadController.text = suggestion;
/// },
/// validator: (value) {
/// if (value.isEmpty) {
/// return 'Please select a city';
/// }
/// },
/// onSaved: (value) => this._selectedCity = value,
/// ),
/// SizedBox(height: 10.0,),
/// RaisedButton(
/// child: Text('Submit'),
/// onPressed: () {
/// if (this._formKey.currentState.validate()) {
/// this._formKey.currentState.save();
/// Scaffold.of(context).showSnackBar(SnackBar(
/// content: Text('Your Favorite City is ${this._selectedCity}')
/// ));
/// }
/// },
/// )
/// ],
/// ),
/// ),
/// )
/// ```
/// Here, we assign to the `controller` property of the `textFieldConfiguration`
/// a `TextEditingController` that we call `_typeAheadController`.
/// We use this controller in the `onSuggestionSelected` callback to set the
/// value of the `TextField` to the selected suggestion.
///
/// The `validator` callback can be used like any `FormField.validator`
/// function. In our example, it checks whether a value has been entered,
/// and displays an error message if not. The `onSaved` callback is used to
/// save the value of the field to the `_selectedCity` member variable.
///
/// The `transitionBuilder` allows us to customize the animation of the
/// suggestion box. In this example, we are returning the suggestionsBox
/// immediately, meaning that we don't want any animation.
///
/// ## Customizations
/// TypeAhead widgets consist of a TextField and a suggestion box that shows
/// as the user types. Both are highly customizable
///
/// ### Customizing the TextField
/// You can customize the text field using the `textFieldConfiguration` property.
/// You provide this property with an instance of `TextFieldConfiguration`,
/// which allows you to configure all the usual properties of `TextField`, like
/// `decoration`, `style`, `controller`, `focusNode`, `autofocus`, `enabled`,
/// etc.
///
/// ### Customizing the Suggestions Box
/// TypeAhead provides default configurations for the suggestions box. You can,
/// however, override most of them.
///
/// #### Customizing the loader, the error and the "no items found" message
/// You can use the [loadingBuilder], [errorBuilder] and [noItemsFoundBuilder] to
/// customize their corresponding widgets. For example, to show a custom error
/// widget:
/// ```dart
/// errorBuilder: (BuildContext context, Object error) =>
/// Text(
/// '$error',
/// style: TextStyle(
/// color: Theme.of(context).errorColor
/// )
/// )
/// ```
/// #### Customizing the animation
/// You can customize the suggestion box animation through 3 parameters: the
/// `animationDuration`, the `animationStart`, and the `transitionBuilder`.
///
/// The `animationDuration` specifies how long the animation should take, while the
/// `animationStart` specified what point (between 0.0 and 1.0) the animation
/// should start from. The `transitionBuilder` accepts the `suggestionsBox` and
/// `animationController` as parameters, and should return a widget that uses
/// the `animationController` to animate the display of the `suggestionsBox`.
/// For example:
/// ```dart
/// transitionBuilder: (context, suggestionsBox, animationController) =>
/// FadeTransition(
/// child: suggestionsBox,
/// opacity: CurvedAnimation(
/// parent: animationController,
/// curve: Curves.fastOutSlowIn
/// ),
/// )
/// ```
/// This uses [FadeTransition](https://docs.flutter.io/flutter/widgets/FadeTransition-class.html)
/// to fade the `suggestionsBox` into the view. Note how the
/// `animationController` was provided as the parent of the animation.
///
/// In order to fully remove the animation, `transitionBuilder` should simply
/// return the `suggestionsBox`. This callback could also be used to wrap the
/// `suggestionsBox` with any desired widgets, not necessarily for animation.
///
/// #### Customizing the debounce duration
/// The suggestions box does not fire for each character the user types. Instead,
/// we wait until the user is idle for a duration of time, and then call the
/// `suggestionsCallback`. The duration defaults to 300 milliseconds, but can be
/// configured using the `debounceDuration` parameter.
///
/// #### Customizing the offset of the suggestions box
/// By default, the suggestions box is displayed 5 pixels below the `TextField`.
/// You can change this by changing the `suggestionsBoxVerticalOffset` property.
///
/// #### Customizing the decoration of the suggestions box
/// You can also customize the decoration of the suggestions box using the
/// `suggestionsBoxDecoration` property. For example, to remove the elevation
/// of the suggestions box, you can write:
/// ```dart
/// suggestionsBoxDecoration: SuggestionsBoxDecoration(
/// elevation: 0.0
/// )
/// ```
library flutter_typeahead;
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
typedef FutureOr<List<T>> SuggestionsCallback<T>(String pattern);
typedef Widget ItemBuilder<T>(BuildContext context, T itemData);
typedef void SuggestionSelectionCallback<T>(T suggestion);
typedef Widget ErrorBuilder(BuildContext context, Object error);
typedef AnimationTransitionBuilder(
BuildContext context, Widget child, AnimationController controller);
/// A [FormField](https://docs.flutter.io/flutter/widgets/FormField-class.html)
/// implementation of [TypeAheadField], that allows the value to be saved,
/// validated, etc.
///
/// See also:
///
/// * [TypeAheadField], A [TextField](https://docs.flutter.io/flutter/material/TextField-class.html)
/// that displays a list of suggestions as the user types
class TypeAheadFormField<T> extends FormField<String> {
/// The configuration of the [TextField](https://docs.flutter.io/flutter/material/TextField-class.html)
/// that the TypeAhead widget displays
final TextFieldConfiguration textFieldConfiguration;
/// Creates a [TypeAheadFormField]
TypeAheadFormField(
{Key key,
String initialValue,
bool getImmediateSuggestions: false,
bool autovalidate: false,
FormFieldSetter<String> onSaved,
FormFieldValidator<String> validator,
ErrorBuilder errorBuilder,
WidgetBuilder noItemsFoundBuilder,
WidgetBuilder loadingBuilder,
Duration debounceDuration: const Duration(milliseconds: 300),
SuggestionsBoxDecoration suggestionsBoxDecoration:
const SuggestionsBoxDecoration(),
@required SuggestionSelectionCallback<T> onSuggestionSelected,
@required ItemBuilder<T> itemBuilder,
@required SuggestionsCallback<T> suggestionsCallback,
double suggestionsBoxVerticalOffset: 5.0,
this.textFieldConfiguration: const TextFieldConfiguration(),
AnimationTransitionBuilder transitionBuilder,
Duration animationDuration: const Duration(milliseconds: 500),
double animationStart: 0.25,
AxisDirection direction: AxisDirection.down})
: assert(
initialValue == null || textFieldConfiguration.controller == null),
super(
key: key,
onSaved: onSaved,
validator: validator,
autovalidate: autovalidate,
initialValue: textFieldConfiguration.controller != null
? textFieldConfiguration.controller.text
: (initialValue ?? ''),
builder: (FormFieldState<String> field) {
final _TypeAheadFormFieldState state = field;
return TypeAheadField(
getImmediateSuggestions: getImmediateSuggestions,
transitionBuilder: transitionBuilder,
errorBuilder: errorBuilder,
noItemsFoundBuilder: noItemsFoundBuilder,
loadingBuilder: loadingBuilder,
debounceDuration: debounceDuration,
suggestionsBoxDecoration: suggestionsBoxDecoration,
textFieldConfiguration: textFieldConfiguration.copyWith(
decoration: textFieldConfiguration.decoration
.copyWith(errorText: state.errorText),
onChanged: state.didChange,
controller: state._effectiveController,
),
suggestionsBoxVerticalOffset: suggestionsBoxVerticalOffset,
onSuggestionSelected: onSuggestionSelected,
itemBuilder: itemBuilder,
suggestionsCallback: suggestionsCallback,
animationStart: animationStart,
animationDuration: animationDuration,
direction: direction,
);
});
@override
_TypeAheadFormFieldState<T> createState() => _TypeAheadFormFieldState();
}
class _TypeAheadFormFieldState<T> extends FormFieldState<String> {
TextEditingController _controller;
TextEditingController get _effectiveController =>
widget.textFieldConfiguration.controller ?? _controller;
@override
TypeAheadFormField get widget => super.widget;
@override
void initState() {
super.initState();
if (widget.textFieldConfiguration.controller == null) {
_controller = TextEditingController(text: widget.initialValue);
} else {
widget.textFieldConfiguration.controller
.addListener(_handleControllerChanged);
}
}
@override
void didUpdateWidget(TypeAheadFormField oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.textFieldConfiguration.controller !=
oldWidget.textFieldConfiguration.controller) {
oldWidget.textFieldConfiguration.controller
?.removeListener(_handleControllerChanged);
widget.textFieldConfiguration.controller
?.addListener(_handleControllerChanged);
if (oldWidget.textFieldConfiguration.controller != null &&
widget.textFieldConfiguration.controller == null)
_controller = TextEditingController.fromValue(
oldWidget.textFieldConfiguration.controller.value);
if (widget.textFieldConfiguration.controller != null) {
setValue(widget.textFieldConfiguration.controller.text);
if (oldWidget.textFieldConfiguration.controller == null)
_controller = null;
}
}
}
@override
void dispose() {
widget.textFieldConfiguration.controller
?.removeListener(_handleControllerChanged);
super.dispose();
}
@override
void reset() {
super.reset();
setState(() {
_effectiveController.text = widget.initialValue;
});
}
void _handleControllerChanged() {
// Suppress changes that originated from within this class.
//
// In the case where a controller has been passed in to this widget, we
// register this change listener. In these cases, we'll also receive change
// notifications for changes originating from within this class -- for
// example, the reset() method. In such cases, the FormField value will
// already have been set.
if (_effectiveController.text != value)
didChange(_effectiveController.text);
}
}
/// A [TextField](https://docs.flutter.io/flutter/material/TextField-class.html)
/// that displays a list of suggestions as the user types
///
/// See also:
///
/// * [TypeAheadFormField], a [FormField](https://docs.flutter.io/flutter/widgets/FormField-class.html)
/// implementation of [TypeAheadField] that allows the value to be saved,
/// validated, etc.
class TypeAheadField<T> extends StatefulWidget {
/// Called with the search pattern to get the search suggestions.
///
/// This callback must not be null. It is be called by the TypeAhead widget
/// and provided with the search pattern. It should return a [List](https://api.dartlang.org/stable/2.0.0/dart-core/List-class.html)
/// of suggestions either synchronously, or asynchronously (as the result of a
/// [Future](https://api.dartlang.org/stable/dart-async/Future-class.html)).
/// Typically, the list of suggestions should not contain more than 4 or 5
/// entries. These entries will then be provided to [itemBuilder] to display
/// the suggestions.
///
/// Example:
/// ```dart
/// suggestionsCallback: (pattern) async {
/// return await _getSuggestions(pattern);
/// }
/// ```
final SuggestionsCallback<T> suggestionsCallback;
/// Called when a suggestion is tapped.
///
/// This callback must not be null. It is called by the TypeAhead widget and
/// provided with the value of the tapped suggestion.
///
/// For example, you might want to navigate to a specific view when the user
/// tabs a suggestion:
/// ```dart
/// onSuggestionSelected: (suggestion) {
/// Navigator.of(context).push(MaterialPageRoute(
/// builder: (context) => SearchResult(
/// searchItem: suggestion
/// )
/// ));
/// }
/// ```
///
/// Or to set the value of the text field:
/// ```dart
/// onSuggestionSelected: (suggestion) {
/// _controller.text = suggestion['name'];
/// }
/// ```
final SuggestionSelectionCallback<T> onSuggestionSelected;
/// Called for each suggestion returned by [suggestionsCallback] to build the
/// corresponding widget.
///
/// This callback must not be null. It is called by the TypeAhead widget for
/// each suggestion, and expected to build a widget to display this
/// suggestion's info. For example:
///
/// ```dart
/// itemBuilder: (context, suggestion) {
/// return ListTile(
/// title: Text(suggestion['name']),
/// subtitle: Text('USD' + suggestion['price'].toString())
/// );
/// }
/// ```
final ItemBuilder<T> itemBuilder;
/// The decoration of the material sheet that contains the suggestions.
///
/// If null, default decoration with an elevation of 4.0 is used
final SuggestionsBoxDecoration suggestionsBoxDecoration;
/// The duration to wait after the user stops typing before calling
/// [suggestionsCallback]
///
/// This is useful, because, if not set, a request for suggestions will be
/// sent for every character that the user types.
///
/// This duration is set by default to 300 milliseconds
final Duration debounceDuration;
/// Called when waiting for [suggestionsCallback] to return.
///
/// It is expected to return a widget to display while waiting.
/// For example:
/// ```dart
/// (BuildContext context) {
/// return Text('Loading...');
/// }
/// ```
///
/// If not specified, a [CircularProgressIndicator](https://docs.flutter.io/flutter/material/CircularProgressIndicator-class.html) is shown
final WidgetBuilder loadingBuilder;
/// Called when [suggestionsCallback] returns an empty array.
///
/// It is expected to return a widget to display when no suggestions are
/// avaiable.
/// For example:
/// ```dart
/// (BuildContext context) {
/// return Text('No Items Found!');
/// }
/// ```
///
/// If not specified, a simple text is shown
final WidgetBuilder noItemsFoundBuilder;
/// Called when [suggestionsCallback] throws an exception.
///
/// It is called with the error object, and expected to return a widget to
/// display when an exception is thrown
/// For example:
/// ```dart
/// (BuildContext context, error) {
/// return Text('$error');
/// }
/// ```
///
/// If not specified, the error is shown in [ThemeData.errorColor](https://docs.flutter.io/flutter/material/ThemeData/errorColor.html)
final ErrorBuilder errorBuilder;
/// Called to display animations when [suggestionsCallback] returns suggestions
///
/// It is provided with the suggestions box instance and the animation
/// controller, and expected to return some animation that uses the controller
/// to display the suggestion box.
///
/// For example:
/// ```dart
/// transitionBuilder: (context, suggestionsBox, animationController) {
/// return FadeTransition(
/// child: suggestionsBox,
/// opacity: CurvedAnimation(
/// parent: animationController,
/// curve: Curves.fastOutSlowIn
/// ),
/// );
/// }
/// ```
/// This argument is best used with [animationDuration] and [animationStart]
/// to fully control the animation.
///
/// To fully remove the animation, just return `suggstionsBox`
///
/// If not specified, a [SizeTransition](https://docs.flutter.io/flutter/widgets/SizeTransition-class.html) is shown.
final AnimationTransitionBuilder transitionBuilder;
/// The duration that [transitionBuilder] animation takes.
///
/// This argument is best used with [transitionBuilder] and [animationStart]
/// to fully control the animation.
///
/// Defaults to 500 milliseconds.
final Duration animationDuration;
/// Determine the [SuggestionBox]'s direction.
///
/// If [AxisDirection.down], the [SuggestionBox] will be below the [TextField]
/// and the [_SuggestionsList] will grow **down**.
///
/// If [AxisDirection.up], the [SuggestionBox] will be above the [TextField]
/// and the [_SuggestionsList] will grow **up**.
///
/// [AxisDirection.left] and [AxisDirection.right] are not allowed.
final AxisDirection direction;
/// The value at which the [transitionBuilder] animation starts.
///
/// This argument is best used with [transitionBuilder] and [animationDuration]
/// to fully control the animation.
///
/// Defaults to 0.25.
final double animationStart;
/// The configuration of the [TextField](https://docs.flutter.io/flutter/material/TextField-class.html)
/// that the TypeAhead widget displays
final TextFieldConfiguration textFieldConfiguration;
/// How far below the text field should the suggestions box be
///
/// Defaults to 5.0
final double suggestionsBoxVerticalOffset;
/// If set to true, suggestions will be fetched immediately when the field is
/// added to the view.
///
/// But the suggestions box will only be shown when the field receives focus.
/// To make the field receive focus immediately, you can set the `autofocus`
/// property in the [textFieldConfiguration] to true
///
/// Defaults to false
final bool getImmediateSuggestions;
/// Creates a [TypeAheadField]
TypeAheadField(
{Key key,
@required this.suggestionsCallback,
@required this.itemBuilder,
@required this.onSuggestionSelected,
this.textFieldConfiguration: const TextFieldConfiguration(),
this.suggestionsBoxDecoration: const SuggestionsBoxDecoration(),
this.debounceDuration: const Duration(milliseconds: 300),
this.loadingBuilder,
this.noItemsFoundBuilder,
this.errorBuilder,
this.transitionBuilder,
this.animationStart: 0.25,
this.animationDuration: const Duration(milliseconds: 500),
this.getImmediateSuggestions: false,
this.suggestionsBoxVerticalOffset: 5.0,
this.direction: AxisDirection.down})
: assert(suggestionsCallback != null),
assert(itemBuilder != null),
assert(onSuggestionSelected != null),
assert(animationStart != null &&
animationStart >= 0.0 &&
animationStart <= 1.0),
assert(animationDuration != null),
assert(debounceDuration != null),
assert(textFieldConfiguration != null),
assert(suggestionsBoxDecoration != null),
assert(suggestionsBoxVerticalOffset != null),
assert(
direction == AxisDirection.down || direction == AxisDirection.up),
super(key: key);
@override
_TypeAheadFieldState createState() => _TypeAheadFieldState();
}
class _TypeAheadFieldState<T> extends State<TypeAheadField<T>>
with WidgetsBindingObserver {
FocusNode _focusNode;
TextEditingController _textEditingController;
_SuggestionsBoxController _suggestionsBoxController;
TextEditingController get _effectiveController =>
widget.textFieldConfiguration.controller ?? _textEditingController;
FocusNode get _effectiveFocusNode =>
widget.textFieldConfiguration.focusNode ?? _focusNode;
final LayerLink _layerLink = LayerLink();
@override
void didChangeMetrics() {
// Catch keyboard event and orientation change; resize suggestions list
this._suggestionsBoxController.onChangeMetrics();
}
@override
void dispose() {
this._suggestionsBoxController.widgetMounted = false;
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
if (widget.textFieldConfiguration.controller == null) {
this._textEditingController = TextEditingController();
}
if (widget.textFieldConfiguration.focusNode == null) {
this._focusNode = FocusNode();
}
this._suggestionsBoxController =
_SuggestionsBoxController(context, widget.direction);
WidgetsBinding.instance.addPostFrameCallback((duration) async {
await this._initOverlayEntry();
// calculate initial suggestions list size
this._suggestionsBoxController.resize();
this._effectiveFocusNode.addListener(() {
if (_effectiveFocusNode.hasFocus) {
this._suggestionsBoxController.open();
} else {
this._suggestionsBoxController.close();
}
});
// in case we already missed the focus event
if (this._effectiveFocusNode.hasFocus) {
this._suggestionsBoxController.open();
}
});
}
Future<void> _initOverlayEntry() async {
RenderBox renderBox = context.findRenderObject();
var size = renderBox.size;
this._suggestionsBoxController._overlayEntry =
OverlayEntry(builder: (context) {
final suggestionsList = _SuggestionsList<T>(
suggestionsBoxController: _suggestionsBoxController,
decoration: widget.suggestionsBoxDecoration,
debounceDuration: widget.debounceDuration,
controller: this._effectiveController,
loadingBuilder: widget.loadingBuilder,
noItemsFoundBuilder: widget.noItemsFoundBuilder,
errorBuilder: widget.errorBuilder,
transitionBuilder: widget.transitionBuilder,
suggestionsCallback: widget.suggestionsCallback,
animationDuration: widget.animationDuration,
animationStart: widget.animationStart,
getImmediateSuggestions: widget.getImmediateSuggestions,
onSuggestionSelected: (T selection) {
this._effectiveFocusNode.unfocus();
widget.onSuggestionSelected(selection);
},
itemBuilder: widget.itemBuilder,
direction: widget.direction,
);
return Positioned(
width: size.width,
child: CompositedTransformFollower(
link: this._layerLink,
showWhenUnlinked: false,
offset: Offset(
0.0,
widget.direction == AxisDirection.down
? size.height + widget.suggestionsBoxVerticalOffset
: -widget.suggestionsBoxVerticalOffset),
child: widget.direction == AxisDirection.down
? suggestionsList
: FractionalTranslation(
translation:
Offset(0.0, -1.0), // visually flips list to go up
child: suggestionsList,
),
),
);
});
}
@override
Widget build(BuildContext context) {
return CompositedTransformTarget(
link: this._layerLink,
child: TextField(
focusNode: this._effectiveFocusNode,
controller: this._effectiveController,
decoration: widget.textFieldConfiguration.decoration,
style: widget.textFieldConfiguration.style,
textAlign: widget.textFieldConfiguration.textAlign,
enabled: widget.textFieldConfiguration.enabled,
keyboardType: widget.textFieldConfiguration.keyboardType,
autofocus: widget.textFieldConfiguration.autofocus,
inputFormatters: widget.textFieldConfiguration.inputFormatters,
autocorrect: widget.textFieldConfiguration.autocorrect,
maxLines: widget.textFieldConfiguration.maxLines,
maxLength: widget.textFieldConfiguration.maxLength,
maxLengthEnforced: widget.textFieldConfiguration.maxLengthEnforced,
obscureText: widget.textFieldConfiguration.obscureText,
onChanged: widget.textFieldConfiguration.onChanged,
onSubmitted: widget.textFieldConfiguration.onSubmitted,
onEditingComplete: widget.textFieldConfiguration.onEditingComplete,
scrollPadding: widget.textFieldConfiguration.scrollPadding,
textInputAction: widget.textFieldConfiguration.textInputAction,
textCapitalization: widget.textFieldConfiguration.textCapitalization,
keyboardAppearance: widget.textFieldConfiguration.keyboardAppearance,
cursorWidth: widget.textFieldConfiguration.cursorWidth,
cursorRadius: widget.textFieldConfiguration.cursorRadius,
cursorColor: widget.textFieldConfiguration.cursorColor,
),
);
}
}
class _SuggestionsList<T> extends StatefulWidget {
final _SuggestionsBoxController suggestionsBoxController;
final TextEditingController controller;
final bool getImmediateSuggestions;
final SuggestionSelectionCallback<T> onSuggestionSelected;
final SuggestionsCallback suggestionsCallback;
final ItemBuilder itemBuilder;
final SuggestionsBoxDecoration decoration;
final Duration debounceDuration;
final WidgetBuilder loadingBuilder;
final WidgetBuilder noItemsFoundBuilder;
final ErrorBuilder errorBuilder;
final AnimationTransitionBuilder transitionBuilder;
final Duration animationDuration;
final double animationStart;
final AxisDirection direction;
_SuggestionsList({
@required this.suggestionsBoxController,
this.controller,
this.getImmediateSuggestions: false,
this.onSuggestionSelected,
this.suggestionsCallback,
this.itemBuilder,
this.decoration,
this.debounceDuration,
this.loadingBuilder,
this.noItemsFoundBuilder,
this.errorBuilder,
this.transitionBuilder,
this.animationDuration,
this.animationStart,
this.direction,
});
@override
_SuggestionsListState createState() => _SuggestionsListState();
}
class _SuggestionsListState<T> extends State<_SuggestionsList<T>>
with SingleTickerProviderStateMixin {
List<T> _suggestions;
VoidCallback _controllerListener;
Timer _debounceTimer;
bool _isLoading;
Object _error;
AnimationController _animationController;
String _lastTextValue;
Object _activeCallbackIdentity;
@override
void initState() {
super.initState();
this._animationController = AnimationController(
vsync: this,
duration: widget.animationDuration,
);
this._isLoading = false;
this._lastTextValue = widget.controller.text;
// If we started with some text, get suggestions immediately
if (widget.controller.text.isNotEmpty || widget.getImmediateSuggestions) {
this._getSuggestions();
}
this._controllerListener = () {
// If we came here because of a change in selected text, not because of
// actual change in text
if (widget.controller.text == this._lastTextValue) return;
this._lastTextValue = widget.controller.text;
this._debounceTimer = Timer(widget.debounceDuration, () async {
if (this._debounceTimer.isActive) return;
// If already closed
if (!this.mounted) return;
await this._getSuggestions();
});
};
widget.controller.addListener(this._controllerListener);
}
Future<void> _getSuggestions() async {
setState(() {
this._animationController.forward(from: 1.0);
this._isLoading = true;
this._error = null;
});
var suggestions = [];
Object error;
final Object callbackIdentity = Object();
this._activeCallbackIdentity = callbackIdentity;
try {
suggestions = await widget.suggestionsCallback(widget.controller.text);
} catch (e) {
error = e;
}
// If another callback has been issued, omit this one
if (this._activeCallbackIdentity != callbackIdentity) return;
if (this.mounted) {
// if it wasn't removed in the meantime
setState(() {
double animationStart = widget.animationStart;
if (error != null || suggestions.length == 0) {
animationStart = 1.0;
}
this._animationController.forward(from: animationStart);
this._error = error;
this._isLoading = false;
this._suggestions = suggestions;
});
}
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
widget.controller.removeListener(this._controllerListener);
}
@override
Widget build(BuildContext context) {
if (this._suggestions == null && this._isLoading == false)
return Container();
Widget child;
if (this._isLoading) {
child = widget.loadingBuilder != null
? widget.loadingBuilder(context)
: Align(
alignment: Alignment.center,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: CircularProgressIndicator(),
),
);
} else if (this._error != null) {
child = widget.errorBuilder != null
? widget.errorBuilder(context, this._error)
: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Error: ${this._error}',
style: TextStyle(color: Theme.of(context).errorColor),
),
);
} else if (this._suggestions.length == 0) {
child = widget.noItemsFoundBuilder != null
? widget.noItemsFoundBuilder(context)
: Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: Text(
'No Items Found!',
textAlign: TextAlign.center,
style: TextStyle(
color: Theme.of(context).disabledColor, fontSize: 18.0),
),
);
} else {
child = ListView(
padding: EdgeInsets.zero,
primary: false,
shrinkWrap: true,
reverse: widget.direction == AxisDirection.down
? false
: true, // reverses the list to start at the bottom
children: this._suggestions.map((T suggestion) {
return InkWell(
child: widget.itemBuilder(context, suggestion),
onTap: () {
widget.onSuggestionSelected(suggestion);
},
);
}).toList(),
);
if (widget.decoration.hasScrollbar) {
child = Scrollbar(child: child);
}
}
var animationChild = widget.transitionBuilder != null
? widget.transitionBuilder(context, child, this._animationController)
: SizeTransition(
axisAlignment: -1.0,
sizeFactor: CurvedAnimation(
parent: this._animationController, curve: Curves.fastOutSlowIn),
child: child,
);
BoxConstraints constraints;
if (widget.decoration.constraints == null) {
constraints = BoxConstraints(
maxHeight: widget.suggestionsBoxController.maxHeight,
);
} else {
constraints = widget.decoration.constraints.copyWith(
minHeight: min(widget.decoration.constraints.minHeight,
widget.suggestionsBoxController.maxHeight),
maxHeight: widget.suggestionsBoxController.maxHeight,
);
}
var container = Material(
elevation: widget.decoration.elevation,
color: widget.decoration.color,
shape: widget.decoration.shape,
borderRadius: widget.decoration.borderRadius,
shadowColor: widget.decoration.shadowColor,
child: ConstrainedBox(
constraints: constraints,
child: animationChild,
),
);
return container;
}
}
/// Supply an instance of this class to the [TypeAhead.suggestionsBoxDecoration]
/// property to configure the suggestions box decoration