forked from flutter/flutter
/
search_anchor.dart
1578 lines (1418 loc) · 57.6 KB
/
search_anchor.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
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math' as math;
import 'dart:ui';
import 'package:flutter/widgets.dart';
import 'button_style.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'constants.dart';
import 'divider.dart';
import 'divider_theme.dart';
import 'icon_button.dart';
import 'icons.dart';
import 'ink_well.dart';
import 'input_border.dart';
import 'input_decorator.dart';
import 'material.dart';
import 'material_localizations.dart';
import 'material_state.dart';
import 'search_bar_theme.dart';
import 'search_view_theme.dart';
import 'text_field.dart';
import 'text_theme.dart';
import 'theme.dart';
import 'theme_data.dart';
const int _kOpenViewMilliseconds = 600;
const Duration _kOpenViewDuration = Duration(milliseconds: _kOpenViewMilliseconds);
const Duration _kAnchorFadeDuration = Duration(milliseconds: 150);
const Curve _kViewFadeOnInterval = Interval(0.0, 1/2);
const Curve _kViewIconsFadeOnInterval = Interval(1/6, 2/6);
const Curve _kViewDividerFadeOnInterval = Interval(0.0, 1/6);
const Curve _kViewListFadeOnInterval = Interval(133 / _kOpenViewMilliseconds, 233 / _kOpenViewMilliseconds);
const double _kDisableSearchBarOpacity = 0.38;
/// Signature for a function that creates a [Widget] which is used to open a search view.
///
/// The `controller` callback provided to [SearchAnchor.builder] can be used
/// to open the search view and control the editable field on the view.
typedef SearchAnchorChildBuilder = Widget Function(BuildContext context, SearchController controller);
/// Signature for a function that creates a [Widget] to build the suggestion list
/// based on the input in the search bar.
///
/// The `controller` callback provided to [SearchAnchor.suggestionsBuilder] can be used
/// to close the search view and control the editable field on the view.
typedef SuggestionsBuilder = FutureOr<Iterable<Widget>> Function(BuildContext context, SearchController controller);
/// Signature for a function that creates a [Widget] to layout the suggestion list.
///
/// Parameter `suggestions` is the content list that this function wants to lay out.
typedef ViewBuilder = Widget Function(Iterable<Widget> suggestions);
/// Manages a "search view" route that allows the user to select one of the
/// suggested completions for a search query.
///
/// The search view's route can either be shown by creating a [SearchController]
/// and then calling [SearchController.openView] or by tapping on an anchor.
/// When the anchor is tapped or [SearchController.openView] is called, the search view either
/// grows to a specific size, or grows to fill the entire screen. By default,
/// the search view only shows full screen on mobile platforms. Use [SearchAnchor.isFullScreen]
/// to override the default setting.
///
/// The search view is usually opened by a [SearchBar], an [IconButton] or an [Icon].
/// If [builder] returns an Icon, or any un-tappable widgets, we don't have
/// to explicitly call [SearchController.openView].
///
/// The search view route will be popped if the window size is changed and the
/// search view route is not in full-screen mode. However, if the search view route
/// is in full-screen mode, changing the window size, such as rotating a mobile
/// device from portrait mode to landscape mode, will not close the search view.
///
/// {@tool dartpad}
/// This example shows how to use an IconButton to open a search view in a [SearchAnchor].
/// It also shows how to use [SearchController] to open or close the search view route.
///
/// ** See code in examples/api/lib/material/search_anchor/search_anchor.2.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example shows how to set up a floating (or pinned) AppBar with a
/// [SearchAnchor] for a title.
///
/// ** See code in examples/api/lib/material/search_anchor/search_anchor.1.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example shows how to fetch the search suggestions from a remote API.
///
/// ** See code in examples/api/lib/material/search_anchor/search_anchor.3.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example demonstrates fetching the search suggestions asynchronously and
/// debouncing network calls.
///
/// ** See code in examples/api/lib/material/search_anchor/search_anchor.4.dart **
/// {@end-tool}
///
/// See also:
///
/// * [SearchBar], a widget that defines a search bar.
/// * [SearchBarTheme], a widget that overrides the default configuration of a search bar.
/// * [SearchViewTheme], a widget that overrides the default configuration of a search view.
class SearchAnchor extends StatefulWidget {
/// Creates a const [SearchAnchor].
///
/// The [builder] and [suggestionsBuilder] arguments are required.
const SearchAnchor({
super.key,
this.isFullScreen,
this.searchController,
this.viewBuilder,
this.viewLeading,
this.viewTrailing,
this.viewHintText,
this.viewBackgroundColor,
this.viewElevation,
this.viewSurfaceTintColor,
this.viewSide,
this.viewShape,
this.headerHeight,
this.headerTextStyle,
this.headerHintStyle,
this.dividerColor,
this.viewConstraints,
this.textCapitalization,
this.viewOnChanged,
this.viewOnSubmitted,
required this.builder,
required this.suggestionsBuilder,
this.textInputAction,
this.keyboardType,
});
/// Create a [SearchAnchor] that has a [SearchBar] which opens a search view.
///
/// All the barX parameters are used to customize the anchor. Similarly, all the
/// viewX parameters are used to override the view's defaults.
///
/// {@tool dartpad}
/// This example shows how to use a [SearchAnchor.bar] which uses a default search
/// bar to open a search view route.
///
/// ** See code in examples/api/lib/material/search_anchor/search_anchor.0.dart **
/// {@end-tool}
factory SearchAnchor.bar({
Widget? barLeading,
Iterable<Widget>? barTrailing,
String? barHintText,
GestureTapCallback? onTap,
ValueChanged<String>? onSubmitted,
ValueChanged<String>? onChanged,
MaterialStateProperty<double?>? barElevation,
MaterialStateProperty<Color?>? barBackgroundColor,
MaterialStateProperty<Color?>? barOverlayColor,
MaterialStateProperty<BorderSide?>? barSide,
MaterialStateProperty<OutlinedBorder?>? barShape,
MaterialStateProperty<EdgeInsetsGeometry?>? barPadding,
MaterialStateProperty<TextStyle?>? barTextStyle,
MaterialStateProperty<TextStyle?>? barHintStyle,
Widget? viewLeading,
Iterable<Widget>? viewTrailing,
String? viewHintText,
Color? viewBackgroundColor,
double? viewElevation,
BorderSide? viewSide,
OutlinedBorder? viewShape,
double? viewHeaderHeight,
TextStyle? viewHeaderTextStyle,
TextStyle? viewHeaderHintStyle,
Color? dividerColor,
BoxConstraints? constraints,
BoxConstraints? viewConstraints,
bool? isFullScreen,
SearchController searchController,
TextCapitalization textCapitalization,
required SuggestionsBuilder suggestionsBuilder,
TextInputAction? textInputAction,
TextInputType? keyboardType,
}) = _SearchAnchorWithSearchBar;
/// Whether the search view grows to fill the entire screen when the
/// [SearchAnchor] is tapped.
///
/// By default, the search view is full-screen on mobile devices. On other
/// platforms, the search view only grows to a specific size that is determined
/// by the anchor and the default size.
final bool? isFullScreen;
/// An optional controller that allows opening and closing of the search view from
/// other widgets.
///
/// If this is null, one internal search controller is created automatically
/// and it is used to open the search view when the user taps on the anchor.
final SearchController? searchController;
/// Optional callback to obtain a widget to lay out the suggestion list of the
/// search view.
///
/// Default view uses a [ListView] with a vertical scroll direction.
final ViewBuilder? viewBuilder;
/// An optional widget to display before the text input field when the search
/// view is open.
///
/// Typically the [viewLeading] widget is an [Icon] or an [IconButton].
///
/// Defaults to a back button which pops the view.
final Widget? viewLeading;
/// An optional widget list to display after the text input field when the search
/// view is open.
///
/// Typically the [viewTrailing] widget list only has one or two widgets.
///
/// Defaults to an icon button which clears the text in the input field.
final Iterable<Widget>? viewTrailing;
/// Text that is displayed when the search bar's input field is empty.
final String? viewHintText;
/// The search view's background fill color.
///
/// If null, the value of [SearchViewThemeData.backgroundColor] will be used.
/// If this is also null, then the default value is [ColorScheme.surfaceContainerHigh].
final Color? viewBackgroundColor;
/// The elevation of the search view's [Material].
///
/// If null, the value of [SearchViewThemeData.elevation] will be used. If this
/// is also null, then default value is 6.0.
final double? viewElevation;
/// The surface tint color of the search view's [Material].
///
/// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles)
/// introduced a set of tone-based surfaces and surface containers in its [ColorScheme],
/// which provide more flexibility. The intention is to eventually remove surface tint color from
/// the framework.
///
/// If null, the value of [SearchViewThemeData.surfaceTintColor] will be used.
/// If this is also null, then the default value is [ColorScheme.surfaceTint].
final Color? viewSurfaceTintColor;
/// The color and weight of the search view's outline.
///
/// This value is combined with [viewShape] to create a shape decorated
/// with an outline. This will be ignored if the view is full-screen.
///
/// If null, the value of [SearchViewThemeData.side] will be used. If this is
/// also null, the search view doesn't have a side by default.
final BorderSide? viewSide;
/// The shape of the search view's underlying [Material].
///
/// This shape is combined with [viewSide] to create a shape decorated
/// with an outline.
///
/// If null, the value of [SearchViewThemeData.shape] will be used.
/// If this is also null, then the default value is a rectangle shape for full-screen
/// mode and a [RoundedRectangleBorder] shape with a 28.0 radius otherwise.
final OutlinedBorder? viewShape;
/// The height of the search field on the search view.
///
/// If null, the value of [SearchViewThemeData.headerHeight] will be used. If
/// this is also null, the default value is 56.0.
final double? headerHeight;
/// The style to use for the text being edited on the search view.
///
/// If null, defaults to the `bodyLarge` text style from the current [Theme].
/// The default text color is [ColorScheme.onSurface].
final TextStyle? headerTextStyle;
/// The style to use for the [viewHintText] on the search view.
///
/// If null, the value of [SearchViewThemeData.headerHintStyle] will be used.
/// If this is also null, the value of [headerTextStyle] will be used. If this is also null,
/// defaults to the `bodyLarge` text style from the current [Theme]. The default
/// text color is [ColorScheme.onSurfaceVariant].
final TextStyle? headerHintStyle;
/// The color of the divider on the search view.
///
/// If this property is null, then [SearchViewThemeData.dividerColor] is used.
/// If that is also null, the default value is [ColorScheme.outline].
final Color? dividerColor;
/// Optional size constraints for the search view.
///
/// By default, the search view has the same width as the anchor and is 2/3
/// the height of the screen. If the width and height of the view are within
/// the [viewConstraints], the view will show its default size. Otherwise,
/// the size of the view will be constrained by this property.
///
/// If null, the value of [SearchViewThemeData.constraints] will be used. If
/// this is also null, then the constraints defaults to:
/// ```dart
/// const BoxConstraints(minWidth: 360.0, minHeight: 240.0)
/// ```
final BoxConstraints? viewConstraints;
/// {@macro flutter.widgets.editableText.textCapitalization}
final TextCapitalization? textCapitalization;
/// Called each time the user modifies the search view's text field.
///
/// See also:
///
/// * [viewOnSubmitted], which is called when the user indicates that they
/// are done editing the search view's text field.
final ValueChanged<String>? viewOnChanged;
/// Called when the user indicates that they are done editing the text in the
/// text field of a search view. Typically this is called when the user presses
/// the enter key.
///
/// See also:
///
/// * [viewOnChanged], which is called when the user modifies the text field
/// of the search view.
final ValueChanged<String>? viewOnSubmitted;
/// Called to create a widget which can open a search view route when it is tapped.
///
/// The widget returned by this builder is faded out when it is tapped.
/// At the same time a search view route is faded in.
final SearchAnchorChildBuilder builder;
/// Called to get the suggestion list for the search view.
///
/// By default, the list returned by this builder is laid out in a [ListView].
/// To get a different layout, use [viewBuilder] to override.
final SuggestionsBuilder suggestionsBuilder;
/// {@macro flutter.widgets.TextField.textInputAction}
final TextInputAction? textInputAction;
/// The type of action button to use for the keyboard.
///
/// Defaults to the default value specified in [TextField].
final TextInputType? keyboardType;
@override
State<SearchAnchor> createState() => _SearchAnchorState();
}
class _SearchAnchorState extends State<SearchAnchor> {
Size? _screenSize;
bool _anchorIsVisible = true;
final GlobalKey _anchorKey = GlobalKey();
bool get _viewIsOpen => !_anchorIsVisible;
SearchController? _internalSearchController;
SearchController get _searchController => widget.searchController ?? (_internalSearchController ??= SearchController());
@override
void initState() {
super.initState();
_searchController._attach(this);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final Size updatedScreenSize = MediaQuery.of(context).size;
if (_screenSize != null && _screenSize != updatedScreenSize) {
if (_searchController.isOpen && !getShowFullScreenView()) {
_closeView(null);
}
}
_screenSize = updatedScreenSize;
}
@override
void didUpdateWidget(SearchAnchor oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.searchController != widget.searchController) {
oldWidget.searchController?._detach(this);
_searchController._attach(this);
}
}
@override
void dispose() {
super.dispose();
widget.searchController?._detach(this);
_internalSearchController?._detach(this);
_internalSearchController?.dispose();
}
void _openView() {
final NavigatorState navigator = Navigator.of(context);
navigator.push(_SearchViewRoute(
viewOnChanged: widget.viewOnChanged,
viewOnSubmitted: widget.viewOnSubmitted,
viewLeading: widget.viewLeading,
viewTrailing: widget.viewTrailing,
viewHintText: widget.viewHintText,
viewBackgroundColor: widget.viewBackgroundColor,
viewElevation: widget.viewElevation,
viewSurfaceTintColor: widget.viewSurfaceTintColor,
viewSide: widget.viewSide,
viewShape: widget.viewShape,
viewHeaderHeight: widget.headerHeight,
viewHeaderTextStyle: widget.headerTextStyle,
viewHeaderHintStyle: widget.headerHintStyle,
dividerColor: widget.dividerColor,
viewConstraints: widget.viewConstraints,
showFullScreenView: getShowFullScreenView(),
toggleVisibility: toggleVisibility,
textDirection: Directionality.of(context),
viewBuilder: widget.viewBuilder,
anchorKey: _anchorKey,
searchController: _searchController,
suggestionsBuilder: widget.suggestionsBuilder,
textCapitalization: widget.textCapitalization,
capturedThemes: InheritedTheme.capture(from: context, to: navigator.context),
textInputAction: widget.textInputAction,
keyboardType: widget.keyboardType,
));
}
void _closeView(String? selectedText) {
if (selectedText != null) {
_searchController.text = selectedText;
}
Navigator.of(context).pop();
}
bool toggleVisibility() {
setState(() {
_anchorIsVisible = !_anchorIsVisible;
});
return _anchorIsVisible;
}
bool getShowFullScreenView() {
return widget.isFullScreen ?? switch (Theme.of(context).platform) {
TargetPlatform.iOS || TargetPlatform.android || TargetPlatform.fuchsia => true,
TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => false,
};
}
@override
Widget build(BuildContext context) {
return AnimatedOpacity(
key: _anchorKey,
opacity: _anchorIsVisible ? 1.0 : 0.0,
duration: _kAnchorFadeDuration,
child: GestureDetector(
onTap: _openView,
child: widget.builder(context, _searchController),
),
);
}
}
class _SearchViewRoute extends PopupRoute<_SearchViewRoute> {
_SearchViewRoute({
this.viewOnChanged,
this.viewOnSubmitted,
this.toggleVisibility,
this.textDirection,
this.viewBuilder,
this.viewLeading,
this.viewTrailing,
this.viewHintText,
this.viewBackgroundColor,
this.viewElevation,
this.viewSurfaceTintColor,
this.viewSide,
this.viewShape,
this.viewHeaderHeight,
this.viewHeaderTextStyle,
this.viewHeaderHintStyle,
this.dividerColor,
this.viewConstraints,
this.textCapitalization,
required this.showFullScreenView,
required this.anchorKey,
required this.searchController,
required this.suggestionsBuilder,
required this.capturedThemes,
this.textInputAction,
this.keyboardType,
});
final ValueChanged<String>? viewOnChanged;
final ValueChanged<String>? viewOnSubmitted;
final ValueGetter<bool>? toggleVisibility;
final TextDirection? textDirection;
final ViewBuilder? viewBuilder;
final Widget? viewLeading;
final Iterable<Widget>? viewTrailing;
final String? viewHintText;
final Color? viewBackgroundColor;
final double? viewElevation;
final Color? viewSurfaceTintColor;
final BorderSide? viewSide;
final OutlinedBorder? viewShape;
final double? viewHeaderHeight;
final TextStyle? viewHeaderTextStyle;
final TextStyle? viewHeaderHintStyle;
final Color? dividerColor;
final BoxConstraints? viewConstraints;
final TextCapitalization? textCapitalization;
final bool showFullScreenView;
final GlobalKey anchorKey;
final SearchController searchController;
final SuggestionsBuilder suggestionsBuilder;
final CapturedThemes capturedThemes;
final TextInputAction? textInputAction;
final TextInputType? keyboardType;
@override
Color? get barrierColor => Colors.transparent;
@override
bool get barrierDismissible => true;
@override
String? get barrierLabel => 'Dismiss';
late final SearchViewThemeData viewDefaults;
late final SearchViewThemeData viewTheme;
final RectTween _rectTween = RectTween();
Rect? getRect() {
final BuildContext? context = anchorKey.currentContext;
if (context != null) {
final RenderBox searchBarBox = context.findRenderObject()! as RenderBox;
final Size boxSize = searchBarBox.size;
final NavigatorState navigator = Navigator.of(context);
final Offset boxLocation = searchBarBox.localToGlobal(Offset.zero, ancestor: navigator.context.findRenderObject());
return boxLocation & boxSize;
}
return null;
}
@override
TickerFuture didPush() {
assert(anchorKey.currentContext != null);
updateViewConfig(anchorKey.currentContext!);
updateTweens(anchorKey.currentContext!);
toggleVisibility?.call();
return super.didPush();
}
@override
bool didPop(_SearchViewRoute? result) {
assert(anchorKey.currentContext != null);
updateTweens(anchorKey.currentContext!);
toggleVisibility?.call();
return super.didPop(result);
}
void updateViewConfig(BuildContext context) {
viewDefaults = _SearchViewDefaultsM3(context, isFullScreen: showFullScreenView);
viewTheme = SearchViewTheme.of(context);
}
void updateTweens(BuildContext context) {
final RenderBox navigator = Navigator.of(context).context.findRenderObject()! as RenderBox;
final Size screenSize = navigator.size;
final Rect anchorRect = getRect() ?? Rect.zero;
final BoxConstraints effectiveConstraints = viewConstraints ?? viewTheme.constraints ?? viewDefaults.constraints!;
_rectTween.begin = anchorRect;
final double viewWidth = clampDouble(anchorRect.width, effectiveConstraints.minWidth, effectiveConstraints.maxWidth);
final double viewHeight = clampDouble(screenSize.height * 2 / 3, effectiveConstraints.minHeight, effectiveConstraints.maxHeight);
switch (textDirection ?? TextDirection.ltr) {
case TextDirection.ltr:
final double viewLeftToScreenRight = screenSize.width - anchorRect.left;
final double viewTopToScreenBottom = screenSize.height - anchorRect.top;
// Make sure the search view doesn't go off the screen. If the search view
// doesn't fit, move the top-left corner of the view to fit the window.
// If the window is smaller than the view, then we resize the view to fit the window.
Offset topLeft = anchorRect.topLeft;
if (viewLeftToScreenRight < viewWidth) {
topLeft = Offset(screenSize.width - math.min(viewWidth, screenSize.width), topLeft.dy);
}
if (viewTopToScreenBottom < viewHeight) {
topLeft = Offset(topLeft.dx, screenSize.height - math.min(viewHeight, screenSize.height));
}
final Size endSize = Size(viewWidth, viewHeight);
_rectTween.end = showFullScreenView ? Offset.zero & screenSize : (topLeft & endSize);
return;
case TextDirection.rtl:
final double viewRightToScreenLeft = anchorRect.right;
final double viewTopToScreenBottom = screenSize.height - anchorRect.top;
// Make sure the search view doesn't go off the screen.
Offset topLeft = Offset(math.max(anchorRect.right - viewWidth, 0.0), anchorRect.top);
if (viewRightToScreenLeft < viewWidth) {
topLeft = Offset(0.0, topLeft.dy);
}
if (viewTopToScreenBottom < viewHeight) {
topLeft = Offset(topLeft.dx, screenSize.height - math.min(viewHeight, screenSize.height));
}
final Size endSize = Size(viewWidth, viewHeight);
_rectTween.end = showFullScreenView ? Offset.zero & screenSize : (topLeft & endSize);
}
}
@override
Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
return Directionality(
textDirection: textDirection ?? TextDirection.ltr,
child: AnimatedBuilder(
animation: animation,
builder: (BuildContext context, Widget? child) {
final Animation<double> curvedAnimation = CurvedAnimation(
parent: animation,
curve: Curves.easeInOutCubicEmphasized,
reverseCurve: Curves.easeInOutCubicEmphasized.flipped,
);
final Rect viewRect = _rectTween.evaluate(curvedAnimation)!;
final double topPadding = showFullScreenView
? lerpDouble(0.0, MediaQuery.paddingOf(context).top, curvedAnimation.value)!
: 0.0;
return FadeTransition(
opacity: CurvedAnimation(
parent: animation,
curve: _kViewFadeOnInterval,
reverseCurve: _kViewFadeOnInterval.flipped,
),
child: capturedThemes.wrap(
_ViewContent(
viewOnChanged: viewOnChanged,
viewOnSubmitted: viewOnSubmitted,
viewLeading: viewLeading,
viewTrailing: viewTrailing,
viewHintText: viewHintText,
viewBackgroundColor: viewBackgroundColor,
viewElevation: viewElevation,
viewSurfaceTintColor: viewSurfaceTintColor,
viewSide: viewSide,
viewShape: viewShape,
viewHeaderHeight: viewHeaderHeight,
viewHeaderTextStyle: viewHeaderTextStyle,
viewHeaderHintStyle: viewHeaderHintStyle,
dividerColor: dividerColor,
showFullScreenView: showFullScreenView,
animation: curvedAnimation,
topPadding: topPadding,
viewMaxWidth: _rectTween.end!.width,
viewRect: viewRect,
viewBuilder: viewBuilder,
searchController: searchController,
suggestionsBuilder: suggestionsBuilder,
textCapitalization: textCapitalization,
textInputAction: textInputAction,
keyboardType: keyboardType,
),
),
);
}
),
);
}
@override
Duration get transitionDuration => _kOpenViewDuration;
}
class _ViewContent extends StatefulWidget {
const _ViewContent({
this.viewOnChanged,
this.viewOnSubmitted,
this.viewBuilder,
this.viewLeading,
this.viewTrailing,
this.viewHintText,
this.viewBackgroundColor,
this.viewElevation,
this.viewSurfaceTintColor,
this.viewSide,
this.viewShape,
this.viewHeaderHeight,
this.viewHeaderTextStyle,
this.viewHeaderHintStyle,
this.dividerColor,
this.textCapitalization,
required this.showFullScreenView,
required this.topPadding,
required this.animation,
required this.viewMaxWidth,
required this.viewRect,
required this.searchController,
required this.suggestionsBuilder,
this.textInputAction,
this.keyboardType,
});
final ValueChanged<String>? viewOnChanged;
final ValueChanged<String>? viewOnSubmitted;
final ViewBuilder? viewBuilder;
final Widget? viewLeading;
final Iterable<Widget>? viewTrailing;
final String? viewHintText;
final Color? viewBackgroundColor;
final double? viewElevation;
final Color? viewSurfaceTintColor;
final BorderSide? viewSide;
final OutlinedBorder? viewShape;
final double? viewHeaderHeight;
final TextStyle? viewHeaderTextStyle;
final TextStyle? viewHeaderHintStyle;
final Color? dividerColor;
final TextCapitalization? textCapitalization;
final bool showFullScreenView;
final double topPadding;
final Animation<double> animation;
final double viewMaxWidth;
final Rect viewRect;
final SearchController searchController;
final SuggestionsBuilder suggestionsBuilder;
final TextInputAction? textInputAction;
final TextInputType? keyboardType;
@override
State<_ViewContent> createState() => _ViewContentState();
}
class _ViewContentState extends State<_ViewContent> {
Size? _screenSize;
late Rect _viewRect;
late final SearchController _controller;
Iterable<Widget> result = <Widget>[];
String? searchValue;
Timer? _timer;
@override
void initState() {
super.initState();
_viewRect = widget.viewRect;
_controller = widget.searchController;
_controller.addListener(updateSuggestions);
}
@override
void didUpdateWidget(covariant _ViewContent oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.viewRect != oldWidget.viewRect) {
setState(() {
_viewRect = widget.viewRect;
});
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final Size updatedScreenSize = MediaQuery.of(context).size;
if (_screenSize != updatedScreenSize) {
_screenSize = updatedScreenSize;
if (widget.showFullScreenView) {
_viewRect = Offset.zero & _screenSize!;
}
}
if (searchValue != _controller.text) {
_timer?.cancel();
_timer = Timer(Duration.zero, () async {
searchValue = _controller.text;
result = await widget.suggestionsBuilder(context, _controller);
_timer?.cancel();
_timer = null;
});
}
}
@override
void dispose() {
_controller.removeListener(updateSuggestions);
_timer?.cancel();
_timer = null;
super.dispose();
}
Widget viewBuilder(Iterable<Widget> suggestions) {
if (widget.viewBuilder == null) {
return MediaQuery.removePadding(
context: context,
removeTop: true,
child: ListView(
children: suggestions.toList()
),
);
}
return widget.viewBuilder!(suggestions);
}
Future<void> updateSuggestions() async {
if (searchValue != _controller.text) {
searchValue = _controller.text;
final Iterable<Widget> suggestions = await widget.suggestionsBuilder(context, _controller);
if (mounted) {
setState(() {
result = suggestions;
});
}
}
}
@override
Widget build(BuildContext context) {
final Widget defaultLeading = IconButton(
icon: const Icon(Icons.arrow_back),
tooltip: MaterialLocalizations.of(context).backButtonTooltip,
onPressed: () { Navigator.of(context).pop(); },
style: const ButtonStyle(tapTargetSize: MaterialTapTargetSize.shrinkWrap),
);
final List<Widget> defaultTrailing = <Widget>[
if (_controller.text.isNotEmpty) IconButton(
icon: const Icon(Icons.close),
tooltip: MaterialLocalizations.of(context).clearButtonTooltip,
onPressed: () {
_controller.clear();
},
),
];
final SearchViewThemeData viewDefaults = _SearchViewDefaultsM3(context, isFullScreen: widget.showFullScreenView);
final SearchViewThemeData viewTheme = SearchViewTheme.of(context);
final DividerThemeData dividerTheme = DividerTheme.of(context);
final Color effectiveBackgroundColor = widget.viewBackgroundColor
?? viewTheme.backgroundColor
?? viewDefaults.backgroundColor!;
final Color effectiveSurfaceTint = widget.viewSurfaceTintColor
?? viewTheme.surfaceTintColor
?? viewDefaults.surfaceTintColor!;
final double effectiveElevation = widget.viewElevation
?? viewTheme.elevation
?? viewDefaults.elevation!;
final BorderSide? effectiveSide = widget.viewSide
?? viewTheme.side
?? viewDefaults.side;
OutlinedBorder effectiveShape = widget.viewShape
?? viewTheme.shape
?? viewDefaults.shape!;
if (effectiveSide != null) {
effectiveShape = effectiveShape.copyWith(side: effectiveSide);
}
final Color effectiveDividerColor = widget.dividerColor
?? viewTheme.dividerColor
?? dividerTheme.color
?? viewDefaults.dividerColor!;
final double? effectiveHeaderHeight = widget.viewHeaderHeight ?? viewTheme.headerHeight;
final BoxConstraints? headerConstraints = effectiveHeaderHeight == null
? null
: BoxConstraints.tightFor(height: effectiveHeaderHeight);
final TextStyle? effectiveTextStyle = widget.viewHeaderTextStyle
?? viewTheme.headerTextStyle
?? viewDefaults.headerTextStyle;
final TextStyle? effectiveHintStyle = widget.viewHeaderHintStyle
?? viewTheme.headerHintStyle
?? widget.viewHeaderTextStyle
?? viewTheme.headerTextStyle
?? viewDefaults.headerHintStyle;
final Widget viewDivider = DividerTheme(
data: dividerTheme.copyWith(color: effectiveDividerColor),
child: const Divider(height: 1),
);
return Align(
alignment: Alignment.topLeft,
child: Transform.translate(
offset: _viewRect.topLeft,
child: SizedBox(
width: _viewRect.width,
height: _viewRect.height,
child: Material(
clipBehavior: Clip.antiAlias,
shape: effectiveShape,
color: effectiveBackgroundColor,
surfaceTintColor: effectiveSurfaceTint,
elevation: effectiveElevation,
child: ClipRect(
clipBehavior: Clip.antiAlias,
child: OverflowBox(
alignment: Alignment.topLeft,
maxWidth: math.min(widget.viewMaxWidth, _screenSize!.width),
minWidth: 0,
child: FadeTransition(
opacity: CurvedAnimation(
parent: widget.animation,
curve: _kViewIconsFadeOnInterval,
reverseCurve: _kViewIconsFadeOnInterval.flipped,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: widget.topPadding),
child: SafeArea(
top: false,
bottom: false,
child: SearchBar(
autoFocus: true,
constraints: headerConstraints ?? (widget.showFullScreenView ? BoxConstraints(minHeight: _SearchViewDefaultsM3.fullScreenBarHeight) : null),
leading: widget.viewLeading ?? defaultLeading,
trailing: widget.viewTrailing ?? defaultTrailing,
hintText: widget.viewHintText,
backgroundColor: const MaterialStatePropertyAll<Color>(Colors.transparent),
overlayColor: const MaterialStatePropertyAll<Color>(Colors.transparent),
elevation: const MaterialStatePropertyAll<double>(0.0),
textStyle: MaterialStatePropertyAll<TextStyle?>(effectiveTextStyle),
hintStyle: MaterialStatePropertyAll<TextStyle?>(effectiveHintStyle),
controller: _controller,
onChanged: (String value) {
widget.viewOnChanged?.call(value);
updateSuggestions();
},
onSubmitted: widget.viewOnSubmitted,
textCapitalization: widget.textCapitalization,
textInputAction: widget.textInputAction,
keyboardType: widget.keyboardType,
),
),
),
FadeTransition(
opacity: CurvedAnimation(
parent: widget.animation,
curve: _kViewDividerFadeOnInterval,
reverseCurve: _kViewFadeOnInterval.flipped,
),
child: viewDivider),
Expanded(
child: FadeTransition(
opacity: CurvedAnimation(
parent: widget.animation,
curve: _kViewListFadeOnInterval,
reverseCurve: _kViewListFadeOnInterval.flipped,
),
child: viewBuilder(result),
),
),
],
),
),
),
),
),
),
),
);
}
}
class _SearchAnchorWithSearchBar extends SearchAnchor {
_SearchAnchorWithSearchBar({
Widget? barLeading,
Iterable<Widget>? barTrailing,
String? barHintText,
GestureTapCallback? onTap,
MaterialStateProperty<double?>? barElevation,
MaterialStateProperty<Color?>? barBackgroundColor,
MaterialStateProperty<Color?>? barOverlayColor,
MaterialStateProperty<BorderSide?>? barSide,
MaterialStateProperty<OutlinedBorder?>? barShape,
MaterialStateProperty<EdgeInsetsGeometry?>? barPadding,
MaterialStateProperty<TextStyle?>? barTextStyle,
MaterialStateProperty<TextStyle?>? barHintStyle,
super.viewLeading,
super.viewTrailing,
String? viewHintText,
super.viewBackgroundColor,
super.viewElevation,
super.viewSide,
super.viewShape,
double? viewHeaderHeight,
TextStyle? viewHeaderTextStyle,
TextStyle? viewHeaderHintStyle,
super.dividerColor,
BoxConstraints? constraints,
super.viewConstraints,
super.isFullScreen,
super.searchController,
super.textCapitalization,
ValueChanged<String>? onChanged,
ValueChanged<String>? onSubmitted,
required super.suggestionsBuilder,