This repository has been archived by the owner on Feb 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
basic.dart
7620 lines (7100 loc) · 283 KB
/
basic.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:math' as math;
import 'dart:ui' as ui show Image, ImageFilter, TextHeightBehavior;
import 'package:flutter/animation.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'binding.dart';
import 'debug.dart';
import 'framework.dart';
import 'localizations.dart';
import 'widget_span.dart';
export 'package:flutter/animation.dart';
export 'package:flutter/foundation.dart' show
ChangeNotifier,
FlutterErrorDetails,
Listenable,
TargetPlatform,
ValueNotifier;
export 'package:flutter/painting.dart';
export 'package:flutter/rendering.dart' show
AlignmentGeometryTween,
AlignmentTween,
Axis,
BoxConstraints,
BoxConstraintsTransform,
CrossAxisAlignment,
CustomClipper,
CustomPainter,
CustomPainterSemantics,
DecorationPosition,
FlexFit,
FlowDelegate,
FlowPaintingContext,
FractionalOffsetTween,
HitTestBehavior,
LayerLink,
MainAxisAlignment,
MainAxisSize,
MouseCursor,
MultiChildLayoutDelegate,
PaintingContext,
PointerCancelEvent,
PointerCancelEventListener,
PointerDownEvent,
PointerDownEventListener,
PointerEvent,
PointerMoveEvent,
PointerMoveEventListener,
PointerUpEvent,
PointerUpEventListener,
RelativeRect,
SemanticsBuilderCallback,
ShaderCallback,
ShapeBorderClipper,
SingleChildLayoutDelegate,
StackFit,
SystemMouseCursors,
TextOverflow,
ValueChanged,
ValueGetter,
WrapAlignment,
WrapCrossAlignment;
export 'package:flutter/services.dart' show
AssetBundle;
// Examples can assume:
// class TestWidget extends StatelessWidget { const TestWidget({super.key}); @override Widget build(BuildContext context) => const Placeholder(); }
// late WidgetTester tester;
// late bool _visible;
// class Sky extends CustomPainter { @override void paint(Canvas c, Size s) {} @override bool shouldRepaint(Sky s) => false; }
// late BuildContext context;
// String userAvatarUrl = '';
// BIDIRECTIONAL TEXT SUPPORT
/// An [InheritedElement] that has hundreds of dependencies but will
/// infrequently change. This provides a performance tradeoff where building
/// the [Widget]s is faster but performing updates is slower.
///
/// | | _UbiquitousInheritedElement | InheritedElement |
/// |---------------------|------------------------------|------------------|
/// | insert (best case) | O(1) | O(1) |
/// | insert (worst case) | O(1) | O(n) |
/// | search (best case) | O(n) | O(1) |
/// | search (worst case) | O(n) | O(n) |
///
/// Insert happens when building the [Widget] tree, search happens when updating
/// [Widget]s.
class _UbiquitousInheritedElement extends InheritedElement {
/// Creates an element that uses the given widget as its configuration.
_UbiquitousInheritedElement(super.widget);
@override
void setDependencies(Element dependent, Object? value) {
// This is where the cost of [InheritedElement] is incurred during build
// time of the widget tree. Omitting this bookkeeping is where the
// performance savings come from.
assert(value == null);
}
@override
Object? getDependencies(Element dependent) {
return null;
}
@override
void notifyClients(InheritedWidget oldWidget) {
_recurseChildren(this, (Element element) {
if (element.doesDependOnInheritedElement(this)) {
notifyDependent(oldWidget, element);
}
});
}
static void _recurseChildren(Element element, ElementVisitor visitor) {
element.visitChildren((Element child) {
_recurseChildren(child, visitor);
});
visitor(element);
}
}
/// See also:
///
/// * [_UbiquitousInheritedElement], the [Element] for [_UbiquitousInheritedWidget].
abstract class _UbiquitousInheritedWidget extends InheritedWidget {
const _UbiquitousInheritedWidget({super.key, required super.child});
@override
InheritedElement createElement() => _UbiquitousInheritedElement(this);
}
/// A widget that determines the ambient directionality of text and
/// text-direction-sensitive render objects.
///
/// For example, [Padding] depends on the [Directionality] to resolve
/// [EdgeInsetsDirectional] objects into absolute [EdgeInsets] objects.
class Directionality extends _UbiquitousInheritedWidget {
/// Creates a widget that determines the directionality of text and
/// text-direction-sensitive render objects.
///
/// The [textDirection] and [child] arguments must not be null.
const Directionality({
super.key,
required this.textDirection,
required super.child,
}) : assert(textDirection != null),
assert(child != null);
/// The text direction for this subtree.
final TextDirection textDirection;
/// The text direction from the closest instance of this class that encloses
/// the given context.
///
/// If there is no [Directionality] ancestor widget in the tree at the given
/// context, then this will throw a descriptive [FlutterError] in debug mode
/// and an exception in release mode.
///
/// Typical usage is as follows:
///
/// ```dart
/// TextDirection textDirection = Directionality.of(context);
/// ```
///
/// See also:
///
/// * [maybeOf], which will return null if no [Directionality] ancestor
/// widget is in the tree.
static TextDirection of(BuildContext context) {
assert(debugCheckHasDirectionality(context));
final Directionality widget = context.dependOnInheritedWidgetOfExactType<Directionality>()!;
return widget.textDirection;
}
/// The text direction from the closest instance of this class that encloses
/// the given context.
///
/// If there is no [Directionality] ancestor widget in the tree at the given
/// context, then this will return null.
///
/// Typical usage is as follows:
///
/// ```dart
/// TextDirection? textDirection = Directionality.maybeOf(context);
/// ```
///
/// See also:
///
/// * [of], which will throw if no [Directionality] ancestor widget is in the
/// tree.
static TextDirection? maybeOf(BuildContext context) {
final Directionality? widget = context.dependOnInheritedWidgetOfExactType<Directionality>();
return widget?.textDirection;
}
@override
bool updateShouldNotify(Directionality oldWidget) => textDirection != oldWidget.textDirection;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(EnumProperty<TextDirection>('textDirection', textDirection));
}
}
// PAINTING NODES
/// A widget that makes its child partially transparent.
///
/// This class paints its child into an intermediate buffer and then blends the
/// child back into the scene partially transparent.
///
/// For values of opacity other than 0.0 and 1.0, this class is relatively
/// expensive because it requires painting the child into an intermediate
/// buffer. For the value 0.0, the child is not painted at all. For the
/// value 1.0, the child is painted immediately without an intermediate buffer.
///
/// The presence of the intermediate buffer which has a transparent background
/// by default may cause some child widgets to behave differently. For example
/// a [BackdropFilter] child will only be able to apply its filter to the content
/// between this widget and the backdrop child and may require adjusting the
/// [BackdropFilter.blendMode] property to produce the desired results.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=9hltevOHQBw}
///
/// {@tool snippet}
///
/// This example shows some [Text] when the `_visible` member field is true, and
/// hides it when it is false:
///
/// ```dart
/// Opacity(
/// opacity: _visible ? 1.0 : 0.0,
/// child: const Text("Now you see me, now you don't!"),
/// )
/// ```
/// {@end-tool}
///
/// This is more efficient than adding and removing the child widget from the
/// tree on demand.
///
/// ## Performance considerations for opacity animation
///
/// Animating an [Opacity] widget directly causes the widget (and possibly its
/// subtree) to rebuild each frame, which is not very efficient. Consider using
/// an [AnimatedOpacity] or a [FadeTransition] instead.
///
/// ## Transparent image
///
/// If only a single [Image] or [Color] needs to be composited with an opacity
/// between 0.0 and 1.0, it's much faster to directly use them without [Opacity]
/// widgets.
///
/// For example, `Container(color: Color.fromRGBO(255, 0, 0, 0.5))` is much
/// faster than `Opacity(opacity: 0.5, child: Container(color: Colors.red))`.
///
/// {@tool snippet}
///
/// The following example draws an [Image] with 0.5 opacity without using
/// [Opacity]:
///
/// ```dart
/// Image.network(
/// 'https://raw.githubusercontent.com/flutter/assets-for-api-docs/master/packages/diagrams/assets/blend_mode_destination.jpeg',
/// color: const Color.fromRGBO(255, 255, 255, 0.5),
/// colorBlendMode: BlendMode.modulate
/// )
/// ```
///
/// {@end-tool}
///
/// Directly drawing an [Image] or [Color] with opacity is faster than using
/// [Opacity] on top of them because [Opacity] could apply the opacity to a
/// group of widgets and therefore a costly offscreen buffer will be used.
/// Drawing content into the offscreen buffer may also trigger render target
/// switches and such switching is particularly slow in older GPUs.
///
/// See also:
///
/// * [Visibility], which can hide a child more efficiently (albeit less
/// subtly, because it is either visible or hidden, rather than allowing
/// fractional opacity values). Specifically, the [Visibility.maintain]
/// constructor is equivalent to using an opacity widget with values of
/// `0.0` or `1.0`.
/// * [ShaderMask], which can apply more elaborate effects to its child.
/// * [Transform], which applies an arbitrary transform to its child widget at
/// paint time.
/// * [AnimatedOpacity], which uses an animation internally to efficiently
/// animate opacity.
/// * [FadeTransition], which uses a provided animation to efficiently animate
/// opacity.
/// * [Image], which can directly provide a partially transparent image with
/// much less performance hit.
class Opacity extends SingleChildRenderObjectWidget {
/// Creates a widget that makes its child partially transparent.
///
/// The [opacity] argument must not be null and must be between 0.0 and 1.0
/// (inclusive).
const Opacity({
super.key,
required this.opacity,
this.alwaysIncludeSemantics = false,
super.child,
}) : assert(opacity != null && opacity >= 0.0 && opacity <= 1.0),
assert(alwaysIncludeSemantics != null);
/// The fraction to scale the child's alpha value.
///
/// An opacity of 1.0 is fully opaque. An opacity of 0.0 is fully transparent
/// (i.e., invisible).
///
/// The opacity must not be null.
///
/// Values 1.0 and 0.0 are painted with a fast path. Other values
/// require painting the child into an intermediate buffer, which is
/// expensive.
final double opacity;
/// Whether the semantic information of the children is always included.
///
/// Defaults to false.
///
/// When true, regardless of the opacity settings the child semantic
/// information is exposed as if the widget were fully visible. This is
/// useful in cases where labels may be hidden during animations that
/// would otherwise contribute relevant semantics.
final bool alwaysIncludeSemantics;
@override
RenderOpacity createRenderObject(BuildContext context) {
return RenderOpacity(
opacity: opacity,
alwaysIncludeSemantics: alwaysIncludeSemantics,
);
}
@override
void updateRenderObject(BuildContext context, RenderOpacity renderObject) {
renderObject
..opacity = opacity
..alwaysIncludeSemantics = alwaysIncludeSemantics;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DoubleProperty('opacity', opacity));
properties.add(FlagProperty('alwaysIncludeSemantics', value: alwaysIncludeSemantics, ifTrue: 'alwaysIncludeSemantics'));
}
}
/// A widget that applies a mask generated by a [Shader] to its child.
///
/// For example, [ShaderMask] can be used to gradually fade out the edge
/// of a child by using a [ui.Gradient.linear] mask.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=7sUL66pTQ7Q}
///
/// {@tool snippet}
///
/// This example makes the text look like it is on fire:
///
/// ```dart
/// ShaderMask(
/// shaderCallback: (Rect bounds) {
/// return RadialGradient(
/// center: Alignment.topLeft,
/// radius: 1.0,
/// colors: <Color>[Colors.yellow, Colors.deepOrange.shade900],
/// tileMode: TileMode.mirror,
/// ).createShader(bounds);
/// },
/// child: const Text('I’m burning the memories'),
/// )
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [Opacity], which can apply a uniform alpha effect to its child.
/// * [CustomPaint], which lets you draw directly on the canvas.
/// * [DecoratedBox], for another approach at decorating child widgets.
/// * [BackdropFilter], which applies an image filter to the background.
class ShaderMask extends SingleChildRenderObjectWidget {
/// Creates a widget that applies a mask generated by a [Shader] to its child.
///
/// The [shaderCallback] and [blendMode] arguments must not be null.
const ShaderMask({
super.key,
required this.shaderCallback,
this.blendMode = BlendMode.modulate,
super.child,
}) : assert(shaderCallback != null),
assert(blendMode != null);
/// Called to create the [dart:ui.Shader] that generates the mask.
///
/// The shader callback is called with the current size of the child so that
/// it can customize the shader to the size and location of the child.
///
/// Typically this will use a [LinearGradient], [RadialGradient], or
/// [SweepGradient] to create the [dart:ui.Shader], though the
/// [dart:ui.ImageShader] class could also be used.
final ShaderCallback shaderCallback;
/// The [BlendMode] to use when applying the shader to the child.
///
/// The default, [BlendMode.modulate], is useful for applying an alpha blend
/// to the child. Other blend modes can be used to create other effects.
final BlendMode blendMode;
@override
RenderShaderMask createRenderObject(BuildContext context) {
return RenderShaderMask(
shaderCallback: shaderCallback,
blendMode: blendMode,
);
}
@override
void updateRenderObject(BuildContext context, RenderShaderMask renderObject) {
renderObject
..shaderCallback = shaderCallback
..blendMode = blendMode;
}
}
/// A widget that applies a filter to the existing painted content and then
/// paints [child].
///
/// The filter will be applied to all the area within its parent or ancestor
/// widget's clip. If there's no clip, the filter will be applied to the full
/// screen.
///
/// The results of the filter will be blended back into the background using
/// the [blendMode] parameter.
/// {@template flutter.widgets.BackdropFilter.blendMode}
/// The only value for [blendMode] that is supported on all platforms is
/// [BlendMode.srcOver] which works well for most scenes. But that value may
/// produce surprising results when a parent of the [BackdropFilter] uses a
/// temporary buffer, or save layer, as does an [Opacity] widget. In that
/// situation, a value of [BlendMode.src] can produce more pleasing results,
/// but at the cost of incompatibility with some platforms, most notably the
/// html renderer for web applications.
/// {@endtemplate}
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=dYRs7Q1vfYI}
///
/// {@tool snippet}
/// If the [BackdropFilter] needs to be applied to an area that exactly matches
/// its child, wraps the [BackdropFilter] with a clip widget that clips exactly
/// to that child.
///
/// ```dart
/// Stack(
/// fit: StackFit.expand,
/// children: <Widget>[
/// Text('0' * 10000),
/// Center(
/// child: ClipRect( // <-- clips to the 200x200 [Container] below
/// child: BackdropFilter(
/// filter: ui.ImageFilter.blur(
/// sigmaX: 5.0,
/// sigmaY: 5.0,
/// ),
/// child: Container(
/// alignment: Alignment.center,
/// width: 200.0,
/// height: 200.0,
/// child: const Text('Hello World'),
/// ),
/// ),
/// ),
/// ),
/// ],
/// )
/// ```
/// {@end-tool}
///
/// This effect is relatively expensive, especially if the filter is non-local,
/// such as a blur.
///
/// If all you want to do is apply an [ImageFilter] to a single widget
/// (as opposed to applying the filter to everything _beneath_ a widget), use
/// [ImageFiltered] instead. For that scenario, [ImageFiltered] is both
/// easier to use and less expensive than [BackdropFilter].
///
/// {@tool snippet}
///
/// This example shows how the common case of applying a [BackdropFilter] blur
/// to a single sibling can be replaced with an [ImageFiltered] widget. This code
/// is generally simpler and the performance will be improved dramatically for
/// complex filters like blurs.
///
/// The implementation below is unnecessarily expensive.
///
/// ```dart
/// Widget buildBackdrop() {
/// return Stack(
/// children: <Widget>[
/// Positioned.fill(child: Image.asset('image.png')),
/// Positioned.fill(
/// child: BackdropFilter(
/// filter: ui.ImageFilter.blur(sigmaX: 6, sigmaY: 6),
/// ),
/// ),
/// ],
/// );
/// }
/// ```
/// {@end-tool}
/// {@tool snippet}
/// Instead consider the following approach which directly applies a blur
/// to the child widget.
///
/// ```dart
/// Widget buildFilter() {
/// return ImageFiltered(
/// imageFilter: ui.ImageFilter.blur(sigmaX: 6, sigmaY: 6),
/// child: Image.asset('image.png'),
/// );
/// }
/// ```
///
/// {@end-tool}
///
/// See also:
///
/// * [ImageFiltered], which applies an [ImageFilter] to its child.
/// * [DecoratedBox], which draws a background under (or over) a widget.
/// * [Opacity], which changes the opacity of the widget itself.
/// * https://flutter.dev/go/ios-platformview-backdrop-filter-blur for details and restrictions when an iOS PlatformView needs to be blurred.
class BackdropFilter extends SingleChildRenderObjectWidget {
/// Creates a backdrop filter.
///
/// The [filter] argument must not be null.
/// The [blendMode] argument will default to [BlendMode.srcOver] and must not be
/// null if provided.
const BackdropFilter({
super.key,
required this.filter,
super.child,
this.blendMode = BlendMode.srcOver,
}) : assert(filter != null);
/// The image filter to apply to the existing painted content before painting the child.
///
/// For example, consider using [ImageFilter.blur] to create a backdrop
/// blur effect.
final ui.ImageFilter filter;
/// The blend mode to use to apply the filtered background content onto the background
/// surface.
///
/// {@macro flutter.widgets.BackdropFilter.blendMode}
final BlendMode blendMode;
@override
RenderBackdropFilter createRenderObject(BuildContext context) {
return RenderBackdropFilter(filter: filter, blendMode: blendMode);
}
@override
void updateRenderObject(BuildContext context, RenderBackdropFilter renderObject) {
renderObject
..filter = filter
..blendMode = blendMode;
}
}
/// A widget that provides a canvas on which to draw during the paint phase.
///
/// When asked to paint, [CustomPaint] first asks its [painter] to paint on the
/// current canvas, then it paints its child, and then, after painting its
/// child, it asks its [foregroundPainter] to paint. The coordinate system of the
/// canvas matches the coordinate system of the [CustomPaint] object. The
/// painters are expected to paint within a rectangle starting at the origin and
/// encompassing a region of the given size. (If the painters paint outside
/// those bounds, there might be insufficient memory allocated to rasterize the
/// painting commands and the resulting behavior is undefined.) To enforce
/// painting within those bounds, consider wrapping this [CustomPaint] with a
/// [ClipRect] widget.
///
/// Painters are implemented by subclassing [CustomPainter].
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=kp14Y4uHpHs}
///
/// Because custom paint calls its painters during paint, you cannot call
/// `setState` or `markNeedsLayout` during the callback (the layout for this
/// frame has already happened).
///
/// Custom painters normally size themselves to their child. If they do not have
/// a child, they attempt to size themselves to the [size], which defaults to
/// [Size.zero]. [size] must not be null.
///
/// [isComplex] and [willChange] are hints to the compositor's raster cache
/// and must not be null.
///
/// {@tool snippet}
///
/// This example shows how the sample custom painter shown at [CustomPainter]
/// could be used in a [CustomPaint] widget to display a background to some
/// text.
///
/// ```dart
/// CustomPaint(
/// painter: Sky(),
/// child: const Center(
/// child: Text(
/// 'Once upon a time...',
/// style: TextStyle(
/// fontSize: 40.0,
/// fontWeight: FontWeight.w900,
/// color: Color(0xFFFFFFFF),
/// ),
/// ),
/// ),
/// )
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [CustomPainter], the class to extend when creating custom painters.
/// * [Canvas], the class that a custom painter uses to paint.
class CustomPaint extends SingleChildRenderObjectWidget {
/// Creates a widget that delegates its painting.
const CustomPaint({
super.key,
this.painter,
this.foregroundPainter,
this.size = Size.zero,
this.isComplex = false,
this.willChange = false,
super.child,
}) : assert(size != null),
assert(isComplex != null),
assert(willChange != null),
assert(painter != null || foregroundPainter != null || (!isComplex && !willChange));
/// The painter that paints before the children.
final CustomPainter? painter;
/// The painter that paints after the children.
final CustomPainter? foregroundPainter;
/// The size that this [CustomPaint] should aim for, given the layout
/// constraints, if there is no child.
///
/// Defaults to [Size.zero].
///
/// If there's a child, this is ignored, and the size of the child is used
/// instead.
final Size size;
/// Whether the painting is complex enough to benefit from caching.
///
/// The compositor contains a raster cache that holds bitmaps of layers in
/// order to avoid the cost of repeatedly rendering those layers on each
/// frame. If this flag is not set, then the compositor will apply its own
/// heuristics to decide whether the this layer is complex enough to benefit
/// from caching.
///
/// This flag can't be set to true if both [painter] and [foregroundPainter]
/// are null because this flag will be ignored in such case.
final bool isComplex;
/// Whether the raster cache should be told that this painting is likely
/// to change in the next frame.
///
/// This flag can't be set to true if both [painter] and [foregroundPainter]
/// are null because this flag will be ignored in such case.
final bool willChange;
@override
RenderCustomPaint createRenderObject(BuildContext context) {
return RenderCustomPaint(
painter: painter,
foregroundPainter: foregroundPainter,
preferredSize: size,
isComplex: isComplex,
willChange: willChange,
);
}
@override
void updateRenderObject(BuildContext context, RenderCustomPaint renderObject) {
renderObject
..painter = painter
..foregroundPainter = foregroundPainter
..preferredSize = size
..isComplex = isComplex
..willChange = willChange;
}
@override
void didUnmountRenderObject(RenderCustomPaint renderObject) {
renderObject
..painter = null
..foregroundPainter = null;
}
}
/// A widget that clips its child using a rectangle.
///
/// By default, [ClipRect] prevents its child from painting outside its
/// bounds, but the size and location of the clip rect can be customized using a
/// custom [clipper].
///
/// [ClipRect] is commonly used with these widgets, which commonly paint outside
/// their bounds:
///
/// * [CustomPaint]
/// * [CustomSingleChildLayout]
/// * [CustomMultiChildLayout]
/// * [Align] and [Center] (e.g., if [Align.widthFactor] or
/// [Align.heightFactor] is less than 1.0).
/// * [OverflowBox]
/// * [SizedOverflowBox]
///
/// {@tool snippet}
///
/// For example, by combining a [ClipRect] with an [Align], one can show just
/// the top half of an [Image]:
///
/// ```dart
/// ClipRect(
/// child: Align(
/// alignment: Alignment.topCenter,
/// heightFactor: 0.5,
/// child: Image.network(userAvatarUrl),
/// ),
/// )
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [CustomClipper], for information about creating custom clips.
/// * [ClipRRect], for a clip with rounded corners.
/// * [ClipOval], for an elliptical clip.
/// * [ClipPath], for an arbitrarily shaped clip.
class ClipRect extends SingleChildRenderObjectWidget {
/// Creates a rectangular clip.
///
/// If [clipper] is null, the clip will match the layout size and position of
/// the child.
///
/// The [clipBehavior] argument must not be null. If [clipBehavior] is
/// [Clip.none], no clipping will be applied.
const ClipRect({
super.key,
this.clipper,
this.clipBehavior = Clip.hardEdge,
super.child,
}) : assert(clipBehavior != null);
/// If non-null, determines which clip to use.
final CustomClipper<Rect>? clipper;
/// {@macro flutter.rendering.ClipRectLayer.clipBehavior}
///
/// Defaults to [Clip.hardEdge].
final Clip clipBehavior;
@override
RenderClipRect createRenderObject(BuildContext context) {
return RenderClipRect(clipper: clipper, clipBehavior: clipBehavior);
}
@override
void updateRenderObject(BuildContext context, RenderClipRect renderObject) {
renderObject
..clipper = clipper
..clipBehavior = clipBehavior;
}
@override
void didUnmountRenderObject(RenderClipRect renderObject) {
renderObject.clipper = null;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<CustomClipper<Rect>>('clipper', clipper, defaultValue: null));
}
}
/// A widget that clips its child using a rounded rectangle.
///
/// By default, [ClipRRect] uses its own bounds as the base rectangle for the
/// clip, but the size and location of the clip can be customized using a custom
/// [clipper].
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=eI43jkQkrvs}
///
/// {@tool dartpad}
/// This example shows various [ClipRRect]s applied to containers.
///
/// ** See code in examples/api/lib/widgets/basic/clip_rrect.0.dart **
/// {@end-tool}
///
/// ## Troubleshooting
///
/// ### Why doesn't my [ClipRRect] child have rounded corners?
///
/// When a [ClipRRect] is bigger than the child it contains, its rounded corners
/// could be drawn in unexpected positions. Make sure that [ClipRRect] and its child
/// have the same bounds (by shrinking the [ClipRRect] with a [FittedBox] or by
/// growing the child).
///
/// {@tool dartpad}
/// This example shows a [ClipRRect] that adds round corners to an image.
///
/// ** See code in examples/api/lib/widgets/basic/clip_rrect.1.dart **
/// {@end-tool}
///
/// See also:
///
/// * [CustomClipper], for information about creating custom clips.
/// * [ClipRect], for more efficient clips without rounded corners.
/// * [ClipOval], for an elliptical clip.
/// * [ClipPath], for an arbitrarily shaped clip.
class ClipRRect extends SingleChildRenderObjectWidget {
/// Creates a rounded-rectangular clip.
///
/// The [borderRadius] defaults to [BorderRadius.zero], i.e. a rectangle with
/// right-angled corners.
///
/// If [clipper] is non-null, then [borderRadius] is ignored.
///
/// The [clipBehavior] argument must not be null. If [clipBehavior] is
/// [Clip.none], no clipping will be applied.
const ClipRRect({
super.key,
this.borderRadius = BorderRadius.zero,
this.clipper,
this.clipBehavior = Clip.antiAlias,
super.child,
}) : assert(borderRadius != null || clipper != null),
assert(clipBehavior != null);
/// The border radius of the rounded corners.
///
/// Values are clamped so that horizontal and vertical radii sums do not
/// exceed width/height.
///
/// This value is ignored if [clipper] is non-null.
final BorderRadiusGeometry? borderRadius;
/// If non-null, determines which clip to use.
final CustomClipper<RRect>? clipper;
/// {@macro flutter.rendering.ClipRectLayer.clipBehavior}
///
/// Defaults to [Clip.antiAlias].
final Clip clipBehavior;
@override
RenderClipRRect createRenderObject(BuildContext context) {
return RenderClipRRect(
borderRadius: borderRadius!,
clipper: clipper,
clipBehavior: clipBehavior,
textDirection: Directionality.maybeOf(context),
);
}
@override
void updateRenderObject(BuildContext context, RenderClipRRect renderObject) {
renderObject
..borderRadius = borderRadius!
..clipBehavior = clipBehavior
..clipper = clipper
..textDirection = Directionality.maybeOf(context);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<BorderRadiusGeometry>('borderRadius', borderRadius, showName: false, defaultValue: null));
properties.add(DiagnosticsProperty<CustomClipper<RRect>>('clipper', clipper, defaultValue: null));
}
}
/// A widget that clips its child using an oval.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=vzWWDO6whIM}
///
/// By default, inscribes an axis-aligned oval into its layout dimensions and
/// prevents its child from painting outside that oval, but the size and
/// location of the clip oval can be customized using a custom [clipper].
///
/// See also:
///
/// * [CustomClipper], for information about creating custom clips.
/// * [ClipRect], for more efficient clips without rounded corners.
/// * [ClipRRect], for a clip with rounded corners.
/// * [ClipPath], for an arbitrarily shaped clip.
class ClipOval extends SingleChildRenderObjectWidget {
/// Creates an oval-shaped clip.
///
/// If [clipper] is null, the oval will be inscribed into the layout size and
/// position of the child.
///
/// The [clipBehavior] argument must not be null. If [clipBehavior] is
/// [Clip.none], no clipping will be applied.
const ClipOval({
super.key,
this.clipper,
this.clipBehavior = Clip.antiAlias,
super.child,
}) : assert(clipBehavior != null);
/// If non-null, determines which clip to use.
///
/// The delegate returns a rectangle that describes the axis-aligned
/// bounding box of the oval. The oval's axes will themselves also
/// be axis-aligned.
///
/// If the [clipper] delegate is null, then the oval uses the
/// widget's bounding box (the layout dimensions of the render
/// object) instead.
final CustomClipper<Rect>? clipper;
/// {@macro flutter.rendering.ClipRectLayer.clipBehavior}
///
/// Defaults to [Clip.antiAlias].
final Clip clipBehavior;
@override
RenderClipOval createRenderObject(BuildContext context) {
return RenderClipOval(clipper: clipper, clipBehavior: clipBehavior);
}
@override
void updateRenderObject(BuildContext context, RenderClipOval renderObject) {
renderObject
..clipper = clipper
..clipBehavior = clipBehavior;
}
@override
void didUnmountRenderObject(RenderClipOval renderObject) {
renderObject.clipper = null;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<CustomClipper<Rect>>('clipper', clipper, defaultValue: null));
}
}
/// A widget that clips its child using a path.
///
/// Calls a callback on a delegate whenever the widget is to be
/// painted. The callback returns a path and the widget prevents the
/// child from painting outside the path.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=oAUebVIb-7s}
///
/// Clipping to a path is expensive. Certain shapes have more
/// optimized widgets:
///
/// * To clip to a rectangle, consider [ClipRect].
/// * To clip to an oval or circle, consider [ClipOval].
/// * To clip to a rounded rectangle, consider [ClipRRect].
///
/// To clip to a particular [ShapeBorder], consider using either the
/// [ClipPath.shape] static method or the [ShapeBorderClipper] custom clipper
/// class.
class ClipPath extends SingleChildRenderObjectWidget {
/// Creates a path clip.
///
/// If [clipper] is null, the clip will be a rectangle that matches the layout
/// size and location of the child. However, rather than use this default,
/// consider using a [ClipRect], which can achieve the same effect more
/// efficiently.
///
/// The [clipBehavior] argument must not be null. If [clipBehavior] is
/// [Clip.none], no clipping will be applied.
const ClipPath({
super.key,
this.clipper,
this.clipBehavior = Clip.antiAlias,
super.child,
}) : assert(clipBehavior != null);