-
Notifications
You must be signed in to change notification settings - Fork 42
/
flexible_bottom_sheet.dart
561 lines (517 loc) · 18.6 KB
/
flexible_bottom_sheet.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
// Copyright (c) 2019-present, SurfStudio LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:bottom_sheet/src/flexible_bottom_sheet_header_delegate.dart';
import 'package:bottom_sheet/src/widgets/change_insets_detector.dart';
import 'package:bottom_sheet/src/widgets/scroll_behavior_in_web.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
/// The signature of a method that provides a [BuildContext] and
/// [ScrollController] for building a widget that may overflow the draggable
/// [Axis] of the containing FlexibleDraggableScrollSheet.
///
/// Users should apply the [scrollController] to a [ScrollView] subclass, such
/// as a [SingleChildScrollView], [ListView] or [GridView], to have the whole
/// sheet be draggable.
///
/// [bottomSheetOffset] - fractional value of offset.
typedef FlexibleDraggableScrollableWidgetBuilder = Widget Function(
BuildContext context,
ScrollController scrollController,
double bottomSheetOffset,
);
/// The signature of the method that provides [BuildContext]
/// and [bottomSheetOffset] for determining the position of the BottomSheet
/// relative to the upper border of the screen.
/// [bottomSheetOffset] - fractional value of offset.
typedef FlexibleDraggableScrollableHeaderWidgetBuilder = Widget Function(
BuildContext context,
double bottomSheetOffset,
);
/// The signature of a method that provides a [BuildContext]
/// and [bottomSheetOffset] for determining the position of the BottomSheet
/// relative to the upper border of the screen.
/// [bottomSheetOffset] - fractional value of offset.
typedef FlexibleDraggableScrollableWidgetBodyBuilder = SliverChildDelegate
Function(
BuildContext context,
double bottomSheetOffset,
);
/// Flexible and scrollable bottom sheet.
///
/// This bottom sheet resizing between min and max size, and when size become
/// max start scrolling content. Reduction size available when content
/// scrolled to 0 offset.
///
/// [minHeight], [maxHeight] are limits of
/// bounds this widget. For example:
/// - you can set [maxHeight] to 1;
/// - you can set [minHeight] to 0.5;
///
/// [isCollapsible] make possible collapse widget and remove from the screen,
/// but you must be carefully to use it, set it to true only if you show this
/// widget with like showFlexibleBottomSheet() case, because it will be removed
/// by Navigator.pop(). If you set [isCollapsible] true, [minHeight]
/// must be 0.
///
/// The [draggableScrollableController] that allow programmatically control bottom sheet.
///
/// The [animationController] that controls the bottom sheet's entrance and
/// exit animations.
/// The FlexibleBottomSheet widget will manipulate the position of this
/// animation, it is not just a passive observer.
///
/// [initHeight] - relevant height for init bottom sheet
///
/// [keyboardBarrierColor] - color for the space behind the keyboard
///
/// [isExpand] - should your bottom sheet expand. By default, [isExpand] is true,
/// which means that the bottom sheet will have the height you specify
/// ([initHeight] and [maxHeight]) regardless of the height of the content in it.
/// If [isExpand] is false, [maxHeight] and [initHeight] must be equal,
/// in which case the bottom sheet will calculate its height based on the content,
/// but no more than [maxHeight] and [initHeight]. [anchors] in this case must be null.
/// ShrinkWrap content widget must be true.
///
/// [bottomSheetColor] - bottom sheet color. If you want to make rounded edges,
/// pass a [Colors.transparent] here, and set the color and border radius of
/// the bottom sheet in the [decoration].
class FlexibleBottomSheet<T> extends StatefulWidget {
final double minHeight;
final double initHeight;
final double maxHeight;
final FlexibleDraggableScrollableWidgetBuilder? builder;
final FlexibleDraggableScrollableHeaderWidgetBuilder? headerBuilder;
final FlexibleDraggableScrollableWidgetBodyBuilder? bodyBuilder;
final bool isCollapsible;
final bool isExpand;
final DraggableScrollableController? draggableScrollableController;
final AnimationController? animationController;
final List<double>? anchors;
final double? minHeaderHeight;
final double? maxHeaderHeight;
final Decoration? decoration;
final VoidCallback? onDismiss;
final Color? keyboardBarrierColor;
final Color? bottomSheetColor;
final PopupRoute<T>? route;
final bool useRootScaffold;
final BorderRadiusGeometry? bottomSheetBorderRadius;
FlexibleBottomSheet({
super.key,
this.route,
this.minHeight = 0,
this.initHeight = 0.5,
this.maxHeight = 1,
this.builder,
this.headerBuilder,
this.bodyBuilder,
this.isCollapsible = false,
this.isExpand = true,
this.animationController,
this.anchors,
this.minHeaderHeight,
this.maxHeaderHeight,
this.decoration,
this.onDismiss,
this.keyboardBarrierColor,
this.bottomSheetColor,
this.bottomSheetBorderRadius,
this.draggableScrollableController,
this.useRootScaffold = true,
}) : assert(minHeight >= 0 && minHeight <= 1),
assert(maxHeight > 0 && maxHeight <= 1),
assert(maxHeight > minHeight),
assert(!isCollapsible || minHeight == 0),
assert(anchors == null || !anchors.any((anchor) => anchor > maxHeight)),
assert(anchors == null || !anchors.any((anchor) => anchor < minHeight)),
assert(isExpand || maxHeight == initHeight && anchors == null);
FlexibleBottomSheet.collapsible({
required PopupRoute<T> route,
Key? key,
double initHeight = 0.5,
double maxHeight = 1,
DraggableScrollableController? draggableScrollableController,
FlexibleDraggableScrollableWidgetBuilder? builder,
FlexibleDraggableScrollableHeaderWidgetBuilder? headerBuilder,
FlexibleDraggableScrollableWidgetBodyBuilder? bodyBuilder,
bool isExpand = true,
AnimationController? animationController,
List<double>? anchors,
double? minHeaderHeight,
double? maxHeaderHeight,
Decoration? decoration,
Color? keyboardBarrierColor,
Color? bottomSheetColor,
bool useRootScaffold = true,
BorderRadiusGeometry? bottomSheetBorderRadius,
}) : this(
route: route,
key: key,
maxHeight: maxHeight,
draggableScrollableController: draggableScrollableController,
builder: builder,
headerBuilder: headerBuilder,
bodyBuilder: bodyBuilder,
minHeight: 0,
initHeight: initHeight,
isCollapsible: true,
isExpand: isExpand,
animationController: animationController,
anchors: anchors,
minHeaderHeight: minHeaderHeight,
maxHeaderHeight: maxHeaderHeight,
decoration: decoration,
keyboardBarrierColor: keyboardBarrierColor,
bottomSheetColor: bottomSheetColor,
useRootScaffold: useRootScaffold,
bottomSheetBorderRadius: bottomSheetBorderRadius,
);
@override
State<FlexibleBottomSheet<T>> createState() => _FlexibleBottomSheetState();
}
class _FlexibleBottomSheetState<T> extends State<FlexibleBottomSheet<T>> {
late final DraggableScrollableController _controller;
late final WidgetsBinding _widgetBinding;
late double _initialChildSize = widget.initHeight;
late double _currentMaxChildSize = widget.maxHeight;
bool _isClosing = false;
bool _isAnimatingToMaxHeight = false;
final double _sizeWhenNeedClose = kIsWeb ? 0.10 : 0.01;
@override
void initState() {
super.initState();
_controller =
widget.draggableScrollableController ?? DraggableScrollableController();
_widgetBinding = WidgetsBinding.instance;
widget.animationController?.addStatusListener(_animationStatusListener);
}
// Method will be called when scrolling.
bool _scrolling(DraggableScrollableNotification notification) {
/// Force widget rebuild to change bottomSheetOffset value
setState(() {});
if (_isClosing) return false;
_initialChildSize = notification.extent;
_checkNeedCloseBottomSheet(notification.extent);
return false;
}
// Make bottom sheet max height.
void _animateToMaxHeight() {
final currPosition = _controller.size;
if (currPosition != widget.maxHeight && !_isAnimatingToMaxHeight) {
_isAnimatingToMaxHeight = true;
_controller
.animateTo(
widget.maxHeight,
duration: const Duration(milliseconds: 200),
curve: Curves.ease,
)
.whenComplete(
() => _isAnimatingToMaxHeight = false,
);
}
}
// Scroll to focused widget.
void _animateToFocused(ScrollController controller) {
if (FocusManager.instance.primaryFocus == null || _isClosing) return;
_widgetBinding.addPostFrameCallback((_) {
final keyboardHeight = MediaQuery.viewInsetsOf(context).bottom;
final widgetHeight = FocusManager.instance.primaryFocus!.size.height;
final widgetOffset = FocusManager.instance.primaryFocus!.offset.dy;
final screenHeight = MediaQuery.sizeOf(context).height;
final targetWidgetOffset =
screenHeight - keyboardHeight - widgetHeight - 20;
final valueToScroll = widgetOffset - targetWidgetOffset;
final currentOffset = controller.offset;
if (valueToScroll > 0) {
controller.animateTo(
currentOffset + valueToScroll,
duration: const Duration(milliseconds: 200),
curve: Curves.ease,
);
}
});
}
// Checking if the bottom sheet needs to be closed.
void _checkNeedCloseBottomSheet(double extent) {
if (widget.isCollapsible && !_isClosing) {
if (extent - widget.minHeight <= _sizeWhenNeedClose) {
_isClosing = true;
_dismiss();
}
}
}
// Method that listens for changing AnimationStatus, to track the closing of
// the bottom sheet by clicking above it.
void _animationStatusListener(AnimationStatus status) {
if (status == AnimationStatus.reverse ||
status == AnimationStatus.dismissed) {
_isClosing = true;
}
}
void _dismiss() {
if (widget.isCollapsible) {
widget.onDismiss?.call();
Navigator.maybePop(context);
WidgetsBinding.instance
.addPostFrameCallback((_) => widget.route?.changedInternalState());
}
}
void _changeInitAndMaxHeight(double height) {
if (!widget.isExpand) {
final screenHeight = MediaQuery.sizeOf(context).height;
final fractionalValue = height / screenHeight;
if (fractionalValue < _currentMaxChildSize) {
setState(
() {
_initialChildSize = fractionalValue;
_currentMaxChildSize = fractionalValue;
},
);
}
}
}
double _calculateCacheExtent(double bottomInset) {
const defaultExtent = RenderAbstractViewport.defaultCacheExtent;
if (bottomInset > defaultExtent) {
return bottomInset;
} else {
return defaultExtent;
}
}
@override
void dispose() {
widget.animationController?.removeStatusListener(_animationStatusListener);
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final bottomSheetThemeBackground =
Theme.of(context).bottomSheetTheme.backgroundColor;
final colorSchemeBackground = Theme.of(context).colorScheme.background;
final bottomSheetColor = widget.bottomSheetColor ??
bottomSheetThemeBackground ??
colorSchemeBackground;
final contentDecoration = widget.decoration ??
BoxDecoration(
color: widget.bottomSheetColor ??
bottomSheetThemeBackground ??
colorSchemeBackground,
);
final behaviorScroll = _getScrollBehaviorInWeb();
final bottomSheet = NotificationListener<DraggableScrollableNotification>(
onNotification: _scrolling,
child: DraggableScrollableSheet(
maxChildSize: _currentMaxChildSize,
minChildSize: widget.minHeight,
initialChildSize: _initialChildSize,
snap: widget.anchors != null,
controller: _controller,
snapSizes: widget.anchors,
expand: widget.isExpand,
builder: (
context,
controller,
) {
return ChangeInsetsDetector(
handler: (change) {
final inset = change.currentInset;
final delta = change.delta;
if (delta > 0 && !_isClosing) {
_animateToMaxHeight();
_widgetBinding.addPostFrameCallback(
(_) {
_animateToFocused(controller);
},
);
}
// Checking for openness of the keyboard before opening the sheet.
if (delta == 0 && inset > 0) {
_widgetBinding.addPostFrameCallback(
(_) {
setState(
() {
_initialChildSize = widget.maxHeight;
},
);
},
);
}
},
child: Material(
type: MaterialType.transparency,
color: bottomSheetColor,
borderRadius: widget.bottomSheetBorderRadius,
clipBehavior: widget.bottomSheetBorderRadius != null
? Clip.antiAlias
: Clip.none,
child: _RegisterScaffold(
useRootScaffold: widget.useRootScaffold,
backgroundColor: bottomSheetColor,
child: _Content(
builder: widget.builder,
decoration: contentDecoration,
bodyBuilder: widget.bodyBuilder,
headerBuilder: widget.headerBuilder,
minHeaderHeight: widget.minHeaderHeight,
maxHeaderHeight: widget.maxHeaderHeight,
currentExtent: _controller.isAttached
? _controller.size
: widget.initHeight,
scrollController: controller,
cacheExtent: _calculateCacheExtent(
MediaQuery.viewInsetsOf(context).bottom,
),
getContentHeight:
!widget.isExpand ? _changeInitAndMaxHeight : null,
),
),
),
);
},
),
);
return behaviorScroll == null
? bottomSheet
: ScrollConfiguration(behavior: behaviorScroll, child: bottomSheet);
}
MaterialScrollBehavior? _getScrollBehaviorInWeb() {
final behaviorInWeb = ScrollBehaviorInWeb();
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.iOS:
return null;
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
return behaviorInWeb;
}
}
}
/// Register [Scaffold] for [FlexibleBottomSheet].
class _RegisterScaffold extends StatelessWidget {
final bool useRootScaffold;
final Widget child;
final Color backgroundColor;
const _RegisterScaffold({
required this.useRootScaffold,
required this.child,
required this.backgroundColor,
});
@override
Widget build(BuildContext context) {
return useRootScaffold
? Scaffold(
backgroundColor: backgroundColor,
body: child,
)
: ColoredBox(
color: backgroundColor,
child: child,
);
}
}
/// Content for [FlexibleBottomSheet].
class _Content extends StatefulWidget {
final FlexibleDraggableScrollableWidgetBuilder? builder;
final Decoration? decoration;
final FlexibleDraggableScrollableHeaderWidgetBuilder? headerBuilder;
final FlexibleDraggableScrollableWidgetBodyBuilder? bodyBuilder;
final double? minHeaderHeight;
final double? maxHeaderHeight;
final double currentExtent;
final ScrollController scrollController;
final Function(double)? getContentHeight;
final double cacheExtent;
const _Content({
required this.currentExtent,
required this.scrollController,
required this.cacheExtent,
this.builder,
this.decoration,
this.headerBuilder,
this.bodyBuilder,
this.minHeaderHeight,
this.maxHeaderHeight,
this.getContentHeight,
});
@override
State<_Content> createState() => _ContentState();
}
class _ContentState extends State<_Content> {
final _contentKey = GlobalKey();
@override
void initState() {
super.initState();
if (widget.getContentHeight != null) {
WidgetsBinding.instance.addPostFrameCallback(
(timeStamp) {
final renderContent =
_contentKey.currentContext!.findRenderObject()! as RenderBox;
widget.getContentHeight!(renderContent.size.height);
},
);
}
}
@override
Widget build(BuildContext context) {
if (widget.builder != null) {
return Material(
type: MaterialType.transparency,
child: DecoratedBox(
decoration: widget.decoration ?? const BoxDecoration(),
child: SizedBox(
key: _contentKey,
child: widget.builder!(
context,
widget.scrollController,
widget.currentExtent,
),
),
),
);
}
return Material(
type: MaterialType.transparency,
child: DecoratedBox(
decoration: widget.decoration ?? const BoxDecoration(),
child: CustomScrollView(
cacheExtent: widget.cacheExtent,
key: _contentKey,
controller: widget.scrollController,
slivers: <Widget>[
if (widget.headerBuilder != null)
SliverPersistentHeader(
pinned: true,
delegate: FlexibleBottomSheetHeaderDelegate(
minHeight: widget.minHeaderHeight ?? 0.0,
maxHeight: widget.maxHeaderHeight ?? 1.0,
child: widget.headerBuilder!(context, widget.currentExtent),
),
),
if (widget.bodyBuilder != null)
SliverList(
delegate: widget.bodyBuilder!(
context,
widget.currentExtent,
),
),
],
),
),
);
}
}