text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// 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 'arena.dart'; import 'binding.dart'; export 'arena.dart' show GestureArenaEntry, GestureArenaMember; class _CombiningGestureArenaEntry implements GestureArenaEntry { _CombiningGestureArenaEntry(this._combiner, this._member); final _CombiningGestureArenaMember _combiner; final GestureArenaMember _member; @override void resolve(GestureDisposition disposition) { _combiner._resolve(_member, disposition); } } class _CombiningGestureArenaMember extends GestureArenaMember { _CombiningGestureArenaMember(this._owner, this._pointer); final GestureArenaTeam _owner; final List<GestureArenaMember> _members = <GestureArenaMember>[]; final int _pointer; bool _resolved = false; GestureArenaMember? _winner; GestureArenaEntry? _entry; @override void acceptGesture(int pointer) { assert(_pointer == pointer); assert(_winner != null || _members.isNotEmpty); _close(); _winner ??= _owner.captain ?? _members[0]; for (final GestureArenaMember member in _members) { if (member != _winner) { member.rejectGesture(pointer); } } _winner!.acceptGesture(pointer); } @override void rejectGesture(int pointer) { assert(_pointer == pointer); _close(); for (final GestureArenaMember member in _members) { member.rejectGesture(pointer); } } void _close() { assert(!_resolved); _resolved = true; final _CombiningGestureArenaMember? combiner = _owner._combiners.remove(_pointer); assert(combiner == this); } GestureArenaEntry _add(int pointer, GestureArenaMember member) { assert(!_resolved); assert(_pointer == pointer); _members.add(member); _entry ??= GestureBinding.instance.gestureArena.add(pointer, this); return _CombiningGestureArenaEntry(this, member); } void _resolve(GestureArenaMember member, GestureDisposition disposition) { if (_resolved) { return; } switch (disposition) { case GestureDisposition.accepted: _winner ??= _owner.captain ?? member; _entry!.resolve(disposition); case GestureDisposition.rejected: _members.remove(member); member.rejectGesture(_pointer); if (_members.isEmpty) { _entry!.resolve(disposition); } } } } /// A group of [GestureArenaMember] objects that are competing as a unit in the /// [GestureArenaManager]. /// /// Normally, a recognizer competes directly in the [GestureArenaManager] to /// recognize a sequence of pointer events as a gesture. With a /// [GestureArenaTeam], recognizers can compete in the arena in a group with /// other recognizers. Arena teams may have a captain which wins the arena on /// behalf of its team. /// /// When gesture recognizers are in a team together without a captain, then once /// there are no other competing gestures in the arena, the first gesture to /// have been added to the team automatically wins, instead of the gestures /// continuing to compete against each other. /// /// When gesture recognizers are in a team with a captain, then once one of the /// team members claims victory or there are no other competing gestures in the /// arena, the captain wins the arena, and all other team members lose. /// /// For example, [Slider] uses a team without a captain to support both a /// [HorizontalDragGestureRecognizer] and a [TapGestureRecognizer], but without /// the drag recognizer having to wait until the user has dragged outside the /// slop region of the tap gesture before triggering. Since they compete as a /// team, as soon as any other recognizers are out of the arena, the drag /// recognizer wins, even if the user has not actually dragged yet. On the other /// hand, if the tap can win outright, before the other recognizers are taken /// out of the arena (e.g. if the slider is in a vertical scrolling list and the /// user places their finger on the touch surface then lifts it, so that neither /// the horizontal nor vertical drag recognizers can claim victory) the tap /// recognizer still actually wins, despite being in the team. /// /// [AndroidView] uses a team with a captain to decide which gestures are /// forwarded to the native view. For example if we want to forward taps and /// vertical scrolls to a native Android view, [TapGestureRecognizer]s and /// [VerticalDragGestureRecognizer] are added to a team with a captain (the /// captain is set to be a gesture recognizer that never explicitly claims the /// gesture). /// /// The captain allows [AndroidView] to know when any gestures in the team has /// been recognized (or all other arena members are out), once the captain wins /// the gesture is forwarded to the Android view. /// /// To assign a gesture recognizer to a team, set /// [OneSequenceGestureRecognizer.team] to an instance of [GestureArenaTeam]. class GestureArenaTeam { final Map<int, _CombiningGestureArenaMember> _combiners = <int, _CombiningGestureArenaMember>{}; /// A member that wins on behalf of the entire team. /// /// If not null, when any one of the [GestureArenaTeam] members claims victory /// the captain accepts the gesture. /// If null, the member that claims a victory accepts the gesture. GestureArenaMember? captain; /// Adds a new member to the arena on behalf of this team. /// /// Used by [GestureRecognizer] subclasses that wish to compete in the arena /// using this team. /// /// To assign a gesture recognizer to a team, see /// [OneSequenceGestureRecognizer.team]. GestureArenaEntry add(int pointer, GestureArenaMember member) { final _CombiningGestureArenaMember combiner = _combiners.putIfAbsent( pointer, () => _CombiningGestureArenaMember(this, pointer), ); return combiner._add(pointer, member); } }
flutter/packages/flutter/lib/src/gestures/team.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/gestures/team.dart", "repo_id": "flutter", "token_count": 1828 }
625
// 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. // AUTOGENERATED FILE DO NOT EDIT! // This file was generated by vitool. part of material_animated_icons; // ignore: use_string_in_part_of_directives const _AnimatedIconData _$list_view = _AnimatedIconData( Size(48.0, 48.0), <_PathFrames>[ _PathFrames( opacities: <double>[ 1.0, 1.0, 1.0, 1.0, 1.0, 0.878048780488, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(3.3000000000000016, 35.5), Offset(3.1872491552817053, 35.294662556963694), Offset(2.803584610041825, 34.55708172822131), Offset(2.086762034690722, 32.974965285488736), Offset(1.0562543947134673, 29.85871467131613), Offset(0.3277056784121384, 23.397935591386524), Offset(5.068384450186188, 9.77558673709007), Offset(19.142440865906075, 0.8236301535641601), Offset(28.4986244695124, 0.7512929847205392), Offset(34.03339705415398, 2.550735594111994), Offset(37.52630261515188, 4.563458703685585), Offset(39.83951862260312, 6.397453314812415), Offset(41.420680465862844, 7.960676694252207), Offset(42.52292959864048, 9.247336542718527), Offset(43.29857028685616, 10.277566364406328), Offset(43.843675623946226, 11.078369385731442), Offset(44.22049532021145, 11.67638165937833), Offset(44.47040673191611, 12.096116254351111), Offset(44.62108022189184, 12.359078623996243), Offset(44.69110902782625, 12.484010802427473), ], ), _PathCubicTo( <Offset>[ Offset(3.3000000000000016, 35.5), Offset(3.1872491552817053, 35.294662556963694), Offset(2.803584610041825, 34.55708172822131), Offset(2.086762034690722, 32.974965285488736), Offset(1.0562543947134673, 29.85871467131613), Offset(0.3277056784121384, 23.397935591386524), Offset(5.068384450186188, 9.77558673709007), Offset(19.142440865906075, 0.8236301535641601), Offset(28.4986244695124, 0.7512929847205392), Offset(34.03339705415398, 2.550735594111994), Offset(37.52630261515188, 4.563458703685585), Offset(39.83951862260312, 6.397453314812415), Offset(41.420680465862844, 7.960676694252207), Offset(42.52292959864048, 9.247336542718527), Offset(43.29857028685616, 10.277566364406328), Offset(43.843675623946226, 11.078369385731442), Offset(44.22049532021145, 11.67638165937833), Offset(44.47040673191611, 12.096116254351111), Offset(44.62108022189184, 12.359078623996243), Offset(44.69110902782625, 12.484010802427473), ], <Offset>[ Offset(7.900000000000001, 35.5), Offset(7.787024068249312, 35.34016805150932), Offset(7.398927009112204, 34.7640315658779), Offset(6.654572753845953, 33.51820117713304), Offset(5.505071070263646, 31.02834289744042), Offset(4.290730713340881, 25.733408257149932), Offset(6.941261311200804, 13.977054607189284), Offset(17.78085941259789, 5.217500423156466), Offset(25.541432860040533, 4.274788093964937), Offset(30.30609713874217, 5.246516620191658), Offset(33.39574733179454, 6.587937167668043), Offset(35.489171433369805, 7.892270806391144), Offset(36.94930799941936, 9.040874947505337), Offset(37.985765755731585, 10.005059620498354), Offset(38.72688536686231, 10.787171105652785), Offset(39.254973101552665, 11.400563676461365), Offset(39.62422079973953, 11.861477668143195), Offset(39.87129202785027, 12.186360028903175), Offset(40.02118722421174, 12.390453931063687), Offset(40.091110400688535, 12.487564720144858), ], <Offset>[ Offset(7.900000000000001, 35.5), Offset(7.787024068249312, 35.34016805150932), Offset(7.398927009112204, 34.7640315658779), Offset(6.654572753845953, 33.51820117713304), Offset(5.505071070263646, 31.02834289744042), Offset(4.290730713340881, 25.733408257149932), Offset(6.941261311200804, 13.977054607189284), Offset(17.78085941259789, 5.217500423156466), Offset(25.541432860040533, 4.274788093964937), Offset(30.30609713874217, 5.246516620191658), Offset(33.39574733179454, 6.587937167668043), Offset(35.489171433369805, 7.892270806391144), Offset(36.94930799941936, 9.040874947505337), Offset(37.985765755731585, 10.005059620498354), Offset(38.72688536686231, 10.787171105652785), Offset(39.254973101552665, 11.400563676461365), Offset(39.62422079973953, 11.861477668143195), Offset(39.87129202785027, 12.186360028903175), Offset(40.02118722421174, 12.390453931063687), Offset(40.091110400688535, 12.487564720144858), ], ), _PathCubicTo( <Offset>[ Offset(7.900000000000001, 35.5), Offset(7.787024068249312, 35.34016805150932), Offset(7.398927009112204, 34.7640315658779), Offset(6.654572753845953, 33.51820117713304), Offset(5.505071070263646, 31.02834289744042), Offset(4.290730713340881, 25.733408257149932), Offset(6.941261311200804, 13.977054607189284), Offset(17.78085941259789, 5.217500423156466), Offset(25.541432860040533, 4.274788093964937), Offset(30.30609713874217, 5.246516620191658), Offset(33.39574733179454, 6.587937167668043), Offset(35.489171433369805, 7.892270806391144), Offset(36.94930799941936, 9.040874947505337), Offset(37.985765755731585, 10.005059620498354), Offset(38.72688536686231, 10.787171105652785), Offset(39.254973101552665, 11.400563676461365), Offset(39.62422079973953, 11.861477668143195), Offset(39.87129202785027, 12.186360028903175), Offset(40.02118722421174, 12.390453931063687), Offset(40.091110400688535, 12.487564720144858), ], <Offset>[ Offset(7.900000000000001, 30.900000000000002), Offset(7.832529562794939, 30.740393138541712), Offset(7.605876846768791, 30.168689166807518), Offset(7.19780864549025, 28.950390457977804), Offset(6.674699296387938, 26.57952622189024), Offset(6.626203379104288, 21.770383222221188), Offset(11.14272918130002, 12.104177746174667), Offset(22.174729682190197, 6.579081876464652), Offset(29.06492796928493, 7.231979703436803), Offset(33.00187816482183, 8.973816535603465), Offset(35.420225795777, 10.718492451025382), Offset(36.983988924948534, 12.242617995624466), Offset(38.02950625267249, 13.51224741394882), Offset(38.743488833511414, 14.542223463407256), Offset(39.23649010810877, 15.358856025646629), Offset(39.57716739228259, 15.989266198854928), Offset(39.8093168085044, 16.457752188615107), Offset(39.96153580240233, 16.785474732969014), Offset(40.052562531279186, 16.990346928743786), Offset(40.094664318405925, 17.087563347282572), ], <Offset>[ Offset(7.900000000000001, 30.900000000000002), Offset(7.832529562794939, 30.740393138541712), Offset(7.605876846768791, 30.168689166807518), Offset(7.19780864549025, 28.950390457977804), Offset(6.674699296387938, 26.57952622189024), Offset(6.626203379104288, 21.770383222221188), Offset(11.14272918130002, 12.104177746174667), Offset(22.174729682190197, 6.579081876464652), Offset(29.06492796928493, 7.231979703436803), Offset(33.00187816482183, 8.973816535603465), Offset(35.420225795777, 10.718492451025382), Offset(36.983988924948534, 12.242617995624466), Offset(38.02950625267249, 13.51224741394882), Offset(38.743488833511414, 14.542223463407256), Offset(39.23649010810877, 15.358856025646629), Offset(39.57716739228259, 15.989266198854928), Offset(39.8093168085044, 16.457752188615107), Offset(39.96153580240233, 16.785474732969014), Offset(40.052562531279186, 16.990346928743786), Offset(40.094664318405925, 17.087563347282572), ], ), _PathCubicTo( <Offset>[ Offset(7.900000000000001, 30.900000000000002), Offset(7.832529562794939, 30.740393138541712), Offset(7.605876846768791, 30.168689166807518), Offset(7.19780864549025, 28.950390457977804), Offset(6.674699296387938, 26.57952622189024), Offset(6.626203379104288, 21.770383222221188), Offset(11.14272918130002, 12.104177746174667), Offset(22.174729682190197, 6.579081876464652), Offset(29.06492796928493, 7.231979703436803), Offset(33.00187816482183, 8.973816535603465), Offset(35.420225795777, 10.718492451025382), Offset(36.983988924948534, 12.242617995624466), Offset(38.02950625267249, 13.51224741394882), Offset(38.743488833511414, 14.542223463407256), Offset(39.23649010810877, 15.358856025646629), Offset(39.57716739228259, 15.989266198854928), Offset(39.8093168085044, 16.457752188615107), Offset(39.96153580240233, 16.785474732969014), Offset(40.052562531279186, 16.990346928743786), Offset(40.094664318405925, 17.087563347282572), ], <Offset>[ Offset(3.3000000000000016, 30.900000000000002), Offset(3.2327546498273323, 30.694887643996086), Offset(3.0105344476984124, 29.96173932915093), Offset(2.6299979263350193, 28.407154566333507), Offset(2.2258826208377593, 25.40989799576595), Offset(2.663178344175545, 19.43491055645778), Offset(9.269852320285402, 7.902709876075453), Offset(23.53631113549838, 2.185211606872347), Offset(32.0221195787568, 3.708484594192405), Offset(36.729178080233645, 6.278035509523802), Offset(39.55078107913434, 8.694013987042924), Offset(41.33433611418185, 10.747800504045737), Offset(42.500878719115974, 12.43204916069569), Offset(43.28065267642031, 13.784500385627428), Offset(43.80817502810262, 14.849251284400172), Offset(44.16586991467615, 15.667071908125004), Offset(44.405591328976314, 16.272656179850244), Offset(44.56065050646817, 16.695230958416946), Offset(44.65245552895929, 16.95897162167634), Offset(44.69466294554364, 17.084009429565185), ], <Offset>[ Offset(3.3000000000000016, 30.900000000000002), Offset(3.2327546498273323, 30.694887643996086), Offset(3.0105344476984124, 29.96173932915093), Offset(2.6299979263350193, 28.407154566333507), Offset(2.2258826208377593, 25.40989799576595), Offset(2.663178344175545, 19.43491055645778), Offset(9.269852320285402, 7.902709876075453), Offset(23.53631113549838, 2.185211606872347), Offset(32.0221195787568, 3.708484594192405), Offset(36.729178080233645, 6.278035509523802), Offset(39.55078107913434, 8.694013987042924), Offset(41.33433611418185, 10.747800504045737), Offset(42.500878719115974, 12.43204916069569), Offset(43.28065267642031, 13.784500385627428), Offset(43.80817502810262, 14.849251284400172), Offset(44.16586991467615, 15.667071908125004), Offset(44.405591328976314, 16.272656179850244), Offset(44.56065050646817, 16.695230958416946), Offset(44.65245552895929, 16.95897162167634), Offset(44.69466294554364, 17.084009429565185), ], ), _PathCubicTo( <Offset>[ Offset(3.3000000000000016, 30.900000000000002), Offset(3.2327546498273323, 30.694887643996086), Offset(3.0105344476984124, 29.96173932915093), Offset(2.6299979263350193, 28.407154566333507), Offset(2.2258826208377593, 25.40989799576595), Offset(2.663178344175545, 19.43491055645778), Offset(9.269852320285402, 7.902709876075453), Offset(23.53631113549838, 2.185211606872347), Offset(32.0221195787568, 3.708484594192405), Offset(36.729178080233645, 6.278035509523802), Offset(39.55078107913434, 8.694013987042924), Offset(41.33433611418185, 10.747800504045737), Offset(42.500878719115974, 12.43204916069569), Offset(43.28065267642031, 13.784500385627428), Offset(43.80817502810262, 14.849251284400172), Offset(44.16586991467615, 15.667071908125004), Offset(44.405591328976314, 16.272656179850244), Offset(44.56065050646817, 16.695230958416946), Offset(44.65245552895929, 16.95897162167634), Offset(44.69466294554364, 17.084009429565185), ], <Offset>[ Offset(3.3000000000000016, 35.5), Offset(3.1872491552817053, 35.294662556963694), Offset(2.803584610041825, 34.55708172822131), Offset(2.086762034690722, 32.974965285488736), Offset(1.0562543947134673, 29.85871467131613), Offset(0.3277056784121384, 23.397935591386524), Offset(5.068384450186188, 9.77558673709007), Offset(19.142440865906075, 0.8236301535641601), Offset(28.4986244695124, 0.7512929847205392), Offset(34.03339705415398, 2.550735594111994), Offset(37.52630261515188, 4.563458703685585), Offset(39.83951862260312, 6.397453314812415), Offset(41.420680465862844, 7.960676694252207), Offset(42.52292959864048, 9.247336542718527), Offset(43.29857028685616, 10.277566364406328), Offset(43.843675623946226, 11.078369385731442), Offset(44.22049532021145, 11.67638165937833), Offset(44.47040673191611, 12.096116254351111), Offset(44.62108022189184, 12.359078623996243), Offset(44.69110902782625, 12.484010802427473), ], <Offset>[ Offset(3.3000000000000016, 35.5), Offset(3.1872491552817053, 35.294662556963694), Offset(2.803584610041825, 34.55708172822131), Offset(2.086762034690722, 32.974965285488736), Offset(1.0562543947134673, 29.85871467131613), Offset(0.3277056784121384, 23.397935591386524), Offset(5.068384450186188, 9.77558673709007), Offset(19.142440865906075, 0.8236301535641601), Offset(28.4986244695124, 0.7512929847205392), Offset(34.03339705415398, 2.550735594111994), Offset(37.52630261515188, 4.563458703685585), Offset(39.83951862260312, 6.397453314812415), Offset(41.420680465862844, 7.960676694252207), Offset(42.52292959864048, 9.247336542718527), Offset(43.29857028685616, 10.277566364406328), Offset(43.843675623946226, 11.078369385731442), Offset(44.22049532021145, 11.67638165937833), Offset(44.47040673191611, 12.096116254351111), Offset(44.62108022189184, 12.359078623996243), Offset(44.69110902782625, 12.484010802427473), ], ), _PathClose( ), ], ), _PathFrames( opacities: <double>[ 1.0, 1.0, 1.0, 1.0, 1.0, 0.878048780488, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(3.3000000000000016, 17.1), Offset(3.3692711334642134, 16.89556290509327), Offset(3.631383960668174, 16.17571213193979), Offset(4.25970560126791, 14.703722408867815), Offset(5.734767299210637, 12.063447969115414), Offset(9.669596341465768, 7.545835451671554), Offset(21.874255930583047, 2.2840792930316054), Offset(36.7179219442753, 6.269955966796905), Offset(42.592604906489996, 12.580059422608004), Offset(44.81652115847264, 17.459935255759223), Offset(45.624216471081716, 21.085679837114938), Offset(45.81878858891804, 23.798842071745703), Offset(45.74147347887537, 25.84616656002614), Offset(45.55382190975979, 27.395991914354134), Offset(45.33698925184199, 28.564306044381702), Offset(45.13245278686591, 29.433179475305685), Offset(44.960879355270905, 30.061479741265988), Offset(44.831381830124364, 30.492575070614457), Offset(44.74658145016162, 30.758650614716647), Offset(44.7053246986958, 30.884005310978335), ], ), _PathCubicTo( <Offset>[ Offset(3.3000000000000016, 17.1), Offset(3.3692711334642134, 16.89556290509327), Offset(3.631383960668174, 16.17571213193979), Offset(4.25970560126791, 14.703722408867815), Offset(5.734767299210637, 12.063447969115414), Offset(9.669596341465768, 7.545835451671554), Offset(21.874255930583047, 2.2840792930316054), Offset(36.7179219442753, 6.269955966796905), Offset(42.592604906489996, 12.580059422608004), Offset(44.81652115847264, 17.459935255759223), Offset(45.624216471081716, 21.085679837114938), Offset(45.81878858891804, 23.798842071745703), Offset(45.74147347887537, 25.84616656002614), Offset(45.55382190975979, 27.395991914354134), Offset(45.33698925184199, 28.564306044381702), Offset(45.13245278686591, 29.433179475305685), Offset(44.960879355270905, 30.061479741265988), Offset(44.831381830124364, 30.492575070614457), Offset(44.74658145016162, 30.758650614716647), Offset(44.7053246986958, 30.884005310978335), ], <Offset>[ Offset(7.900000000000001, 17.1), Offset(7.96904604643182, 16.941068399638898), Offset(8.226726359738553, 16.382661969596377), Offset(8.82751632042314, 15.246958300512112), Offset(10.183583974760815, 13.233076195239708), Offset(13.63262137639451, 9.88130811743496), Offset(23.747132791597664, 6.48554716313082), Offset(35.35634049096711, 10.66382623638921), Offset(39.63541329701813, 16.103554531852403), Offset(41.08922124306083, 20.155716281838888), Offset(41.49366118772438, 23.1101583010974), Offset(41.46844139968472, 25.293659563324432), Offset(41.27010101243189, 26.92636481327927), Offset(41.016658066850894, 28.15371499213396), Offset(40.76530433184814, 29.07391078562816), Offset(40.54375026447235, 29.75537376603561), Offset(40.36460483479899, 30.24657575003085), Offset(40.232267126058524, 30.582818845166525), Offset(40.14668845248152, 30.790025921784093), Offset(40.10532607155808, 30.88755922869572), ], <Offset>[ Offset(7.900000000000001, 17.1), Offset(7.96904604643182, 16.941068399638898), Offset(8.226726359738553, 16.382661969596377), Offset(8.82751632042314, 15.246958300512112), Offset(10.183583974760815, 13.233076195239708), Offset(13.63262137639451, 9.88130811743496), Offset(23.747132791597664, 6.48554716313082), Offset(35.35634049096711, 10.66382623638921), Offset(39.63541329701813, 16.103554531852403), Offset(41.08922124306083, 20.155716281838888), Offset(41.49366118772438, 23.1101583010974), Offset(41.46844139968472, 25.293659563324432), Offset(41.27010101243189, 26.92636481327927), Offset(41.016658066850894, 28.15371499213396), Offset(40.76530433184814, 29.07391078562816), Offset(40.54375026447235, 29.75537376603561), Offset(40.36460483479899, 30.24657575003085), Offset(40.232267126058524, 30.582818845166525), Offset(40.14668845248152, 30.790025921784093), Offset(40.10532607155808, 30.88755922869572), ], ), _PathCubicTo( <Offset>[ Offset(7.900000000000001, 17.1), Offset(7.96904604643182, 16.941068399638898), Offset(8.226726359738553, 16.382661969596377), Offset(8.82751632042314, 15.246958300512112), Offset(10.183583974760815, 13.233076195239708), Offset(13.63262137639451, 9.88130811743496), Offset(23.747132791597664, 6.48554716313082), Offset(35.35634049096711, 10.66382623638921), Offset(39.63541329701813, 16.103554531852403), Offset(41.08922124306083, 20.155716281838888), Offset(41.49366118772438, 23.1101583010974), Offset(41.46844139968472, 25.293659563324432), Offset(41.27010101243189, 26.92636481327927), Offset(41.016658066850894, 28.15371499213396), Offset(40.76530433184814, 29.07391078562816), Offset(40.54375026447235, 29.75537376603561), Offset(40.36460483479899, 30.24657575003085), Offset(40.232267126058524, 30.582818845166525), Offset(40.14668845248152, 30.790025921784093), Offset(40.10532607155808, 30.88755922869572), ], <Offset>[ Offset(7.900000000000001, 12.5), Offset(8.014551540977447, 12.34129348667129), Offset(8.43367619739514, 11.787319570526), Offset(9.370752212067437, 10.679147581356883), Offset(11.353212200885107, 8.78425951968953), Offset(15.968094042157917, 5.918283082506218), Offset(27.94860066169688, 4.6126703021162045), Offset(39.75021076055942, 12.025407689697397), Offset(43.158908406262526, 19.060746141324266), Offset(43.78500226914049, 23.883016197250694), Offset(43.51813965170684, 27.24071358445474), Offset(42.96325889126345, 29.644006752557758), Offset(42.35029926568502, 31.397737279722755), Offset(41.77438114463072, 32.69087883504286), Offset(41.2749090730946, 33.64559570562201), Offset(40.865944555202276, 34.34407628842917), Offset(40.549700843563855, 34.842850270502765), Offset(40.32251090061059, 35.18193354923236), Offset(40.17806375954897, 35.38991891946419), Offset(40.10887998927547, 35.48755785583344), ], <Offset>[ Offset(7.900000000000001, 12.5), Offset(8.014551540977447, 12.34129348667129), Offset(8.43367619739514, 11.787319570526), Offset(9.370752212067437, 10.679147581356883), Offset(11.353212200885107, 8.78425951968953), Offset(15.968094042157917, 5.918283082506218), Offset(27.94860066169688, 4.6126703021162045), Offset(39.75021076055942, 12.025407689697397), Offset(43.158908406262526, 19.060746141324266), Offset(43.78500226914049, 23.883016197250694), Offset(43.51813965170684, 27.24071358445474), Offset(42.96325889126345, 29.644006752557758), Offset(42.35029926568502, 31.397737279722755), Offset(41.77438114463072, 32.69087883504286), Offset(41.2749090730946, 33.64559570562201), Offset(40.865944555202276, 34.34407628842917), Offset(40.549700843563855, 34.842850270502765), Offset(40.32251090061059, 35.18193354923236), Offset(40.17806375954897, 35.38991891946419), Offset(40.10887998927547, 35.48755785583344), ], ), _PathCubicTo( <Offset>[ Offset(7.900000000000001, 12.5), Offset(8.014551540977447, 12.34129348667129), Offset(8.43367619739514, 11.787319570526), Offset(9.370752212067437, 10.679147581356883), Offset(11.353212200885107, 8.78425951968953), Offset(15.968094042157917, 5.918283082506218), Offset(27.94860066169688, 4.6126703021162045), Offset(39.75021076055942, 12.025407689697397), Offset(43.158908406262526, 19.060746141324266), Offset(43.78500226914049, 23.883016197250694), Offset(43.51813965170684, 27.24071358445474), Offset(42.96325889126345, 29.644006752557758), Offset(42.35029926568502, 31.397737279722755), Offset(41.77438114463072, 32.69087883504286), Offset(41.2749090730946, 33.64559570562201), Offset(40.865944555202276, 34.34407628842917), Offset(40.549700843563855, 34.842850270502765), Offset(40.32251090061059, 35.18193354923236), Offset(40.17806375954897, 35.38991891946419), Offset(40.10887998927547, 35.48755785583344), ], <Offset>[ Offset(3.3000000000000016, 12.5), Offset(3.4147766280098404, 12.295787992125664), Offset(3.8383337983247614, 11.580369732869412), Offset(4.802941492912208, 10.135911689712586), Offset(6.904395525334929, 7.614631293565236), Offset(12.005069007229174, 3.5828104167428108), Offset(26.075723800682262, 0.4112024320169896), Offset(41.1117922138676, 7.631537420105092), Offset(46.11610001573439, 15.537251032079869), Offset(47.512302184552304, 21.18723517117103), Offset(47.64869493506418, 25.216235120472277), Offset(47.31360608049677, 28.14918926097903), Offset(46.8216717321285, 30.317539026469625), Offset(46.31154498753962, 31.933155757263034), Offset(45.84659399308845, 33.13599096437555), Offset(45.45464707759584, 34.021881997699246), Offset(45.14597536403577, 34.6577542617379), Offset(44.92162560467643, 35.0916897746803), Offset(44.77795675722907, 35.358543612396744), Offset(44.70887861641319, 35.48400393811605), ], <Offset>[ Offset(3.3000000000000016, 12.5), Offset(3.4147766280098404, 12.295787992125664), Offset(3.8383337983247614, 11.580369732869412), Offset(4.802941492912208, 10.135911689712586), Offset(6.904395525334929, 7.614631293565236), Offset(12.005069007229174, 3.5828104167428108), Offset(26.075723800682262, 0.4112024320169896), Offset(41.1117922138676, 7.631537420105092), Offset(46.11610001573439, 15.537251032079869), Offset(47.512302184552304, 21.18723517117103), Offset(47.64869493506418, 25.216235120472277), Offset(47.31360608049677, 28.14918926097903), Offset(46.8216717321285, 30.317539026469625), Offset(46.31154498753962, 31.933155757263034), Offset(45.84659399308845, 33.13599096437555), Offset(45.45464707759584, 34.021881997699246), Offset(45.14597536403577, 34.6577542617379), Offset(44.92162560467643, 35.0916897746803), Offset(44.77795675722907, 35.358543612396744), Offset(44.70887861641319, 35.48400393811605), ], ), _PathCubicTo( <Offset>[ Offset(3.3000000000000016, 12.5), Offset(3.4147766280098404, 12.295787992125664), Offset(3.8383337983247614, 11.580369732869412), Offset(4.802941492912208, 10.135911689712586), Offset(6.904395525334929, 7.614631293565236), Offset(12.005069007229174, 3.5828104167428108), Offset(26.075723800682262, 0.4112024320169896), Offset(41.1117922138676, 7.631537420105092), Offset(46.11610001573439, 15.537251032079869), Offset(47.512302184552304, 21.18723517117103), Offset(47.64869493506418, 25.216235120472277), Offset(47.31360608049677, 28.14918926097903), Offset(46.8216717321285, 30.317539026469625), Offset(46.31154498753962, 31.933155757263034), Offset(45.84659399308845, 33.13599096437555), Offset(45.45464707759584, 34.021881997699246), Offset(45.14597536403577, 34.6577542617379), Offset(44.92162560467643, 35.0916897746803), Offset(44.77795675722907, 35.358543612396744), Offset(44.70887861641319, 35.48400393811605), ], <Offset>[ Offset(3.3000000000000016, 17.1), Offset(3.3692711334642134, 16.89556290509327), Offset(3.631383960668174, 16.17571213193979), Offset(4.25970560126791, 14.703722408867815), Offset(5.734767299210637, 12.063447969115414), Offset(9.669596341465768, 7.545835451671554), Offset(21.874255930583047, 2.2840792930316054), Offset(36.7179219442753, 6.269955966796905), Offset(42.592604906489996, 12.580059422608004), Offset(44.81652115847264, 17.459935255759223), Offset(45.624216471081716, 21.085679837114938), Offset(45.81878858891804, 23.798842071745703), Offset(45.74147347887537, 25.84616656002614), Offset(45.55382190975979, 27.395991914354134), Offset(45.33698925184199, 28.564306044381702), Offset(45.13245278686591, 29.433179475305685), Offset(44.960879355270905, 30.061479741265988), Offset(44.831381830124364, 30.492575070614457), Offset(44.74658145016162, 30.758650614716647), Offset(44.7053246986958, 30.884005310978335), ], <Offset>[ Offset(3.3000000000000016, 17.1), Offset(3.3692711334642134, 16.89556290509327), Offset(3.631383960668174, 16.17571213193979), Offset(4.25970560126791, 14.703722408867815), Offset(5.734767299210637, 12.063447969115414), Offset(9.669596341465768, 7.545835451671554), Offset(21.874255930583047, 2.2840792930316054), Offset(36.7179219442753, 6.269955966796905), Offset(42.592604906489996, 12.580059422608004), Offset(44.81652115847264, 17.459935255759223), Offset(45.624216471081716, 21.085679837114938), Offset(45.81878858891804, 23.798842071745703), Offset(45.74147347887537, 25.84616656002614), Offset(45.55382190975979, 27.395991914354134), Offset(45.33698925184199, 28.564306044381702), Offset(45.13245278686591, 29.433179475305685), Offset(44.960879355270905, 30.061479741265988), Offset(44.831381830124364, 30.492575070614457), Offset(44.74658145016162, 30.758650614716647), Offset(44.7053246986958, 30.884005310978335), ], ), _PathClose( ), ], ), _PathFrames( opacities: <double>[ 1.0, 1.0, 1.0, 1.0, 1.0, 0.878048780488, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(3.3000000000000016, 26.3), Offset(3.2782601443729593, 26.095112731028483), Offset(3.217484285354999, 25.366396930080548), Offset(3.1732338179793156, 23.839343847178277), Offset(3.3955108469620523, 20.961081320215772), Offset(4.998651009938952, 15.471885521529039), Offset(13.471320190384617, 6.029833015060841), Offset(27.930181405090686, 3.5467930601805335), Offset(35.545614688001194, 6.665676203664274), Offset(39.42495910631331, 10.005335424935609), Offset(41.57525954311679, 12.824569270400263), Offset(42.82915360576058, 15.098147693279058), Offset(43.58107697236911, 16.903421627139174), Offset(44.03837575420013, 18.32166422853633), Offset(44.31777976934908, 19.420936204394014), Offset(44.48806420540607, 20.25577443051856), Offset(44.59068733774117, 20.86893070032216), Offset(44.650894281020236, 21.294345662482787), Offset(44.68383083602673, 21.558864619356445), Offset(44.698216863261024, 21.684008056702904), ], ), _PathCubicTo( <Offset>[ Offset(3.3000000000000016, 26.3), Offset(3.2782601443729593, 26.095112731028483), Offset(3.217484285354999, 25.366396930080548), Offset(3.1732338179793156, 23.839343847178277), Offset(3.3955108469620523, 20.961081320215772), Offset(4.998651009938952, 15.471885521529039), Offset(13.471320190384617, 6.029833015060841), Offset(27.930181405090686, 3.5467930601805335), Offset(35.545614688001194, 6.665676203664274), Offset(39.42495910631331, 10.005335424935609), Offset(41.57525954311679, 12.824569270400263), Offset(42.82915360576058, 15.098147693279058), Offset(43.58107697236911, 16.903421627139174), Offset(44.03837575420013, 18.32166422853633), Offset(44.31777976934908, 19.420936204394014), Offset(44.48806420540607, 20.25577443051856), Offset(44.59068733774117, 20.86893070032216), Offset(44.650894281020236, 21.294345662482787), Offset(44.68383083602673, 21.558864619356445), Offset(44.698216863261024, 21.684008056702904), ], <Offset>[ Offset(7.900000000000001, 26.3), Offset(7.878035057340566, 26.14061822557411), Offset(7.812826684425378, 25.573346767737135), Offset(7.741044537134545, 24.382579738822574), Offset(7.844327522512231, 22.130709546340064), Offset(8.961676044867694, 17.807358187292447), Offset(15.344197051399235, 10.231300885160056), Offset(26.568599951782502, 7.940663329772839), Offset(32.58842307852933, 10.189171312908673), Offset(35.6976591909015, 12.701116451015272), Offset(37.444704259759455, 14.84904773438272), Offset(38.47880641652726, 16.592965184857785), Offset(39.10970450592563, 17.983619880392304), Offset(39.501211911291236, 19.079387306316157), Offset(39.74609484935523, 19.930540945640473), Offset(39.89936168301251, 20.577968721248485), Offset(39.99441281726926, 21.054026709087022), Offset(40.051779576954395, 21.384589437034855), Offset(40.08393783834663, 21.59023992642389), Offset(40.09821823612331, 21.68756197442029), ], <Offset>[ Offset(7.900000000000001, 26.3), Offset(7.878035057340566, 26.14061822557411), Offset(7.812826684425378, 25.573346767737135), Offset(7.741044537134545, 24.382579738822574), Offset(7.844327522512231, 22.130709546340064), Offset(8.961676044867694, 17.807358187292447), Offset(15.344197051399235, 10.231300885160056), Offset(26.568599951782502, 7.940663329772839), Offset(32.58842307852933, 10.189171312908673), Offset(35.6976591909015, 12.701116451015272), Offset(37.444704259759455, 14.84904773438272), Offset(38.47880641652726, 16.592965184857785), Offset(39.10970450592563, 17.983619880392304), Offset(39.501211911291236, 19.079387306316157), Offset(39.74609484935523, 19.930540945640473), Offset(39.89936168301251, 20.577968721248485), Offset(39.99441281726926, 21.054026709087022), Offset(40.051779576954395, 21.384589437034855), Offset(40.08393783834663, 21.59023992642389), Offset(40.09821823612331, 21.68756197442029), ], ), _PathCubicTo( <Offset>[ Offset(7.900000000000001, 26.3), Offset(7.878035057340566, 26.14061822557411), Offset(7.812826684425378, 25.573346767737135), Offset(7.741044537134545, 24.382579738822574), Offset(7.844327522512231, 22.130709546340064), Offset(8.961676044867694, 17.807358187292447), Offset(15.344197051399235, 10.231300885160056), Offset(26.568599951782502, 7.940663329772839), Offset(32.58842307852933, 10.189171312908673), Offset(35.6976591909015, 12.701116451015272), Offset(37.444704259759455, 14.84904773438272), Offset(38.47880641652726, 16.592965184857785), Offset(39.10970450592563, 17.983619880392304), Offset(39.501211911291236, 19.079387306316157), Offset(39.74609484935523, 19.930540945640473), Offset(39.89936168301251, 20.577968721248485), Offset(39.99441281726926, 21.054026709087022), Offset(40.051779576954395, 21.384589437034855), Offset(40.08393783834663, 21.59023992642389), Offset(40.09821823612331, 21.68756197442029), ], <Offset>[ Offset(7.900000000000001, 21.7), Offset(7.923540551886193, 21.5408433126065), Offset(8.019776522081965, 20.97800436866676), Offset(8.284280428778843, 19.814769019667345), Offset(9.013955748636523, 17.681892870789884), Offset(11.2971487106311, 13.844333152363703), Offset(19.54566492149845, 8.358424024145439), Offset(30.962470221374808, 9.302244783081026), Offset(36.111918187773725, 13.146362922380538), Offset(38.39344021698116, 16.42841636642708), Offset(39.469182723741916, 18.97960301774006), Offset(39.97362390810599, 20.94331237409111), Offset(40.18990275917876, 22.454992346835787), Offset(40.258934989071065, 23.616551149225057), Offset(40.25569959060169, 24.50222586563432), Offset(40.22155597374243, 25.166671243642046), Offset(40.17950882603412, 25.650301229558934), Offset(40.14202335150646, 25.98370414110069), Offset(40.11531314541408, 26.190132924103988), Offset(40.1017721538407, 26.287560601558003), ], <Offset>[ Offset(7.900000000000001, 21.7), Offset(7.923540551886193, 21.5408433126065), Offset(8.019776522081965, 20.97800436866676), Offset(8.284280428778843, 19.814769019667345), Offset(9.013955748636523, 17.681892870789884), Offset(11.2971487106311, 13.844333152363703), Offset(19.54566492149845, 8.358424024145439), Offset(30.962470221374808, 9.302244783081026), Offset(36.111918187773725, 13.146362922380538), Offset(38.39344021698116, 16.42841636642708), Offset(39.469182723741916, 18.97960301774006), Offset(39.97362390810599, 20.94331237409111), Offset(40.18990275917876, 22.454992346835787), Offset(40.258934989071065, 23.616551149225057), Offset(40.25569959060169, 24.50222586563432), Offset(40.22155597374243, 25.166671243642046), Offset(40.17950882603412, 25.650301229558934), Offset(40.14202335150646, 25.98370414110069), Offset(40.11531314541408, 26.190132924103988), Offset(40.1017721538407, 26.287560601558003), ], ), _PathCubicTo( <Offset>[ Offset(7.900000000000001, 21.7), Offset(7.923540551886193, 21.5408433126065), Offset(8.019776522081965, 20.97800436866676), Offset(8.284280428778843, 19.814769019667345), Offset(9.013955748636523, 17.681892870789884), Offset(11.2971487106311, 13.844333152363703), Offset(19.54566492149845, 8.358424024145439), Offset(30.962470221374808, 9.302244783081026), Offset(36.111918187773725, 13.146362922380538), Offset(38.39344021698116, 16.42841636642708), Offset(39.469182723741916, 18.97960301774006), Offset(39.97362390810599, 20.94331237409111), Offset(40.18990275917876, 22.454992346835787), Offset(40.258934989071065, 23.616551149225057), Offset(40.25569959060169, 24.50222586563432), Offset(40.22155597374243, 25.166671243642046), Offset(40.17950882603412, 25.650301229558934), Offset(40.14202335150646, 25.98370414110069), Offset(40.11531314541408, 26.190132924103988), Offset(40.1017721538407, 26.287560601558003), ], <Offset>[ Offset(3.3000000000000016, 21.7), Offset(3.3237656389185863, 21.495337818060875), Offset(3.4244341230115865, 20.771054531010172), Offset(3.716469709623613, 19.271533128023048), Offset(4.565139073086344, 16.512264644665592), Offset(7.334123675702358, 11.508860486600296), Offset(17.672788060483832, 4.156956154046225), Offset(32.32405167468299, 4.90837451348872), Offset(39.06910979724559, 9.62286781313614), Offset(42.120740132392974, 13.732635340347416), Offset(43.599738007099255, 16.9551245537576), Offset(44.32397109733931, 19.44849488251238), Offset(44.66127522562224, 21.374794093582658), Offset(44.79609883197996, 22.85882807144523), Offset(44.827384510595536, 23.99262112438786), Offset(44.810258496135994, 24.84447695291212), Offset(44.77578334650604, 25.465205220794072), Offset(44.7411380555723, 25.893460366548624), Offset(44.71520614309418, 26.158757617036542), Offset(44.701770780978414, 26.284006683840616), ], <Offset>[ Offset(3.3000000000000016, 21.7), Offset(3.3237656389185863, 21.495337818060875), Offset(3.4244341230115865, 20.771054531010172), Offset(3.716469709623613, 19.271533128023048), Offset(4.565139073086344, 16.512264644665592), Offset(7.334123675702358, 11.508860486600296), Offset(17.672788060483832, 4.156956154046225), Offset(32.32405167468299, 4.90837451348872), Offset(39.06910979724559, 9.62286781313614), Offset(42.120740132392974, 13.732635340347416), Offset(43.599738007099255, 16.9551245537576), Offset(44.32397109733931, 19.44849488251238), Offset(44.66127522562224, 21.374794093582658), Offset(44.79609883197996, 22.85882807144523), Offset(44.827384510595536, 23.99262112438786), Offset(44.810258496135994, 24.84447695291212), Offset(44.77578334650604, 25.465205220794072), Offset(44.7411380555723, 25.893460366548624), Offset(44.71520614309418, 26.158757617036542), Offset(44.701770780978414, 26.284006683840616), ], ), _PathCubicTo( <Offset>[ Offset(3.3000000000000016, 21.7), Offset(3.3237656389185863, 21.495337818060875), Offset(3.4244341230115865, 20.771054531010172), Offset(3.716469709623613, 19.271533128023048), Offset(4.565139073086344, 16.512264644665592), Offset(7.334123675702358, 11.508860486600296), Offset(17.672788060483832, 4.156956154046225), Offset(32.32405167468299, 4.90837451348872), Offset(39.06910979724559, 9.62286781313614), Offset(42.120740132392974, 13.732635340347416), Offset(43.599738007099255, 16.9551245537576), Offset(44.32397109733931, 19.44849488251238), Offset(44.66127522562224, 21.374794093582658), Offset(44.79609883197996, 22.85882807144523), Offset(44.827384510595536, 23.99262112438786), Offset(44.810258496135994, 24.84447695291212), Offset(44.77578334650604, 25.465205220794072), Offset(44.7411380555723, 25.893460366548624), Offset(44.71520614309418, 26.158757617036542), Offset(44.701770780978414, 26.284006683840616), ], <Offset>[ Offset(3.3000000000000016, 26.3), Offset(3.2782601443729593, 26.095112731028483), Offset(3.217484285354999, 25.366396930080548), Offset(3.1732338179793156, 23.839343847178277), Offset(3.3955108469620523, 20.961081320215772), Offset(4.998651009938952, 15.471885521529039), Offset(13.471320190384617, 6.029833015060841), Offset(27.930181405090686, 3.5467930601805335), Offset(35.545614688001194, 6.665676203664274), Offset(39.42495910631331, 10.005335424935609), Offset(41.57525954311679, 12.824569270400263), Offset(42.82915360576058, 15.098147693279058), Offset(43.58107697236911, 16.903421627139174), Offset(44.03837575420013, 18.32166422853633), Offset(44.31777976934908, 19.420936204394014), Offset(44.48806420540607, 20.25577443051856), Offset(44.59068733774117, 20.86893070032216), Offset(44.650894281020236, 21.294345662482787), Offset(44.68383083602673, 21.558864619356445), Offset(44.698216863261024, 21.684008056702904), ], <Offset>[ Offset(3.3000000000000016, 26.3), Offset(3.2782601443729593, 26.095112731028483), Offset(3.217484285354999, 25.366396930080548), Offset(3.1732338179793156, 23.839343847178277), Offset(3.3955108469620523, 20.961081320215772), Offset(4.998651009938952, 15.471885521529039), Offset(13.471320190384617, 6.029833015060841), Offset(27.930181405090686, 3.5467930601805335), Offset(35.545614688001194, 6.665676203664274), Offset(39.42495910631331, 10.005335424935609), Offset(41.57525954311679, 12.824569270400263), Offset(42.82915360576058, 15.098147693279058), Offset(43.58107697236911, 16.903421627139174), Offset(44.03837575420013, 18.32166422853633), Offset(44.31777976934908, 19.420936204394014), Offset(44.48806420540607, 20.25577443051856), Offset(44.59068733774117, 20.86893070032216), Offset(44.650894281020236, 21.294345662482787), Offset(44.68383083602673, 21.558864619356445), Offset(44.698216863261024, 21.684008056702904), ], ), _PathClose( ), ], ), _PathFrames( opacities: <double>[ 1.0, 1.0, 1.0, 1.0, 1.0, 0.878048780488, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(12.5, 35.5), Offset(12.386798981216916, 35.38567354605495), Offset(11.994269408182586, 34.97098140353448), Offset(11.222383473001184, 34.06143706877733), Offset(9.953887745813823, 32.19797112356471), Offset(8.253755748269624, 28.068880922913333), Offset(8.81413817221542, 18.1785224772885), Offset(16.419277959289705, 9.611370692748771), Offset(22.584241250568667, 7.798283203209337), Offset(26.57879722333036, 7.942297646271321), Offset(29.2651920484372, 8.612415631650505), Offset(31.13882424413648, 9.387088297969871), Offset(32.47793553297588, 10.121073200758469), Offset(33.44860191282268, 10.762782698278183), Offset(34.15520044686847, 11.296775846899239), Offset(34.666270579159104, 11.72275796719129), Offset(35.027946279267624, 12.046573676908062), Offset(35.27217732378443, 12.276603803455243), Offset(35.42129422653164, 12.421829238131133), Offset(35.49111177355083, 12.491118637862245), ], ), _PathCubicTo( <Offset>[ Offset(12.5, 35.5), Offset(12.386798981216916, 35.38567354605495), Offset(11.994269408182586, 34.97098140353448), Offset(11.222383473001184, 34.06143706877733), Offset(9.953887745813823, 32.19797112356471), Offset(8.253755748269624, 28.068880922913333), Offset(8.81413817221542, 18.1785224772885), Offset(16.419277959289705, 9.611370692748771), Offset(22.584241250568667, 7.798283203209337), Offset(26.57879722333036, 7.942297646271321), Offset(29.2651920484372, 8.612415631650505), Offset(31.13882424413648, 9.387088297969871), Offset(32.47793553297588, 10.121073200758469), Offset(33.44860191282268, 10.762782698278183), Offset(34.15520044686847, 11.296775846899239), Offset(34.666270579159104, 11.72275796719129), Offset(35.027946279267624, 12.046573676908062), Offset(35.27217732378443, 12.276603803455243), Offset(35.42129422653164, 12.421829238131133), Offset(35.49111177355083, 12.491118637862245), ], <Offset>[ Offset(44.699999999999996, 35.5), Offset(44.58522337199017, 35.70421200787435), Offset(44.161666201675246, 36.41963026713059), Offset(43.197058507087796, 37.86408831028741), Offset(41.09560447466507, 40.38536870643476), Offset(35.994930992770826, 44.41718958325718), Offset(21.92427619931773, 47.58879756798301), Offset(6.8882077861324005, 40.36846257989491), Offset(1.8838999842656072, 32.46274896792012), Offset(0.4876978154477065, 26.81276482882897), Offset(0.3513050649358309, 22.783764879527716), Offset(0.6863939195032227, 19.85081073902098), Offset(1.1783282678714926, 17.682460973530382), Offset(1.6884550124603805, 16.066844242736977), Offset(2.1534060069115526, 14.864009035624443), Offset(2.5453529224041667, 13.978118002300755), Offset(2.854024635964233, 13.34224573826211), Offset(3.0783743953235785, 12.9083102253197), Offset(3.222043242770944, 12.641456387603249), Offset(3.2911213835868267, 12.515996061883946), ], <Offset>[ Offset(44.699999999999996, 35.5), Offset(44.58522337199017, 35.70421200787435), Offset(44.161666201675246, 36.41963026713059), Offset(43.197058507087796, 37.86408831028741), Offset(41.09560447466507, 40.38536870643476), Offset(35.994930992770826, 44.41718958325718), Offset(21.92427619931773, 47.58879756798301), Offset(6.8882077861324005, 40.36846257989491), Offset(1.8838999842656072, 32.46274896792012), Offset(0.4876978154477065, 26.81276482882897), Offset(0.3513050649358309, 22.783764879527716), Offset(0.6863939195032227, 19.85081073902098), Offset(1.1783282678714926, 17.682460973530382), Offset(1.6884550124603805, 16.066844242736977), Offset(2.1534060069115526, 14.864009035624443), Offset(2.5453529224041667, 13.978118002300755), Offset(2.854024635964233, 13.34224573826211), Offset(3.0783743953235785, 12.9083102253197), Offset(3.222043242770944, 12.641456387603249), Offset(3.2911213835868267, 12.515996061883946), ], ), _PathCubicTo( <Offset>[ Offset(44.699999999999996, 35.5), Offset(44.58522337199017, 35.70421200787435), Offset(44.161666201675246, 36.41963026713059), Offset(43.197058507087796, 37.86408831028741), Offset(41.09560447466507, 40.38536870643476), Offset(35.994930992770826, 44.41718958325718), Offset(21.92427619931773, 47.58879756798301), Offset(6.8882077861324005, 40.36846257989491), Offset(1.8838999842656072, 32.46274896792012), Offset(0.4876978154477065, 26.81276482882897), Offset(0.3513050649358309, 22.783764879527716), Offset(0.6863939195032227, 19.85081073902098), Offset(1.1783282678714926, 17.682460973530382), Offset(1.6884550124603805, 16.066844242736977), Offset(2.1534060069115526, 14.864009035624443), Offset(2.5453529224041667, 13.978118002300755), Offset(2.854024635964233, 13.34224573826211), Offset(3.0783743953235785, 12.9083102253197), Offset(3.222043242770944, 12.641456387603249), Offset(3.2911213835868267, 12.515996061883946), ], <Offset>[ Offset(44.699999999999996, 30.900000000000002), Offset(44.63072886653579, 31.104437094906736), Offset(44.368616039331826, 31.82428786806021), Offset(43.74029439873209, 33.296277591132174), Offset(42.26523270078937, 35.936552030884584), Offset(38.33040365853423, 40.454164548328436), Offset(26.125744069416946, 45.71592070696839), Offset(11.282078055724707, 41.73004403320309), Offset(5.407395093510004, 35.41994057739199), Offset(3.1834788415273714, 30.54006474424078), Offset(2.375783528918289, 26.914320162885055), Offset(2.181211411081952, 24.2011579282543), Offset(2.2585265211246224, 22.153833439973866), Offset(2.446178090240206, 20.604008085645876), Offset(2.66301074815801, 19.43569395561829), Offset(2.8675472131340918, 18.566820524694318), Offset(3.0391206447290973, 17.938520258734023), Offset(3.168618169875643, 17.507424929385536), Offset(3.2534185498383863, 17.24134938528335), Offset(3.29467530130421, 17.11599468902166), ], <Offset>[ Offset(44.699999999999996, 30.900000000000002), Offset(44.63072886653579, 31.104437094906736), Offset(44.368616039331826, 31.82428786806021), Offset(43.74029439873209, 33.296277591132174), Offset(42.26523270078937, 35.936552030884584), Offset(38.33040365853423, 40.454164548328436), Offset(26.125744069416946, 45.71592070696839), Offset(11.282078055724707, 41.73004403320309), Offset(5.407395093510004, 35.41994057739199), Offset(3.1834788415273714, 30.54006474424078), Offset(2.375783528918289, 26.914320162885055), Offset(2.181211411081952, 24.2011579282543), Offset(2.2585265211246224, 22.153833439973866), Offset(2.446178090240206, 20.604008085645876), Offset(2.66301074815801, 19.43569395561829), Offset(2.8675472131340918, 18.566820524694318), Offset(3.0391206447290973, 17.938520258734023), Offset(3.168618169875643, 17.507424929385536), Offset(3.2534185498383863, 17.24134938528335), Offset(3.29467530130421, 17.11599468902166), ], ), _PathCubicTo( <Offset>[ Offset(44.699999999999996, 30.900000000000002), Offset(44.63072886653579, 31.104437094906736), Offset(44.368616039331826, 31.82428786806021), Offset(43.74029439873209, 33.296277591132174), Offset(42.26523270078937, 35.936552030884584), Offset(38.33040365853423, 40.454164548328436), Offset(26.125744069416946, 45.71592070696839), Offset(11.282078055724707, 41.73004403320309), Offset(5.407395093510004, 35.41994057739199), Offset(3.1834788415273714, 30.54006474424078), Offset(2.375783528918289, 26.914320162885055), Offset(2.181211411081952, 24.2011579282543), Offset(2.2585265211246224, 22.153833439973866), Offset(2.446178090240206, 20.604008085645876), Offset(2.66301074815801, 19.43569395561829), Offset(2.8675472131340918, 18.566820524694318), Offset(3.0391206447290973, 17.938520258734023), Offset(3.168618169875643, 17.507424929385536), Offset(3.2534185498383863, 17.24134938528335), Offset(3.29467530130421, 17.11599468902166), ], <Offset>[ Offset(12.5, 30.900000000000002), Offset(12.432304475762546, 30.785898633087346), Offset(12.201219245839173, 30.3756390044641), Offset(11.765619364645481, 29.493626349622097), Offset(11.123515971938117, 27.749154448014536), Offset(10.589228414033032, 24.10585588798459), Offset(13.015606042314635, 16.305645616273882), Offset(20.81314822888201, 10.972952146056956), Offset(26.107736359813064, 10.755474812681204), Offset(29.274578249410023, 11.66959756168313), Offset(31.28967051241966, 12.742970915007843), Offset(32.63364173571521, 13.737435487203195), Offset(33.55813378622901, 14.592445667201952), Offset(34.20632499060251, 15.299946541187085), Offset(34.664805188114926, 15.868460766893085), Offset(34.98846486988903, 16.311460489584853), Offset(35.21304228803248, 16.642848197379976), Offset(35.3624210983365, 16.87571850752108), Offset(35.452669533599085, 17.021722235811232), Offset(35.49466569126821, 17.09111726499996), ], <Offset>[ Offset(12.5, 30.900000000000002), Offset(12.432304475762546, 30.785898633087346), Offset(12.201219245839173, 30.3756390044641), Offset(11.765619364645481, 29.493626349622097), Offset(11.123515971938117, 27.749154448014536), Offset(10.589228414033032, 24.10585588798459), Offset(13.015606042314635, 16.305645616273882), Offset(20.81314822888201, 10.972952146056956), Offset(26.107736359813064, 10.755474812681204), Offset(29.274578249410023, 11.66959756168313), Offset(31.28967051241966, 12.742970915007843), Offset(32.63364173571521, 13.737435487203195), Offset(33.55813378622901, 14.592445667201952), Offset(34.20632499060251, 15.299946541187085), Offset(34.664805188114926, 15.868460766893085), Offset(34.98846486988903, 16.311460489584853), Offset(35.21304228803248, 16.642848197379976), Offset(35.3624210983365, 16.87571850752108), Offset(35.452669533599085, 17.021722235811232), Offset(35.49466569126821, 17.09111726499996), ], ), _PathCubicTo( <Offset>[ Offset(12.5, 30.900000000000002), Offset(12.432304475762546, 30.785898633087346), Offset(12.201219245839173, 30.3756390044641), Offset(11.765619364645481, 29.493626349622097), Offset(11.123515971938117, 27.749154448014536), Offset(10.589228414033032, 24.10585588798459), Offset(13.015606042314635, 16.305645616273882), Offset(20.81314822888201, 10.972952146056956), Offset(26.107736359813064, 10.755474812681204), Offset(29.274578249410023, 11.66959756168313), Offset(31.28967051241966, 12.742970915007843), Offset(32.63364173571521, 13.737435487203195), Offset(33.55813378622901, 14.592445667201952), Offset(34.20632499060251, 15.299946541187085), Offset(34.664805188114926, 15.868460766893085), Offset(34.98846486988903, 16.311460489584853), Offset(35.21304228803248, 16.642848197379976), Offset(35.3624210983365, 16.87571850752108), Offset(35.452669533599085, 17.021722235811232), Offset(35.49466569126821, 17.09111726499996), ], <Offset>[ Offset(12.5, 35.5), Offset(12.386798981216916, 35.38567354605495), Offset(11.994269408182586, 34.97098140353448), Offset(11.222383473001184, 34.06143706877733), Offset(9.953887745813823, 32.19797112356471), Offset(8.253755748269624, 28.068880922913333), Offset(8.81413817221542, 18.1785224772885), Offset(16.419277959289705, 9.611370692748771), Offset(22.584241250568667, 7.798283203209337), Offset(26.57879722333036, 7.942297646271321), Offset(29.2651920484372, 8.612415631650505), Offset(31.13882424413648, 9.387088297969871), Offset(32.47793553297588, 10.121073200758469), Offset(33.44860191282268, 10.762782698278183), Offset(34.15520044686847, 11.296775846899239), Offset(34.666270579159104, 11.72275796719129), Offset(35.027946279267624, 12.046573676908062), Offset(35.27217732378443, 12.276603803455243), Offset(35.42129422653164, 12.421829238131133), Offset(35.49111177355083, 12.491118637862245), ], <Offset>[ Offset(12.5, 35.5), Offset(12.386798981216916, 35.38567354605495), Offset(11.994269408182586, 34.97098140353448), Offset(11.222383473001184, 34.06143706877733), Offset(9.953887745813823, 32.19797112356471), Offset(8.253755748269624, 28.068880922913333), Offset(8.81413817221542, 18.1785224772885), Offset(16.419277959289705, 9.611370692748771), Offset(22.584241250568667, 7.798283203209337), Offset(26.57879722333036, 7.942297646271321), Offset(29.2651920484372, 8.612415631650505), Offset(31.13882424413648, 9.387088297969871), Offset(32.47793553297588, 10.121073200758469), Offset(33.44860191282268, 10.762782698278183), Offset(34.15520044686847, 11.296775846899239), Offset(34.666270579159104, 11.72275796719129), Offset(35.027946279267624, 12.046573676908062), Offset(35.27217732378443, 12.276603803455243), Offset(35.42129422653164, 12.421829238131133), Offset(35.49111177355083, 12.491118637862245), ], ), _PathClose( ), ], ), _PathFrames( opacities: <double>[ 1.0, 1.0, 1.0, 1.0, 1.0, 0.878048780488, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(12.5, 17.1), Offset(12.568820959399424, 16.986573894184524), Offset(12.822068758808932, 16.589611807252965), Offset(13.395327039578369, 15.790194192156408), Offset(14.632400650310995, 14.402704421364), Offset(17.59564641132325, 12.216780783198363), Offset(25.620009652612282, 10.687015033230036), Offset(33.99475903765893, 15.057696505981518), Offset(36.67822168754626, 19.6270496410968), Offset(37.361921327649014, 22.851497307918553), Offset(37.36310590436704, 25.13463676507986), Offset(37.118094210451396, 26.788477054903165), Offset(36.7987285459884, 28.0065630665324), Offset(36.479494223942, 28.91143806991379), Offset(36.1936194118543, 29.58351552687462), Offset(35.95504774207879, 30.077568056765532), Offset(35.76833031432708, 30.43167175879571), Offset(35.63315242199269, 30.673062619718593), Offset(35.54679545480142, 30.821401228851528), Offset(35.50532744442037, 30.891113146413097), ], ), _PathCubicTo( <Offset>[ Offset(12.5, 17.1), Offset(12.568820959399424, 16.986573894184524), Offset(12.822068758808932, 16.589611807252965), Offset(13.395327039578369, 15.790194192156408), Offset(14.632400650310995, 14.402704421364), Offset(17.59564641132325, 12.216780783198363), Offset(25.620009652612282, 10.687015033230036), Offset(33.99475903765893, 15.057696505981518), Offset(36.67822168754626, 19.6270496410968), Offset(37.361921327649014, 22.851497307918553), Offset(37.36310590436704, 25.13463676507986), Offset(37.118094210451396, 26.788477054903165), Offset(36.7987285459884, 28.0065630665324), Offset(36.479494223942, 28.91143806991379), Offset(36.1936194118543, 29.58351552687462), Offset(35.95504774207879, 30.077568056765532), Offset(35.76833031432708, 30.43167175879571), Offset(35.63315242199269, 30.673062619718593), Offset(35.54679545480142, 30.821401228851528), Offset(35.50532744442037, 30.891113146413097), ], <Offset>[ Offset(44.699999999999996, 17.1), Offset(44.76724535017267, 17.305112356003914), Offset(44.98946555230159, 18.038260670849073), Offset(45.37000207366498, 19.592845433666486), Offset(45.77411737916225, 22.590102004234048), Offset(45.33682165582445, 28.565089443542213), Offset(38.7301476797146, 40.09729012392454), Offset(24.463688864501623, 45.81478839312766), Offset(15.977880421243203, 44.29151540580759), Offset(11.270821919766366, 41.7219644904762), Offset(8.44921892086567, 39.30598601295708), Offset(6.665663885818139, 37.25219949595427), Offset(5.499121280884019, 35.56795083930431), Offset(4.71934732357969, 34.21549961437258), Offset(4.191824971897383, 33.150748715599825), Offset(3.83413008532386, 32.332928091875), Offset(3.5944086710236895, 31.727343820149756), Offset(3.439349493531836, 31.30476904158305), Offset(3.3475444710407203, 31.041028378323645), Offset(3.3053370544563663, 30.9159905704348), ], <Offset>[ Offset(44.699999999999996, 17.1), Offset(44.76724535017267, 17.305112356003914), Offset(44.98946555230159, 18.038260670849073), Offset(45.37000207366498, 19.592845433666486), Offset(45.77411737916225, 22.590102004234048), Offset(45.33682165582445, 28.565089443542213), Offset(38.7301476797146, 40.09729012392454), Offset(24.463688864501623, 45.81478839312766), Offset(15.977880421243203, 44.29151540580759), Offset(11.270821919766366, 41.7219644904762), Offset(8.44921892086567, 39.30598601295708), Offset(6.665663885818139, 37.25219949595427), Offset(5.499121280884019, 35.56795083930431), Offset(4.71934732357969, 34.21549961437258), Offset(4.191824971897383, 33.150748715599825), Offset(3.83413008532386, 32.332928091875), Offset(3.5944086710236895, 31.727343820149756), Offset(3.439349493531836, 31.30476904158305), Offset(3.3475444710407203, 31.041028378323645), Offset(3.3053370544563663, 30.9159905704348), ], ), _PathCubicTo( <Offset>[ Offset(44.699999999999996, 17.1), Offset(44.76724535017267, 17.305112356003914), Offset(44.98946555230159, 18.038260670849073), Offset(45.37000207366498, 19.592845433666486), Offset(45.77411737916225, 22.590102004234048), Offset(45.33682165582445, 28.565089443542213), Offset(38.7301476797146, 40.09729012392454), Offset(24.463688864501623, 45.81478839312766), Offset(15.977880421243203, 44.29151540580759), Offset(11.270821919766366, 41.7219644904762), Offset(8.44921892086567, 39.30598601295708), Offset(6.665663885818139, 37.25219949595427), Offset(5.499121280884019, 35.56795083930431), Offset(4.71934732357969, 34.21549961437258), Offset(4.191824971897383, 33.150748715599825), Offset(3.83413008532386, 32.332928091875), Offset(3.5944086710236895, 31.727343820149756), Offset(3.439349493531836, 31.30476904158305), Offset(3.3475444710407203, 31.041028378323645), Offset(3.3053370544563663, 30.9159905704348), ], <Offset>[ Offset(44.699999999999996, 12.5), Offset(44.8127508447183, 12.705337443036306), Offset(45.196415389958176, 13.442918271778694), Offset(45.91323796530928, 15.025034714511255), Offset(46.94374560528654, 18.14128532868387), Offset(47.67229432158786, 24.60206440861347), Offset(42.93161554981381, 38.22441326290992), Offset(28.85755913409393, 47.17636984643584), Offset(19.5013755304876, 47.24870701527945), Offset(13.96660294584603, 45.449264405888016), Offset(10.473697384848128, 43.43654129631442), Offset(8.160481377396868, 41.60254668518759), Offset(6.579319534137149, 40.03932330574779), Offset(5.477070401359516, 38.75266345728148), Offset(4.70142971314384, 37.722433635593674), Offset(4.156324376053785, 36.92163061426856), Offset(3.7795046797885536, 36.32361834062167), Offset(3.5295932680839, 35.90388374564888), Offset(3.3789197781081626, 35.640921376003746), Offset(3.3088909721737494, 35.515989197572516), ], <Offset>[ Offset(44.699999999999996, 12.5), Offset(44.8127508447183, 12.705337443036306), Offset(45.196415389958176, 13.442918271778694), Offset(45.91323796530928, 15.025034714511255), Offset(46.94374560528654, 18.14128532868387), Offset(47.67229432158786, 24.60206440861347), Offset(42.93161554981381, 38.22441326290992), Offset(28.85755913409393, 47.17636984643584), Offset(19.5013755304876, 47.24870701527945), Offset(13.96660294584603, 45.449264405888016), Offset(10.473697384848128, 43.43654129631442), Offset(8.160481377396868, 41.60254668518759), Offset(6.579319534137149, 40.03932330574779), Offset(5.477070401359516, 38.75266345728148), Offset(4.70142971314384, 37.722433635593674), Offset(4.156324376053785, 36.92163061426856), Offset(3.7795046797885536, 36.32361834062167), Offset(3.5295932680839, 35.90388374564888), Offset(3.3789197781081626, 35.640921376003746), Offset(3.3088909721737494, 35.515989197572516), ], ), _PathCubicTo( <Offset>[ Offset(44.699999999999996, 12.5), Offset(44.8127508447183, 12.705337443036306), Offset(45.196415389958176, 13.442918271778694), Offset(45.91323796530928, 15.025034714511255), Offset(46.94374560528654, 18.14128532868387), Offset(47.67229432158786, 24.60206440861347), Offset(42.93161554981381, 38.22441326290992), Offset(28.85755913409393, 47.17636984643584), Offset(19.5013755304876, 47.24870701527945), Offset(13.96660294584603, 45.449264405888016), Offset(10.473697384848128, 43.43654129631442), Offset(8.160481377396868, 41.60254668518759), Offset(6.579319534137149, 40.03932330574779), Offset(5.477070401359516, 38.75266345728148), Offset(4.70142971314384, 37.722433635593674), Offset(4.156324376053785, 36.92163061426856), Offset(3.7795046797885536, 36.32361834062167), Offset(3.5295932680839, 35.90388374564888), Offset(3.3789197781081626, 35.640921376003746), Offset(3.3088909721737494, 35.515989197572516), ], <Offset>[ Offset(12.5, 12.5), Offset(12.614326453945054, 12.386798981216916), Offset(13.02901859646552, 11.994269408182586), Offset(13.938562931222666, 11.222383473001177), Offset(15.802028876435289, 9.953887745813823), Offset(19.931119077086663, 8.25375574826962), Offset(29.821477522711497, 8.814138172215419), Offset(38.388629307251236, 16.4192779592897), Offset(40.20171679679066, 22.584241250568667), Offset(40.057702353728686, 26.578797223330362), Offset(39.3875843683495, 29.2651920484372), Offset(38.612911702030125, 31.138824244136487), Offset(37.87892679924153, 32.477935532975884), Offset(37.23721730172182, 33.44860191282269), Offset(36.703224153100756, 34.15520044686847), Offset(36.277242032808715, 34.6662705791591), Offset(35.953426323091946, 35.027946279267624), Offset(35.723396196544755, 35.272177323784426), Offset(35.57817076186886, 35.42129422653163), Offset(35.50888136213775, 35.49111177355081), ], <Offset>[ Offset(12.5, 12.5), Offset(12.614326453945054, 12.386798981216916), Offset(13.02901859646552, 11.994269408182586), Offset(13.938562931222666, 11.222383473001177), Offset(15.802028876435289, 9.953887745813823), Offset(19.931119077086663, 8.25375574826962), Offset(29.821477522711497, 8.814138172215419), Offset(38.388629307251236, 16.4192779592897), Offset(40.20171679679066, 22.584241250568667), Offset(40.057702353728686, 26.578797223330362), Offset(39.3875843683495, 29.2651920484372), Offset(38.612911702030125, 31.138824244136487), Offset(37.87892679924153, 32.477935532975884), Offset(37.23721730172182, 33.44860191282269), Offset(36.703224153100756, 34.15520044686847), Offset(36.277242032808715, 34.6662705791591), Offset(35.953426323091946, 35.027946279267624), Offset(35.723396196544755, 35.272177323784426), Offset(35.57817076186886, 35.42129422653163), Offset(35.50888136213775, 35.49111177355081), ], ), _PathCubicTo( <Offset>[ Offset(12.5, 12.5), Offset(12.614326453945054, 12.386798981216916), Offset(13.02901859646552, 11.994269408182586), Offset(13.938562931222666, 11.222383473001177), Offset(15.802028876435289, 9.953887745813823), Offset(19.931119077086663, 8.25375574826962), Offset(29.821477522711497, 8.814138172215419), Offset(38.388629307251236, 16.4192779592897), Offset(40.20171679679066, 22.584241250568667), Offset(40.057702353728686, 26.578797223330362), Offset(39.3875843683495, 29.2651920484372), Offset(38.612911702030125, 31.138824244136487), Offset(37.87892679924153, 32.477935532975884), Offset(37.23721730172182, 33.44860191282269), Offset(36.703224153100756, 34.15520044686847), Offset(36.277242032808715, 34.6662705791591), Offset(35.953426323091946, 35.027946279267624), Offset(35.723396196544755, 35.272177323784426), Offset(35.57817076186886, 35.42129422653163), Offset(35.50888136213775, 35.49111177355081), ], <Offset>[ Offset(12.5, 17.1), Offset(12.568820959399424, 16.986573894184524), Offset(12.822068758808932, 16.589611807252965), Offset(13.395327039578369, 15.790194192156408), Offset(14.632400650310995, 14.402704421364), Offset(17.59564641132325, 12.216780783198363), Offset(25.620009652612282, 10.687015033230036), Offset(33.99475903765893, 15.057696505981518), Offset(36.67822168754626, 19.6270496410968), Offset(37.361921327649014, 22.851497307918553), Offset(37.36310590436704, 25.13463676507986), Offset(37.118094210451396, 26.788477054903165), Offset(36.7987285459884, 28.0065630665324), Offset(36.479494223942, 28.91143806991379), Offset(36.1936194118543, 29.58351552687462), Offset(35.95504774207879, 30.077568056765532), Offset(35.76833031432708, 30.43167175879571), Offset(35.63315242199269, 30.673062619718593), Offset(35.54679545480142, 30.821401228851528), Offset(35.50532744442037, 30.891113146413097), ], <Offset>[ Offset(12.5, 17.1), Offset(12.568820959399424, 16.986573894184524), Offset(12.822068758808932, 16.589611807252965), Offset(13.395327039578369, 15.790194192156408), Offset(14.632400650310995, 14.402704421364), Offset(17.59564641132325, 12.216780783198363), Offset(25.620009652612282, 10.687015033230036), Offset(33.99475903765893, 15.057696505981518), Offset(36.67822168754626, 19.6270496410968), Offset(37.361921327649014, 22.851497307918553), Offset(37.36310590436704, 25.13463676507986), Offset(37.118094210451396, 26.788477054903165), Offset(36.7987285459884, 28.0065630665324), Offset(36.479494223942, 28.91143806991379), Offset(36.1936194118543, 29.58351552687462), Offset(35.95504774207879, 30.077568056765532), Offset(35.76833031432708, 30.43167175879571), Offset(35.63315242199269, 30.673062619718593), Offset(35.54679545480142, 30.821401228851528), Offset(35.50532744442037, 30.891113146413097), ], ), _PathClose( ), ], ), _PathFrames( opacities: <double>[ 1.0, 1.0, 1.0, 1.0, 1.0, 0.878048780488, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(12.5, 26.3), Offset(12.477809970308172, 26.186123720119735), Offset(12.40816908349576, 25.780296605393723), Offset(12.308855256289778, 24.925815630466868), Offset(12.293144198062407, 23.30033777246436), Offset(12.924701079796437, 20.14283085305585), Offset(17.217073912413852, 14.432768755259271), Offset(25.207018498474316, 12.334533599365145), Offset(29.631231469057468, 13.71266642215307), Offset(31.970359275489688, 15.396897477094935), Offset(33.314148976402116, 16.873526198365184), Offset(34.12845922729394, 18.087782676436515), Offset(34.638332039482144, 19.063818133645434), Offset(34.96404806838234, 19.837110384095983), Offset(35.17440992936138, 20.44014568688693), Offset(35.31065916061894, 20.900163011978407), Offset(35.398138296797356, 21.239122717851885), Offset(35.45266487288856, 21.47483321158692), Offset(35.484044840666535, 21.62161523349133), Offset(35.4982196089856, 21.691115892137674), ], ), _PathCubicTo( <Offset>[ Offset(12.5, 26.3), Offset(12.477809970308172, 26.186123720119735), Offset(12.40816908349576, 25.780296605393723), Offset(12.308855256289778, 24.925815630466868), Offset(12.293144198062407, 23.30033777246436), Offset(12.924701079796437, 20.14283085305585), Offset(17.217073912413852, 14.432768755259271), Offset(25.207018498474316, 12.334533599365145), Offset(29.631231469057468, 13.71266642215307), Offset(31.970359275489688, 15.396897477094935), Offset(33.314148976402116, 16.873526198365184), Offset(34.12845922729394, 18.087782676436515), Offset(34.638332039482144, 19.063818133645434), Offset(34.96404806838234, 19.837110384095983), Offset(35.17440992936138, 20.44014568688693), Offset(35.31065916061894, 20.900163011978407), Offset(35.398138296797356, 21.239122717851885), Offset(35.45266487288856, 21.47483321158692), Offset(35.484044840666535, 21.62161523349133), Offset(35.4982196089856, 21.691115892137674), ], <Offset>[ Offset(44.699999999999996, 26.3), Offset(44.67623436108142, 26.504662181939125), Offset(44.57556587698842, 27.22894546898983), Offset(44.28353029037639, 28.72846687197695), Offset(43.43486092691366, 31.487735355334408), Offset(40.665876324297635, 36.4911395133997), Offset(30.32721193951616, 43.84304384595377), Offset(15.675948325317012, 43.09162548651128), Offset(8.930890202754409, 38.37713218686386), Offset(5.879259867607036, 34.267364659652586), Offset(4.400261992900747, 31.044875446242393), Offset(3.676028902660681, 28.551505117487622), Offset(3.3387247743777593, 26.62520590641735), Offset(3.2039011680200318, 25.141171928554776), Offset(3.172615489404464, 24.007378875612137), Offset(3.18974150386401, 23.155523047087872), Offset(3.224216653493965, 22.53479477920593), Offset(3.258861944427707, 22.106539633451376), Offset(3.2847938569058357, 21.841242382963447), Offset(3.2982292190216, 21.715993316159373), ], <Offset>[ Offset(44.699999999999996, 26.3), Offset(44.67623436108142, 26.504662181939125), Offset(44.57556587698842, 27.22894546898983), Offset(44.28353029037639, 28.72846687197695), Offset(43.43486092691366, 31.487735355334408), Offset(40.665876324297635, 36.4911395133997), Offset(30.32721193951616, 43.84304384595377), Offset(15.675948325317012, 43.09162548651128), Offset(8.930890202754409, 38.37713218686386), Offset(5.879259867607036, 34.267364659652586), Offset(4.400261992900747, 31.044875446242393), Offset(3.676028902660681, 28.551505117487622), Offset(3.3387247743777593, 26.62520590641735), Offset(3.2039011680200318, 25.141171928554776), Offset(3.172615489404464, 24.007378875612137), Offset(3.18974150386401, 23.155523047087872), Offset(3.224216653493965, 22.53479477920593), Offset(3.258861944427707, 22.106539633451376), Offset(3.2847938569058357, 21.841242382963447), Offset(3.2982292190216, 21.715993316159373), ], ), _PathCubicTo( <Offset>[ Offset(44.699999999999996, 26.3), Offset(44.67623436108142, 26.504662181939125), Offset(44.57556587698842, 27.22894546898983), Offset(44.28353029037639, 28.72846687197695), Offset(43.43486092691366, 31.487735355334408), Offset(40.665876324297635, 36.4911395133997), Offset(30.32721193951616, 43.84304384595377), Offset(15.675948325317012, 43.09162548651128), Offset(8.930890202754409, 38.37713218686386), Offset(5.879259867607036, 34.267364659652586), Offset(4.400261992900747, 31.044875446242393), Offset(3.676028902660681, 28.551505117487622), Offset(3.3387247743777593, 26.62520590641735), Offset(3.2039011680200318, 25.141171928554776), Offset(3.172615489404464, 24.007378875612137), Offset(3.18974150386401, 23.155523047087872), Offset(3.224216653493965, 22.53479477920593), Offset(3.258861944427707, 22.106539633451376), Offset(3.2847938569058357, 21.841242382963447), Offset(3.2982292190216, 21.715993316159373), ], <Offset>[ Offset(44.699999999999996, 21.7), Offset(44.72173985562705, 21.904887268971517), Offset(44.782515714645, 22.633603069919452), Offset(44.82676618202069, 24.16065615282172), Offset(44.60448915303795, 27.03891867978423), Offset(43.00134899006105, 32.528114478470954), Offset(34.528679809615376, 41.970166984939155), Offset(20.069818594909318, 44.45320693981947), Offset(12.454385311998806, 41.334323796335724), Offset(8.575040893686701, 37.99466457506439), Offset(6.424740456883205, 35.17543072959973), Offset(5.17084639423941, 32.90185230672094), Offset(4.418923027630889, 31.096578372860833), Offset(3.9616242457998574, 29.678335771463676), Offset(3.6822202306509215, 28.579063795605983), Offset(3.511935794593935, 27.744225569481436), Offset(3.409312662258829, 27.131069299677847), Offset(3.3491057189797715, 26.70565433751721), Offset(3.316169163973278, 26.441135380643548), Offset(3.301783136738983, 26.315991943297085), ], <Offset>[ Offset(44.699999999999996, 21.7), Offset(44.72173985562705, 21.904887268971517), Offset(44.782515714645, 22.633603069919452), Offset(44.82676618202069, 24.16065615282172), Offset(44.60448915303795, 27.03891867978423), Offset(43.00134899006105, 32.528114478470954), Offset(34.528679809615376, 41.970166984939155), Offset(20.069818594909318, 44.45320693981947), Offset(12.454385311998806, 41.334323796335724), Offset(8.575040893686701, 37.99466457506439), Offset(6.424740456883205, 35.17543072959973), Offset(5.17084639423941, 32.90185230672094), Offset(4.418923027630889, 31.096578372860833), Offset(3.9616242457998574, 29.678335771463676), Offset(3.6822202306509215, 28.579063795605983), Offset(3.511935794593935, 27.744225569481436), Offset(3.409312662258829, 27.131069299677847), Offset(3.3491057189797715, 26.70565433751721), Offset(3.316169163973278, 26.441135380643548), Offset(3.301783136738983, 26.315991943297085), ], ), _PathCubicTo( <Offset>[ Offset(44.699999999999996, 21.7), Offset(44.72173985562705, 21.904887268971517), Offset(44.782515714645, 22.633603069919452), Offset(44.82676618202069, 24.16065615282172), Offset(44.60448915303795, 27.03891867978423), Offset(43.00134899006105, 32.528114478470954), Offset(34.528679809615376, 41.970166984939155), Offset(20.069818594909318, 44.45320693981947), Offset(12.454385311998806, 41.334323796335724), Offset(8.575040893686701, 37.99466457506439), Offset(6.424740456883205, 35.17543072959973), Offset(5.17084639423941, 32.90185230672094), Offset(4.418923027630889, 31.096578372860833), Offset(3.9616242457998574, 29.678335771463676), Offset(3.6822202306509215, 28.579063795605983), Offset(3.511935794593935, 27.744225569481436), Offset(3.409312662258829, 27.131069299677847), Offset(3.3491057189797715, 26.70565433751721), Offset(3.316169163973278, 26.441135380643548), Offset(3.301783136738983, 26.315991943297085), ], <Offset>[ Offset(12.5, 21.7), Offset(12.523315464853802, 21.586348807152127), Offset(12.615118921152348, 21.184954206323344), Offset(12.852091147934075, 20.35800491131164), Offset(13.462772424186701, 18.851521096914183), Offset(15.260173745559845, 16.179805818127107), Offset(21.418541782513067, 12.559891894244654), Offset(29.60088876806662, 13.69611505267333), Offset(33.15472657830186, 16.669858031624937), Offset(34.66614030156936, 19.124197392506744), Offset(35.33862744038458, 21.004081481722523), Offset(35.62327671887267, 22.438129865669836), Offset(35.718530292735274, 23.535190600088917), Offset(35.72177114616216, 24.374274227004882), Offset(35.68401467060784, 25.011830606880775), Offset(35.632853451348865, 25.48886553437197), Offset(35.583234305562215, 25.8353972383238), Offset(35.542908647440626, 26.073947915652752), Offset(35.51542014773398, 26.22150823117143), Offset(35.50177352670298, 26.291114519275386), ], <Offset>[ Offset(12.5, 21.7), Offset(12.523315464853802, 21.586348807152127), Offset(12.615118921152348, 21.184954206323344), Offset(12.852091147934075, 20.35800491131164), Offset(13.462772424186701, 18.851521096914183), Offset(15.260173745559845, 16.179805818127107), Offset(21.418541782513067, 12.559891894244654), Offset(29.60088876806662, 13.69611505267333), Offset(33.15472657830186, 16.669858031624937), Offset(34.66614030156936, 19.124197392506744), Offset(35.33862744038458, 21.004081481722523), Offset(35.62327671887267, 22.438129865669836), Offset(35.718530292735274, 23.535190600088917), Offset(35.72177114616216, 24.374274227004882), Offset(35.68401467060784, 25.011830606880775), Offset(35.632853451348865, 25.48886553437197), Offset(35.583234305562215, 25.8353972383238), Offset(35.542908647440626, 26.073947915652752), Offset(35.51542014773398, 26.22150823117143), Offset(35.50177352670298, 26.291114519275386), ], ), _PathCubicTo( <Offset>[ Offset(12.5, 21.7), Offset(12.523315464853802, 21.586348807152127), Offset(12.615118921152348, 21.184954206323344), Offset(12.852091147934075, 20.35800491131164), Offset(13.462772424186701, 18.851521096914183), Offset(15.260173745559845, 16.179805818127107), Offset(21.418541782513067, 12.559891894244654), Offset(29.60088876806662, 13.69611505267333), Offset(33.15472657830186, 16.669858031624937), Offset(34.66614030156936, 19.124197392506744), Offset(35.33862744038458, 21.004081481722523), Offset(35.62327671887267, 22.438129865669836), Offset(35.718530292735274, 23.535190600088917), Offset(35.72177114616216, 24.374274227004882), Offset(35.68401467060784, 25.011830606880775), Offset(35.632853451348865, 25.48886553437197), Offset(35.583234305562215, 25.8353972383238), Offset(35.542908647440626, 26.073947915652752), Offset(35.51542014773398, 26.22150823117143), Offset(35.50177352670298, 26.291114519275386), ], <Offset>[ Offset(12.5, 26.3), Offset(12.477809970308172, 26.186123720119735), Offset(12.40816908349576, 25.780296605393723), Offset(12.308855256289778, 24.925815630466868), Offset(12.293144198062407, 23.30033777246436), Offset(12.924701079796437, 20.14283085305585), Offset(17.217073912413852, 14.432768755259271), Offset(25.207018498474316, 12.334533599365145), Offset(29.631231469057468, 13.71266642215307), Offset(31.970359275489688, 15.396897477094935), Offset(33.314148976402116, 16.873526198365184), Offset(34.12845922729394, 18.087782676436515), Offset(34.638332039482144, 19.063818133645434), Offset(34.96404806838234, 19.837110384095983), Offset(35.17440992936138, 20.44014568688693), Offset(35.31065916061894, 20.900163011978407), Offset(35.398138296797356, 21.239122717851885), Offset(35.45266487288856, 21.47483321158692), Offset(35.484044840666535, 21.62161523349133), Offset(35.4982196089856, 21.691115892137674), ], <Offset>[ Offset(12.5, 26.3), Offset(12.477809970308172, 26.186123720119735), Offset(12.40816908349576, 25.780296605393723), Offset(12.308855256289778, 24.925815630466868), Offset(12.293144198062407, 23.30033777246436), Offset(12.924701079796437, 20.14283085305585), Offset(17.217073912413852, 14.432768755259271), Offset(25.207018498474316, 12.334533599365145), Offset(29.631231469057468, 13.71266642215307), Offset(31.970359275489688, 15.396897477094935), Offset(33.314148976402116, 16.873526198365184), Offset(34.12845922729394, 18.087782676436515), Offset(34.638332039482144, 19.063818133645434), Offset(34.96404806838234, 19.837110384095983), Offset(35.17440992936138, 20.44014568688693), Offset(35.31065916061894, 20.900163011978407), Offset(35.398138296797356, 21.239122717851885), Offset(35.45266487288856, 21.47483321158692), Offset(35.484044840666535, 21.62161523349133), Offset(35.4982196089856, 21.691115892137674), ], ), _PathClose( ), ], ), _PathFrames( opacities: <double>[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.146341463415, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(18.039538499999995, 12.930571500000006), Offset(18.149334465395803, 12.872149290550801), Offset(18.543577170010774, 12.67362376971493), Offset(19.38848933269092, 12.304132440263823), Offset(21.0500251098891, 11.778829975926628), Offset(24.4849959176686, 11.43667565110878), Offset(31.716380432411114, 14.006619703548635), Offset(36.563833612934715, 21.53883416894973), Offset(36.92848913752976, 26.678594000151676), Offset(36.41588677676291, 30.008169262247456), Offset(35.68873044963835, 32.36483086720799), Offset(34.89395296392378, 34.0653568909929), Offset(34.11750536482414, 35.28323166524228), Offset(33.42442890399698, 36.15784461978932), Offset(32.840093239206396, 36.785183822829495), Offset(32.36951533303179, 37.23048479128569), Offset(32.00877148413249, 37.538392723203316), Offset(31.749801205381853, 37.7397340593929), Offset(31.58332657425492, 37.85607615398918), Offset(31.500705947534364, 37.904137673197035), ], ), _PathCubicTo( <Offset>[ Offset(18.039538499999995, 12.930571500000006), Offset(18.149334465395803, 12.872149290550801), Offset(18.543577170010774, 12.67362376971493), Offset(19.38848933269092, 12.304132440263823), Offset(21.0500251098891, 11.778829975926628), Offset(24.4849959176686, 11.43667565110878), Offset(31.716380432411114, 14.006619703548635), Offset(36.563833612934715, 21.53883416894973), Offset(36.92848913752976, 26.678594000151676), Offset(36.41588677676291, 30.008169262247456), Offset(35.68873044963835, 32.36483086720799), Offset(34.89395296392378, 34.0653568909929), Offset(34.11750536482414, 35.28323166524228), Offset(33.42442890399698, 36.15784461978932), Offset(32.840093239206396, 36.785183822829495), Offset(32.36951533303179, 37.23048479128569), Offset(32.00877148413249, 37.538392723203316), Offset(31.749801205381853, 37.7397340593929), Offset(31.58332657425492, 37.85607615398918), Offset(31.500705947534364, 37.904137673197035), ], <Offset>[ Offset(9.524593499999996, 12.930571500000006), Offset(9.63480611837429, 12.787915207234757), Offset(10.037253738651572, 12.290544098974763), Offset(10.933129105730652, 11.298562062138357), Offset(12.814931782195051, 9.613760407253604), Offset(17.148837885012377, 7.11336292762574), Offset(28.234762045851944, 6.196224855085145), Offset(39.13042441508561, 13.256357206311968), Offset(42.67716555792793, 19.829043505343183), Offset(43.985492641283884, 24.533428745633444), Offset(44.43019441391232, 28.080441886710624), Offset(44.394288300179475, 30.80095825365075), Offset(44.09477826399472, 32.872912945700186), Offset(43.700712499650194, 34.44166739898953), Offset(43.302847476418705, 35.61890284347735), Offset(42.94671302192797, 36.48781021374379), Offset(42.653748813975184, 37.109710143785925), Offset(42.43168887555528, 37.5301341853464), Offset(42.28113740093583, 37.78310769585204), Offset(42.20064775415372, 37.89587099404257), ], <Offset>[ Offset(9.524593499999996, 12.930571500000006), Offset(9.63480611837429, 12.787915207234757), Offset(10.037253738651572, 12.290544098974763), Offset(10.933129105730652, 11.298562062138357), Offset(12.814931782195051, 9.613760407253604), Offset(17.148837885012377, 7.11336292762574), Offset(28.234762045851944, 6.196224855085145), Offset(39.13042441508561, 13.256357206311968), Offset(42.67716555792793, 19.829043505343183), Offset(43.985492641283884, 24.533428745633444), Offset(44.43019441391232, 28.080441886710624), Offset(44.394288300179475, 30.80095825365075), Offset(44.09477826399472, 32.872912945700186), Offset(43.700712499650194, 34.44166739898953), Offset(43.302847476418705, 35.61890284347735), Offset(42.94671302192797, 36.48781021374379), Offset(42.653748813975184, 37.109710143785925), Offset(42.43168887555528, 37.5301341853464), Offset(42.28113740093583, 37.78310769585204), Offset(42.20064775415372, 37.89587099404257), ], ), _PathCubicTo( <Offset>[ Offset(9.524593499999996, 12.930571500000006), Offset(9.63480611837429, 12.787915207234757), Offset(10.037253738651572, 12.290544098974763), Offset(10.933129105730652, 11.298562062138357), Offset(12.814931782195051, 9.613760407253604), Offset(17.148837885012377, 7.11336292762574), Offset(28.234762045851944, 6.196224855085145), Offset(39.13042441508561, 13.256357206311968), Offset(42.67716555792793, 19.829043505343183), Offset(43.985492641283884, 24.533428745633444), Offset(44.43019441391232, 28.080441886710624), Offset(44.394288300179475, 30.80095825365075), Offset(44.09477826399472, 32.872912945700186), Offset(43.700712499650194, 34.44166739898953), Offset(43.302847476418705, 35.61890284347735), Offset(42.94671302192797, 36.48781021374379), Offset(42.653748813975184, 37.109710143785925), Offset(42.43168887555528, 37.5301341853464), Offset(42.28113740093583, 37.78310769585204), Offset(42.20064775415372, 37.89587099404257), ], <Offset>[ Offset(9.524593499999998, 23.148505500000006), Offset(9.533725218395034, 23.005349223660573), Offset(9.577558133763372, 22.498132216605804), Offset(9.726444651980092, 21.44499433449068), Offset(10.216848299787422, 19.495872400486462), Offset(11.960862616832728, 15.916752566813207), Offset(18.862288227695757, 10.374166918956151), Offset(29.191452059920294, 10.176448243730892), Offset(34.457704964157735, 12.93063180086538), Offset(37.415804021347064, 15.449901708208273), Offset(39.288927637315474, 17.590685129581864), Offset(40.4770099353689, 19.400555850143917), Offset(41.202395800544195, 20.900185466695486), Offset(41.64129983469044, 22.110127084205665), Offset(41.90331030119613, 23.06359775882259), Offset(42.055503528877686, 23.79517298706838), Offset(42.13932971867431, 24.335737347974696), Offset(42.18016902669948, 24.711868981138284), Offset(42.19357525117126, 24.945734703834944), Offset(42.19072773916836, 25.055940826099334), ], <Offset>[ Offset(9.524593499999998, 23.148505500000006), Offset(9.533725218395034, 23.005349223660573), Offset(9.577558133763372, 22.498132216605804), Offset(9.726444651980092, 21.44499433449068), Offset(10.216848299787422, 19.495872400486462), Offset(11.960862616832728, 15.916752566813207), Offset(18.862288227695757, 10.374166918956151), Offset(29.191452059920294, 10.176448243730892), Offset(34.457704964157735, 12.93063180086538), Offset(37.415804021347064, 15.449901708208273), Offset(39.288927637315474, 17.590685129581864), Offset(40.4770099353689, 19.400555850143917), Offset(41.202395800544195, 20.900185466695486), Offset(41.64129983469044, 22.110127084205665), Offset(41.90331030119613, 23.06359775882259), Offset(42.055503528877686, 23.79517298706838), Offset(42.13932971867431, 24.335737347974696), Offset(42.18016902669948, 24.711868981138284), Offset(42.19357525117126, 24.945734703834944), Offset(42.19072773916836, 25.055940826099334), ], ), _PathCubicTo( <Offset>[ Offset(9.524593499999998, 23.148505500000006), Offset(9.533725218395034, 23.005349223660573), Offset(9.577558133763372, 22.498132216605804), Offset(9.726444651980092, 21.44499433449068), Offset(10.216848299787422, 19.495872400486462), Offset(11.960862616832728, 15.916752566813207), Offset(18.862288227695757, 10.374166918956151), Offset(29.191452059920294, 10.176448243730892), Offset(34.457704964157735, 12.93063180086538), Offset(37.415804021347064, 15.449901708208273), Offset(39.288927637315474, 17.590685129581864), Offset(40.4770099353689, 19.400555850143917), Offset(41.202395800544195, 20.900185466695486), Offset(41.64129983469044, 22.110127084205665), Offset(41.90331030119613, 23.06359775882259), Offset(42.055503528877686, 23.79517298706838), Offset(42.13932971867431, 24.335737347974696), Offset(42.18016902669948, 24.711868981138284), Offset(42.19357525117126, 24.945734703834944), Offset(42.19072773916836, 25.055940826099334), ], <Offset>[ Offset(18.0395385, 23.148505500000006), Offset(18.048253565416548, 23.089583306976618), Offset(18.083881565122574, 22.88121188734597), Offset(18.181804878940362, 22.450564712616142), Offset(18.45194162748147, 21.660941969159484), Offset(19.29702064948895, 20.240065290296247), Offset(22.343906614254927, 18.18456176741964), Offset(26.6248612577694, 18.458925206368654), Offset(28.709028543759565, 19.78018229567387), Offset(29.84619815682609, 20.924642224822286), Offset(30.547463673041506, 21.875074110079233), Offset(30.976674599113203, 22.664954487486067), Offset(31.225122901373616, 23.310504186237587), Offset(31.365016239037228, 23.82630430500546), Offset(31.440556063983824, 24.229878738174733), Offset(31.47830583998151, 24.53784756461028), Offset(31.49435238883162, 24.76441992739209), Offset(31.498281356526046, 24.921468855184788), Offset(31.495764424490346, 25.018703161972084), Offset(31.490785932549, 25.064207505253805), ], <Offset>[ Offset(18.0395385, 23.148505500000006), Offset(18.048253565416548, 23.089583306976618), Offset(18.083881565122574, 22.88121188734597), Offset(18.181804878940362, 22.450564712616142), Offset(18.45194162748147, 21.660941969159484), Offset(19.29702064948895, 20.240065290296247), Offset(22.343906614254927, 18.18456176741964), Offset(26.6248612577694, 18.458925206368654), Offset(28.709028543759565, 19.78018229567387), Offset(29.84619815682609, 20.924642224822286), Offset(30.547463673041506, 21.875074110079233), Offset(30.976674599113203, 22.664954487486067), Offset(31.225122901373616, 23.310504186237587), Offset(31.365016239037228, 23.82630430500546), Offset(31.440556063983824, 24.229878738174733), Offset(31.47830583998151, 24.53784756461028), Offset(31.49435238883162, 24.76441992739209), Offset(31.498281356526046, 24.921468855184788), Offset(31.495764424490346, 25.018703161972084), Offset(31.490785932549, 25.064207505253805), ], ), _PathCubicTo( <Offset>[ Offset(18.0395385, 23.148505500000006), Offset(18.048253565416548, 23.089583306976618), Offset(18.083881565122574, 22.88121188734597), Offset(18.181804878940362, 22.450564712616142), Offset(18.45194162748147, 21.660941969159484), Offset(19.29702064948895, 20.240065290296247), Offset(22.343906614254927, 18.18456176741964), Offset(26.6248612577694, 18.458925206368654), Offset(28.709028543759565, 19.78018229567387), Offset(29.84619815682609, 20.924642224822286), Offset(30.547463673041506, 21.875074110079233), Offset(30.976674599113203, 22.664954487486067), Offset(31.225122901373616, 23.310504186237587), Offset(31.365016239037228, 23.82630430500546), Offset(31.440556063983824, 24.229878738174733), Offset(31.47830583998151, 24.53784756461028), Offset(31.49435238883162, 24.76441992739209), Offset(31.498281356526046, 24.921468855184788), Offset(31.495764424490346, 25.018703161972084), Offset(31.490785932549, 25.064207505253805), ], <Offset>[ Offset(18.039538499999995, 12.930571500000006), Offset(18.149334465395803, 12.872149290550801), Offset(18.543577170010774, 12.67362376971493), Offset(19.38848933269092, 12.304132440263823), Offset(21.0500251098891, 11.778829975926628), Offset(24.4849959176686, 11.43667565110878), Offset(31.716380432411114, 14.006619703548635), Offset(36.563833612934715, 21.53883416894973), Offset(36.92848913752976, 26.678594000151676), Offset(36.41588677676291, 30.008169262247456), Offset(35.68873044963835, 32.36483086720799), Offset(34.89395296392378, 34.0653568909929), Offset(34.11750536482414, 35.28323166524228), Offset(33.42442890399698, 36.15784461978932), Offset(32.840093239206396, 36.785183822829495), Offset(32.36951533303179, 37.23048479128569), Offset(32.00877148413249, 37.538392723203316), Offset(31.749801205381853, 37.7397340593929), Offset(31.58332657425492, 37.85607615398918), Offset(31.500705947534364, 37.904137673197035), ], <Offset>[ Offset(18.039538499999995, 12.930571500000006), Offset(18.149334465395803, 12.872149290550801), Offset(18.543577170010774, 12.67362376971493), Offset(19.38848933269092, 12.304132440263823), Offset(21.0500251098891, 11.778829975926628), Offset(24.4849959176686, 11.43667565110878), Offset(31.716380432411114, 14.006619703548635), Offset(36.563833612934715, 21.53883416894973), Offset(36.92848913752976, 26.678594000151676), Offset(36.41588677676291, 30.008169262247456), Offset(35.68873044963835, 32.36483086720799), Offset(34.89395296392378, 34.0653568909929), Offset(34.11750536482414, 35.28323166524228), Offset(33.42442890399698, 36.15784461978932), Offset(32.840093239206396, 36.785183822829495), Offset(32.36951533303179, 37.23048479128569), Offset(32.00877148413249, 37.538392723203316), Offset(31.749801205381853, 37.7397340593929), Offset(31.58332657425492, 37.85607615398918), Offset(31.500705947534364, 37.904137673197035), ], ), _PathClose( ), ], ), _PathFrames( opacities: <double>[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.146341463415, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(38.4754065, 24.8514945), Offset(38.466274781604966, 24.99465077633943), Offset(38.42244186623663, 25.501867783394207), Offset(38.27355534801991, 26.555005665509313), Offset(37.78315170021258, 28.504127599513545), Offset(36.03913738316727, 32.08324743318679), Offset(29.137711772304243, 37.62583308104385), Offset(18.8085479400797, 37.8235517562691), Offset(13.542295035842265, 35.06936819913462), Offset(10.58419597865294, 32.55009829179173), Offset(8.71107236268452, 30.409314870418136), Offset(7.522990064631102, 28.599444149856083), Offset(6.797604199455802, 27.099814533304514), Offset(6.358700165309552, 25.889872915794328), Offset(6.096689698803871, 24.93640224117742), Offset(5.94449647112231, 24.204827012931613), Offset(5.860670281325686, 23.6642626520253), Offset(5.819830973300516, 23.288131018861716), Offset(5.806424748828734, 23.05426529616505), Offset(5.809272260831642, 22.944059173900662), ], ), _PathCubicTo( <Offset>[ Offset(38.4754065, 24.8514945), Offset(38.466274781604966, 24.99465077633943), Offset(38.42244186623663, 25.501867783394207), Offset(38.27355534801991, 26.555005665509313), Offset(37.78315170021258, 28.504127599513545), Offset(36.03913738316727, 32.08324743318679), Offset(29.137711772304243, 37.62583308104385), Offset(18.8085479400797, 37.8235517562691), Offset(13.542295035842265, 35.06936819913462), Offset(10.58419597865294, 32.55009829179173), Offset(8.71107236268452, 30.409314870418136), Offset(7.522990064631102, 28.599444149856083), Offset(6.797604199455802, 27.099814533304514), Offset(6.358700165309552, 25.889872915794328), Offset(6.096689698803871, 24.93640224117742), Offset(5.94449647112231, 24.204827012931613), Offset(5.860670281325686, 23.6642626520253), Offset(5.819830973300516, 23.288131018861716), Offset(5.806424748828734, 23.05426529616505), Offset(5.809272260831642, 22.944059173900662), ], <Offset>[ Offset(29.9604615, 24.8514945), Offset(29.951746434583455, 24.910416693023386), Offset(29.91611843487743, 25.11878811265404), Offset(29.818195121059638, 25.54943528738385), Offset(29.54805837251853, 26.339058030840523), Offset(28.702979350511054, 27.759934709703753), Offset(25.656093385745073, 29.81543823258036), Offset(21.375138742230593, 29.54107479363134), Offset(19.290971456240435, 28.21981770432613), Offset(18.153801843173916, 27.07535777517771), Offset(17.452536326958487, 26.124925889920767), Offset(17.023325400886797, 25.335045512513933), Offset(16.774877098626384, 24.689495813762413), Offset(16.63498376096277, 24.17369569499453), Offset(16.559443936016173, 23.770121261825274), Offset(16.521694160018484, 23.46215243538971), Offset(16.505647611168378, 23.235580072607906), Offset(16.501718643473946, 23.078531144815212), Offset(16.504235575509647, 22.98129683802791), Offset(16.509214067451, 22.93579249474619), ], <Offset>[ Offset(29.9604615, 24.8514945), Offset(29.951746434583455, 24.910416693023386), Offset(29.91611843487743, 25.11878811265404), Offset(29.818195121059638, 25.54943528738385), Offset(29.54805837251853, 26.339058030840523), Offset(28.702979350511054, 27.759934709703753), Offset(25.656093385745073, 29.81543823258036), Offset(21.375138742230593, 29.54107479363134), Offset(19.290971456240435, 28.21981770432613), Offset(18.153801843173916, 27.07535777517771), Offset(17.452536326958487, 26.124925889920767), Offset(17.023325400886797, 25.335045512513933), Offset(16.774877098626384, 24.689495813762413), Offset(16.63498376096277, 24.17369569499453), Offset(16.559443936016173, 23.770121261825274), Offset(16.521694160018484, 23.46215243538971), Offset(16.505647611168378, 23.235580072607906), Offset(16.501718643473946, 23.078531144815212), Offset(16.504235575509647, 22.98129683802791), Offset(16.509214067451, 22.93579249474619), ], ), _PathCubicTo( <Offset>[ Offset(29.9604615, 24.8514945), Offset(29.951746434583455, 24.910416693023386), Offset(29.91611843487743, 25.11878811265404), Offset(29.818195121059638, 25.54943528738385), Offset(29.54805837251853, 26.339058030840523), Offset(28.702979350511054, 27.759934709703753), Offset(25.656093385745073, 29.81543823258036), Offset(21.375138742230593, 29.54107479363134), Offset(19.290971456240435, 28.21981770432613), Offset(18.153801843173916, 27.07535777517771), Offset(17.452536326958487, 26.124925889920767), Offset(17.023325400886797, 25.335045512513933), Offset(16.774877098626384, 24.689495813762413), Offset(16.63498376096277, 24.17369569499453), Offset(16.559443936016173, 23.770121261825274), Offset(16.521694160018484, 23.46215243538971), Offset(16.505647611168378, 23.235580072607906), Offset(16.501718643473946, 23.078531144815212), Offset(16.504235575509647, 22.98129683802791), Offset(16.509214067451, 22.93579249474619), ], <Offset>[ Offset(29.9604615, 35.0694285), Offset(29.8506655346042, 35.1278507094492), Offset(29.45642282998923, 35.326376230285085), Offset(28.61151066730908, 35.69586755973617), Offset(26.9499748901109, 36.22117002407338), Offset(23.515004082331405, 36.56332434889122), Offset(16.283619567588886, 33.99338029645136), Offset(11.43616638706528, 26.461165831050263), Offset(11.071510862470241, 21.321405999848324), Offset(11.5841132232371, 17.99183073775254), Offset(12.311269550361642, 15.635169132792008), Offset(13.10604703607622, 13.934643109007098), Offset(13.882494635175863, 12.716768334757713), Offset(14.575571096003015, 11.84215538021067), Offset(15.159906760793596, 11.214816177170512), Offset(15.630484666968204, 10.7695152087143), Offset(15.991228515867505, 10.461607276796677), Offset(16.250198794618143, 10.260265940607095), Offset(16.416673425745074, 10.143923846010813), Offset(16.49929405246564, 10.095862326802958), ], <Offset>[ Offset(29.9604615, 35.0694285), Offset(29.8506655346042, 35.1278507094492), Offset(29.45642282998923, 35.326376230285085), Offset(28.61151066730908, 35.69586755973617), Offset(26.9499748901109, 36.22117002407338), Offset(23.515004082331405, 36.56332434889122), Offset(16.283619567588886, 33.99338029645136), Offset(11.43616638706528, 26.461165831050263), Offset(11.071510862470241, 21.321405999848324), Offset(11.5841132232371, 17.99183073775254), Offset(12.311269550361642, 15.635169132792008), Offset(13.10604703607622, 13.934643109007098), Offset(13.882494635175863, 12.716768334757713), Offset(14.575571096003015, 11.84215538021067), Offset(15.159906760793596, 11.214816177170512), Offset(15.630484666968204, 10.7695152087143), Offset(15.991228515867505, 10.461607276796677), Offset(16.250198794618143, 10.260265940607095), Offset(16.416673425745074, 10.143923846010813), Offset(16.49929405246564, 10.095862326802958), ], ), _PathCubicTo( <Offset>[ Offset(29.9604615, 35.0694285), Offset(29.8506655346042, 35.1278507094492), Offset(29.45642282998923, 35.326376230285085), Offset(28.61151066730908, 35.69586755973617), Offset(26.9499748901109, 36.22117002407338), Offset(23.515004082331405, 36.56332434889122), Offset(16.283619567588886, 33.99338029645136), Offset(11.43616638706528, 26.461165831050263), Offset(11.071510862470241, 21.321405999848324), Offset(11.5841132232371, 17.99183073775254), Offset(12.311269550361642, 15.635169132792008), Offset(13.10604703607622, 13.934643109007098), Offset(13.882494635175863, 12.716768334757713), Offset(14.575571096003015, 11.84215538021067), Offset(15.159906760793596, 11.214816177170512), Offset(15.630484666968204, 10.7695152087143), Offset(15.991228515867505, 10.461607276796677), Offset(16.250198794618143, 10.260265940607095), Offset(16.416673425745074, 10.143923846010813), Offset(16.49929405246564, 10.095862326802958), ], <Offset>[ Offset(38.4754065, 35.0694285), Offset(38.365193881625714, 35.212084792765246), Offset(37.96274626134843, 35.70945590102525), Offset(37.06687089426935, 36.701437937861634), Offset(35.18506821780495, 38.386239592746406), Offset(30.851162114987627, 40.886637072374256), Offset(19.765237954148056, 41.80377514491485), Offset(8.869575584914383, 34.743642793688025), Offset(5.3228344420720735, 28.170956494656817), Offset(4.0145073587161235, 23.466571254366553), Offset(3.5698055860876767, 19.919558113289376), Offset(3.6057116998205245, 17.19904174634925), Offset(3.90522173600528, 15.127087054299814), Offset(4.299287500349799, 13.558332601010466), Offset(4.697152523581295, 12.381097156522657), Offset(5.053286978072029, 11.5121897862562), Offset(5.346251186024813, 10.890289856214071), Offset(5.568311124444711, 10.469865814653598), Offset(5.7188625990641615, 10.216892304147956), Offset(5.799352245846278, 10.104129005957429), ], <Offset>[ Offset(38.4754065, 35.0694285), Offset(38.365193881625714, 35.212084792765246), Offset(37.96274626134843, 35.70945590102525), Offset(37.06687089426935, 36.701437937861634), Offset(35.18506821780495, 38.386239592746406), Offset(30.851162114987627, 40.886637072374256), Offset(19.765237954148056, 41.80377514491485), Offset(8.869575584914383, 34.743642793688025), Offset(5.3228344420720735, 28.170956494656817), Offset(4.0145073587161235, 23.466571254366553), Offset(3.5698055860876767, 19.919558113289376), Offset(3.6057116998205245, 17.19904174634925), Offset(3.90522173600528, 15.127087054299814), Offset(4.299287500349799, 13.558332601010466), Offset(4.697152523581295, 12.381097156522657), Offset(5.053286978072029, 11.5121897862562), Offset(5.346251186024813, 10.890289856214071), Offset(5.568311124444711, 10.469865814653598), Offset(5.7188625990641615, 10.216892304147956), Offset(5.799352245846278, 10.104129005957429), ], ), _PathCubicTo( <Offset>[ Offset(38.4754065, 35.0694285), Offset(38.365193881625714, 35.212084792765246), Offset(37.96274626134843, 35.70945590102525), Offset(37.06687089426935, 36.701437937861634), Offset(35.18506821780495, 38.386239592746406), Offset(30.851162114987627, 40.886637072374256), Offset(19.765237954148056, 41.80377514491485), Offset(8.869575584914383, 34.743642793688025), Offset(5.3228344420720735, 28.170956494656817), Offset(4.0145073587161235, 23.466571254366553), Offset(3.5698055860876767, 19.919558113289376), Offset(3.6057116998205245, 17.19904174634925), Offset(3.90522173600528, 15.127087054299814), Offset(4.299287500349799, 13.558332601010466), Offset(4.697152523581295, 12.381097156522657), Offset(5.053286978072029, 11.5121897862562), Offset(5.346251186024813, 10.890289856214071), Offset(5.568311124444711, 10.469865814653598), Offset(5.7188625990641615, 10.216892304147956), Offset(5.799352245846278, 10.104129005957429), ], <Offset>[ Offset(38.4754065, 24.8514945), Offset(38.466274781604966, 24.99465077633943), Offset(38.42244186623663, 25.501867783394207), Offset(38.27355534801991, 26.555005665509313), Offset(37.78315170021258, 28.504127599513545), Offset(36.03913738316727, 32.08324743318679), Offset(29.137711772304243, 37.62583308104385), Offset(18.8085479400797, 37.8235517562691), Offset(13.542295035842265, 35.06936819913462), Offset(10.58419597865294, 32.55009829179173), Offset(8.71107236268452, 30.409314870418136), Offset(7.522990064631102, 28.599444149856083), Offset(6.797604199455802, 27.099814533304514), Offset(6.358700165309552, 25.889872915794328), Offset(6.096689698803871, 24.93640224117742), Offset(5.94449647112231, 24.204827012931613), Offset(5.860670281325686, 23.6642626520253), Offset(5.819830973300516, 23.288131018861716), Offset(5.806424748828734, 23.05426529616505), Offset(5.809272260831642, 22.944059173900662), ], <Offset>[ Offset(38.4754065, 24.8514945), Offset(38.466274781604966, 24.99465077633943), Offset(38.42244186623663, 25.501867783394207), Offset(38.27355534801991, 26.555005665509313), Offset(37.78315170021258, 28.504127599513545), Offset(36.03913738316727, 32.08324743318679), Offset(29.137711772304243, 37.62583308104385), Offset(18.8085479400797, 37.8235517562691), Offset(13.542295035842265, 35.06936819913462), Offset(10.58419597865294, 32.55009829179173), Offset(8.71107236268452, 30.409314870418136), Offset(7.522990064631102, 28.599444149856083), Offset(6.797604199455802, 27.099814533304514), Offset(6.358700165309552, 25.889872915794328), Offset(6.096689698803871, 24.93640224117742), Offset(5.94449647112231, 24.204827012931613), Offset(5.860670281325686, 23.6642626520253), Offset(5.819830973300516, 23.288131018861716), Offset(5.806424748828734, 23.05426529616505), Offset(5.809272260831642, 22.944059173900662), ], ), _PathClose( ), ], ), _PathFrames( opacities: <double>[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.146341463415, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(28.2574725, 24.8514945), Offset(28.248840765179153, 24.893569876360175), Offset(28.214853748605588, 25.042172178506007), Offset(28.12712307566759, 25.34832121175876), Offset(27.90103970697972, 25.90604411710592), Offset(27.235747743979807, 26.895272165007142), Offset(24.959769708433235, 28.253359262887663), Offset(21.888456902660778, 27.88457940110379), Offset(20.440706740320067, 26.84990760536443), Offset(19.66772301607811, 25.980409671854908), Offset(19.20082911981328, 25.26804809382129), Offset(18.92339246813794, 24.682165785045505), Offset(18.770331678460497, 24.207432069853994), Offset(18.690240480093415, 23.830460250834577), Offset(18.651994783458633, 23.536865065954846), Offset(18.637133697797722, 23.313617519881333), Offset(18.634643077136914, 23.149843556724427), Offset(18.638096177508633, 23.03661117000591), Offset(18.643797740845827, 22.966703146400476), Offset(18.649202428774874, 22.9341391589153), ], ), _PathCubicTo( <Offset>[ Offset(28.2574725, 24.8514945), Offset(28.248840765179153, 24.893569876360175), Offset(28.214853748605588, 25.042172178506007), Offset(28.12712307566759, 25.34832121175876), Offset(27.90103970697972, 25.90604411710592), Offset(27.235747743979807, 26.895272165007142), Offset(24.959769708433235, 28.253359262887663), Offset(21.888456902660778, 27.88457940110379), Offset(20.440706740320067, 26.84990760536443), Offset(19.66772301607811, 25.980409671854908), Offset(19.20082911981328, 25.26804809382129), Offset(18.92339246813794, 24.682165785045505), Offset(18.770331678460497, 24.207432069853994), Offset(18.690240480093415, 23.830460250834577), Offset(18.651994783458633, 23.536865065954846), Offset(18.637133697797722, 23.313617519881333), Offset(18.634643077136914, 23.149843556724427), Offset(18.638096177508633, 23.03661117000591), Offset(18.643797740845827, 22.966703146400476), Offset(18.649202428774874, 22.9341391589153), ], <Offset>[ Offset(19.7425275, 24.8514945), Offset(19.73431241815764, 24.80933579304413), Offset(19.708530317246385, 24.65909250776584), Offset(19.67176284870732, 24.34275083363329), Offset(19.66594637928567, 23.740974548432895), Offset(19.899589711323586, 22.5719594415241), Offset(21.478151321874066, 20.442964414424175), Offset(24.455047704811673, 19.602102438466027), Offset(26.189383160718236, 20.00035711055594), Offset(27.237328880599087, 20.505669155240895), Offset(27.942293084087247, 20.983659113323917), Offset(28.423727804393636, 21.417767147703355), Offset(28.74760457763108, 21.797113350311893), Offset(28.96652407574663, 22.11428303003478), Offset(29.114749020670935, 22.3705840866027), Offset(29.2143313866939, 22.570942942339432), Offset(29.279620406979603, 22.721160977307033), Offset(29.319983847682064, 22.827011295959405), Offset(29.34160856752674, 22.893734688263336), Offset(29.349144235394235, 22.92587247976083), ], <Offset>[ Offset(19.7425275, 24.8514945), Offset(19.73431241815764, 24.80933579304413), Offset(19.708530317246385, 24.65909250776584), Offset(19.67176284870732, 24.34275083363329), Offset(19.66594637928567, 23.740974548432895), Offset(19.899589711323586, 22.5719594415241), Offset(21.478151321874066, 20.442964414424175), Offset(24.455047704811673, 19.602102438466027), Offset(26.189383160718236, 20.00035711055594), Offset(27.237328880599087, 20.505669155240895), Offset(27.942293084087247, 20.983659113323917), Offset(28.423727804393636, 21.417767147703355), Offset(28.74760457763108, 21.797113350311893), Offset(28.96652407574663, 22.11428303003478), Offset(29.114749020670935, 22.3705840866027), Offset(29.2143313866939, 22.570942942339432), Offset(29.279620406979603, 22.721160977307033), Offset(29.319983847682064, 22.827011295959405), Offset(29.34160856752674, 22.893734688263336), Offset(29.349144235394235, 22.92587247976083), ], ), _PathCubicTo( <Offset>[ Offset(19.7425275, 24.8514945), Offset(19.73431241815764, 24.80933579304413), Offset(19.708530317246385, 24.65909250776584), Offset(19.67176284870732, 24.34275083363329), Offset(19.66594637928567, 23.740974548432895), Offset(19.899589711323586, 22.5719594415241), Offset(21.478151321874066, 20.442964414424175), Offset(24.455047704811673, 19.602102438466027), Offset(26.189383160718236, 20.00035711055594), Offset(27.237328880599087, 20.505669155240895), Offset(27.942293084087247, 20.983659113323917), Offset(28.423727804393636, 21.417767147703355), Offset(28.74760457763108, 21.797113350311893), Offset(28.96652407574663, 22.11428303003478), Offset(29.114749020670935, 22.3705840866027), Offset(29.2143313866939, 22.570942942339432), Offset(29.279620406979603, 22.721160977307033), Offset(29.319983847682064, 22.827011295959405), Offset(29.34160856752674, 22.893734688263336), Offset(29.349144235394235, 22.92587247976083), ], <Offset>[ Offset(19.7425275, 35.0694285), Offset(19.633231518178384, 35.02676980946995), Offset(19.248834712358185, 34.86668062539688), Offset(18.465078394956763, 34.48918310598561), Offset(17.067862896878044, 33.62308654166575), Offset(14.711614443143937, 31.375349080711565), Offset(12.105677503717876, 24.620906478295183), Offset(14.516075349646359, 16.52219347588495), Offset(17.969922566948043, 13.101945406078135), Offset(20.66764026066227, 11.422142117815724), Offset(22.8010263074904, 10.49390235619516), Offset(24.506449439583058, 10.01736474419652), Offset(25.85522211418056, 9.824385871307193), Offset(26.907111410786875, 9.782742715250919), Offset(27.71521184544836, 9.815279001947939), Offset(28.323121893643616, 9.87830571566402), Offset(28.76520131167873, 9.947188181495804), Offset(29.068463998826257, 10.008746091751288), Offset(29.25404641776217, 10.05636169624624), Offset(29.33922422040887, 10.085942311817597), ], <Offset>[ Offset(19.7425275, 35.0694285), Offset(19.633231518178384, 35.02676980946995), Offset(19.248834712358185, 34.86668062539688), Offset(18.465078394956763, 34.48918310598561), Offset(17.067862896878044, 33.62308654166575), Offset(14.711614443143937, 31.375349080711565), Offset(12.105677503717876, 24.620906478295183), Offset(14.516075349646359, 16.52219347588495), Offset(17.969922566948043, 13.101945406078135), Offset(20.66764026066227, 11.422142117815724), Offset(22.8010263074904, 10.49390235619516), Offset(24.506449439583058, 10.01736474419652), Offset(25.85522211418056, 9.824385871307193), Offset(26.907111410786875, 9.782742715250919), Offset(27.71521184544836, 9.815279001947939), Offset(28.323121893643616, 9.87830571566402), Offset(28.76520131167873, 9.947188181495804), Offset(29.068463998826257, 10.008746091751288), Offset(29.25404641776217, 10.05636169624624), Offset(29.33922422040887, 10.085942311817597), ], ), _PathCubicTo( <Offset>[ Offset(19.7425275, 35.0694285), Offset(19.633231518178384, 35.02676980946995), Offset(19.248834712358185, 34.86668062539688), Offset(18.465078394956763, 34.48918310598561), Offset(17.067862896878044, 33.62308654166575), Offset(14.711614443143937, 31.375349080711565), Offset(12.105677503717876, 24.620906478295183), Offset(14.516075349646359, 16.52219347588495), Offset(17.969922566948043, 13.101945406078135), Offset(20.66764026066227, 11.422142117815724), Offset(22.8010263074904, 10.49390235619516), Offset(24.506449439583058, 10.01736474419652), Offset(25.85522211418056, 9.824385871307193), Offset(26.907111410786875, 9.782742715250919), Offset(27.71521184544836, 9.815279001947939), Offset(28.323121893643616, 9.87830571566402), Offset(28.76520131167873, 9.947188181495804), Offset(29.068463998826257, 10.008746091751288), Offset(29.25404641776217, 10.05636169624624), Offset(29.33922422040887, 10.085942311817597), ], <Offset>[ Offset(28.2574725, 35.0694285), Offset(28.147759865199898, 35.111003892785995), Offset(27.755158143717388, 35.24976029613705), Offset(26.920438621917032, 35.49475348411108), Offset(25.302956224572092, 35.788156110338775), Offset(22.04777247580016, 35.69866180419461), Offset(15.58729589027705, 32.43130132675867), Offset(11.949484547495462, 24.804670438522713), Offset(12.221246146549875, 19.951495900886627), Offset(13.098034396141294, 16.896882634429737), Offset(14.059562343216436, 14.778291336692531), Offset(15.006114103327363, 13.28176338153867), Offset(15.877949215009977, 12.234704590849294), Offset(16.63082781513366, 11.498919936050715), Offset(17.252457608236057, 10.981559981300084), Offset(17.74592420474744, 10.620980293205921), Offset(18.12022398183604, 10.375870760913198), Offset(18.386576328652826, 10.218345965797791), Offset(18.556235591081254, 10.129330154383384), Offset(18.63928241378951, 10.094208990972067), ], <Offset>[ Offset(28.2574725, 35.0694285), Offset(28.147759865199898, 35.111003892785995), Offset(27.755158143717388, 35.24976029613705), Offset(26.920438621917032, 35.49475348411108), Offset(25.302956224572092, 35.788156110338775), Offset(22.04777247580016, 35.69866180419461), Offset(15.58729589027705, 32.43130132675867), Offset(11.949484547495462, 24.804670438522713), Offset(12.221246146549875, 19.951495900886627), Offset(13.098034396141294, 16.896882634429737), Offset(14.059562343216436, 14.778291336692531), Offset(15.006114103327363, 13.28176338153867), Offset(15.877949215009977, 12.234704590849294), Offset(16.63082781513366, 11.498919936050715), Offset(17.252457608236057, 10.981559981300084), Offset(17.74592420474744, 10.620980293205921), Offset(18.12022398183604, 10.375870760913198), Offset(18.386576328652826, 10.218345965797791), Offset(18.556235591081254, 10.129330154383384), Offset(18.63928241378951, 10.094208990972067), ], ), _PathCubicTo( <Offset>[ Offset(28.2574725, 35.0694285), Offset(28.147759865199898, 35.111003892785995), Offset(27.755158143717388, 35.24976029613705), Offset(26.920438621917032, 35.49475348411108), Offset(25.302956224572092, 35.788156110338775), Offset(22.04777247580016, 35.69866180419461), Offset(15.58729589027705, 32.43130132675867), Offset(11.949484547495462, 24.804670438522713), Offset(12.221246146549875, 19.951495900886627), Offset(13.098034396141294, 16.896882634429737), Offset(14.059562343216436, 14.778291336692531), Offset(15.006114103327363, 13.28176338153867), Offset(15.877949215009977, 12.234704590849294), Offset(16.63082781513366, 11.498919936050715), Offset(17.252457608236057, 10.981559981300084), Offset(17.74592420474744, 10.620980293205921), Offset(18.12022398183604, 10.375870760913198), Offset(18.386576328652826, 10.218345965797791), Offset(18.556235591081254, 10.129330154383384), Offset(18.63928241378951, 10.094208990972067), ], <Offset>[ Offset(28.2574725, 24.8514945), Offset(28.248840765179153, 24.893569876360175), Offset(28.214853748605588, 25.042172178506007), Offset(28.12712307566759, 25.34832121175876), Offset(27.90103970697972, 25.90604411710592), Offset(27.235747743979807, 26.895272165007142), Offset(24.959769708433235, 28.253359262887663), Offset(21.888456902660778, 27.88457940110379), Offset(20.440706740320067, 26.84990760536443), Offset(19.66772301607811, 25.980409671854908), Offset(19.20082911981328, 25.26804809382129), Offset(18.92339246813794, 24.682165785045505), Offset(18.770331678460497, 24.207432069853994), Offset(18.690240480093415, 23.830460250834577), Offset(18.651994783458633, 23.536865065954846), Offset(18.637133697797722, 23.313617519881333), Offset(18.634643077136914, 23.149843556724427), Offset(18.638096177508633, 23.03661117000591), Offset(18.643797740845827, 22.966703146400476), Offset(18.649202428774874, 22.9341391589153), ], <Offset>[ Offset(28.2574725, 24.8514945), Offset(28.248840765179153, 24.893569876360175), Offset(28.214853748605588, 25.042172178506007), Offset(28.12712307566759, 25.34832121175876), Offset(27.90103970697972, 25.90604411710592), Offset(27.235747743979807, 26.895272165007142), Offset(24.959769708433235, 28.253359262887663), Offset(21.888456902660778, 27.88457940110379), Offset(20.440706740320067, 26.84990760536443), Offset(19.66772301607811, 25.980409671854908), Offset(19.20082911981328, 25.26804809382129), Offset(18.92339246813794, 24.682165785045505), Offset(18.770331678460497, 24.207432069853994), Offset(18.690240480093415, 23.830460250834577), Offset(18.651994783458633, 23.536865065954846), Offset(18.637133697797722, 23.313617519881333), Offset(18.634643077136914, 23.149843556724427), Offset(18.638096177508633, 23.03661117000591), Offset(18.643797740845827, 22.966703146400476), Offset(18.649202428774874, 22.9341391589153), ], ), _PathClose( ), ], ), _PathFrames( opacities: <double>[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.146341463415, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(18.0395385, 24.851494500000005), Offset(18.03140674875334, 24.79248897638092), Offset(18.007265630974544, 24.58247657361781), Offset(17.98069080331527, 24.141636758008197), Offset(18.018927713746866, 23.30796063469829), Offset(18.432358104792343, 21.707296896827494), Offset(20.78182764456223, 18.880885444731472), Offset(24.96836586524185, 17.945607045938473), Offset(27.339118444797872, 18.63044701159424), Offset(28.751250053503288, 19.41072105191809), Offset(29.690585876942034, 20.12678131722444), Offset(30.323794871644772, 20.764887420234924), Offset(30.7430591574652, 21.315049606403473), Offset(31.021780794877273, 21.771047585874822), Offset(31.20729986811339, 22.13732789073227), Offset(31.32977092447313, 22.42240802683105), Offset(31.408615872948143, 22.635424461423554), Offset(31.456361381716757, 22.785091321150105), Offset(31.48117073286292, 22.87914099663591), Offset(31.489132596718107, 22.924219143929935), ], ), _PathCubicTo( <Offset>[ Offset(18.0395385, 24.851494500000005), Offset(18.03140674875334, 24.79248897638092), Offset(18.007265630974544, 24.58247657361781), Offset(17.98069080331527, 24.141636758008197), Offset(18.018927713746866, 23.30796063469829), Offset(18.432358104792343, 21.707296896827494), Offset(20.78182764456223, 18.880885444731472), Offset(24.96836586524185, 17.945607045938473), Offset(27.339118444797872, 18.63044701159424), Offset(28.751250053503288, 19.41072105191809), Offset(29.690585876942034, 20.12678131722444), Offset(30.323794871644772, 20.764887420234924), Offset(30.7430591574652, 21.315049606403473), Offset(31.021780794877273, 21.771047585874822), Offset(31.20729986811339, 22.13732789073227), Offset(31.32977092447313, 22.42240802683105), Offset(31.408615872948143, 22.635424461423554), Offset(31.456361381716757, 22.785091321150105), Offset(31.48117073286292, 22.87914099663591), Offset(31.489132596718107, 22.924219143929935), ], <Offset>[ Offset(9.5245935, 24.851494500000005), Offset(9.516878401731827, 24.708254893064876), Offset(9.500942199615341, 24.199396902877645), Offset(9.525330576355001, 23.136066379882735), Offset(9.783834386052819, 21.142891066025268), Offset(11.09620007213612, 17.383984173344455), Offset(17.300209258003058, 11.070490596267984), Offset(27.534956667392745, 9.663130083300711), Offset(33.08779486519604, 11.780896516785745), Offset(36.320855918024264, 13.935980535304076), Offset(38.432049841216, 15.842392336727073), Offset(39.82413020790047, 17.500488782892777), Offset(40.72033205663578, 18.904730886861373), Offset(41.298064390530485, 20.054870365075026), Offset(41.67005410532569, 20.971046911380125), Offset(41.90696861336931, 21.67973344928915), Offset(42.053593202790836, 22.20674188200616), Offset(42.138249051890185, 22.5754914471036), Offset(42.178981559543836, 22.806172538498764), Offset(42.189074403337465, 22.915952464775465), ], <Offset>[ Offset(9.5245935, 24.851494500000005), Offset(9.516878401731827, 24.708254893064876), Offset(9.500942199615341, 24.199396902877645), Offset(9.525330576355001, 23.136066379882735), Offset(9.783834386052819, 21.142891066025268), Offset(11.09620007213612, 17.383984173344455), Offset(17.300209258003058, 11.070490596267984), Offset(27.534956667392745, 9.663130083300711), Offset(33.08779486519604, 11.780896516785745), Offset(36.320855918024264, 13.935980535304076), Offset(38.432049841216, 15.842392336727073), Offset(39.82413020790047, 17.500488782892777), Offset(40.72033205663578, 18.904730886861373), Offset(41.298064390530485, 20.054870365075026), Offset(41.67005410532569, 20.971046911380125), Offset(41.90696861336931, 21.67973344928915), Offset(42.053593202790836, 22.20674188200616), Offset(42.138249051890185, 22.5754914471036), Offset(42.178981559543836, 22.806172538498764), Offset(42.189074403337465, 22.915952464775465), ], ), _PathCubicTo( <Offset>[ Offset(9.5245935, 24.851494500000005), Offset(9.516878401731827, 24.708254893064876), Offset(9.500942199615341, 24.199396902877645), Offset(9.525330576355001, 23.136066379882735), Offset(9.783834386052819, 21.142891066025268), Offset(11.09620007213612, 17.383984173344455), Offset(17.300209258003058, 11.070490596267984), Offset(27.534956667392745, 9.663130083300711), Offset(33.08779486519604, 11.780896516785745), Offset(36.320855918024264, 13.935980535304076), Offset(38.432049841216, 15.842392336727073), Offset(39.82413020790047, 17.500488782892777), Offset(40.72033205663578, 18.904730886861373), Offset(41.298064390530485, 20.054870365075026), Offset(41.67005410532569, 20.971046911380125), Offset(41.90696861336931, 21.67973344928915), Offset(42.053593202790836, 22.20674188200616), Offset(42.138249051890185, 22.5754914471036), Offset(42.178981559543836, 22.806172538498764), Offset(42.189074403337465, 22.915952464775465), ], <Offset>[ Offset(9.524593500000002, 35.06942850000001), Offset(9.415797501752571, 34.92568890949069), Offset(9.041246594727141, 34.406985020508685), Offset(8.318646122604441, 33.282498652235056), Offset(7.185750903645189, 31.025003059258125), Offset(5.908224803956472, 26.187373812531924), Offset(7.92773543984687, 15.24843266013899), Offset(17.59598431222743, 6.583221120719635), Offset(24.868334271425848, 4.882484812307943), Offset(29.75116729808745, 4.852453497878906), Offset(33.290783064619156, 5.352635579598315), Offset(35.90685184308989, 6.1000863793859414), Offset(37.82794959318526, 6.932003407856674), Offset(39.23865172557073, 7.723330050291165), Offset(40.27051693010311, 8.415741826725363), Offset(41.015759120319025, 8.987096222613737), Offset(41.53917410748996, 9.43276908619493), Offset(41.886729203034385, 9.757226242895484), Offset(42.09141940977926, 9.968799546481671), Offset(42.1791543883521, 10.076022296832232), ], <Offset>[ Offset(9.524593500000002, 35.06942850000001), Offset(9.415797501752571, 34.92568890949069), Offset(9.041246594727141, 34.406985020508685), Offset(8.318646122604441, 33.282498652235056), Offset(7.185750903645189, 31.025003059258125), Offset(5.908224803956472, 26.187373812531924), Offset(7.92773543984687, 15.24843266013899), Offset(17.59598431222743, 6.583221120719635), Offset(24.868334271425848, 4.882484812307943), Offset(29.75116729808745, 4.852453497878906), Offset(33.290783064619156, 5.352635579598315), Offset(35.90685184308989, 6.1000863793859414), Offset(37.82794959318526, 6.932003407856674), Offset(39.23865172557073, 7.723330050291165), Offset(40.27051693010311, 8.415741826725363), Offset(41.015759120319025, 8.987096222613737), Offset(41.53917410748996, 9.43276908619493), Offset(41.886729203034385, 9.757226242895484), Offset(42.09141940977926, 9.968799546481671), Offset(42.1791543883521, 10.076022296832232), ], ), _PathCubicTo( <Offset>[ Offset(9.524593500000002, 35.06942850000001), Offset(9.415797501752571, 34.92568890949069), Offset(9.041246594727141, 34.406985020508685), Offset(8.318646122604441, 33.282498652235056), Offset(7.185750903645189, 31.025003059258125), Offset(5.908224803956472, 26.187373812531924), Offset(7.92773543984687, 15.24843266013899), Offset(17.59598431222743, 6.583221120719635), Offset(24.868334271425848, 4.882484812307943), Offset(29.75116729808745, 4.852453497878906), Offset(33.290783064619156, 5.352635579598315), Offset(35.90685184308989, 6.1000863793859414), Offset(37.82794959318526, 6.932003407856674), Offset(39.23865172557073, 7.723330050291165), Offset(40.27051693010311, 8.415741826725363), Offset(41.015759120319025, 8.987096222613737), Offset(41.53917410748996, 9.43276908619493), Offset(41.886729203034385, 9.757226242895484), Offset(42.09141940977926, 9.968799546481671), Offset(42.1791543883521, 10.076022296832232), ], <Offset>[ Offset(18.0395385, 35.0694285), Offset(17.930325848774086, 35.009922992806736), Offset(17.547570026086344, 34.79006469124885), Offset(16.77400634956471, 34.28806903036052), Offset(15.420844231339236, 33.190072627931144), Offset(13.244382836612694, 30.510686536014962), Offset(11.409353826406043, 23.05882750860248), Offset(15.029393510076535, 14.865698083357398), Offset(19.119657851027682, 11.732035307116437), Offset(22.181561433566472, 10.327194014492921), Offset(24.549319100345187, 9.637024560095686), Offset(26.406516506834194, 9.36448501672809), Offset(27.85067669401468, 9.342322127398774), Offset(28.962368129917518, 9.43950727109096), Offset(29.807762692890815, 9.582022806077507), Offset(30.438561431422848, 9.729770800155638), Offset(30.89419677764727, 9.861451665612325), Offset(31.20484153286095, 9.966826116941988), Offset(31.39360858309835, 10.041768004618815), Offset(31.479212581732742, 10.084288975986702), ], <Offset>[ Offset(18.0395385, 35.0694285), Offset(17.930325848774086, 35.009922992806736), Offset(17.547570026086344, 34.79006469124885), Offset(16.77400634956471, 34.28806903036052), Offset(15.420844231339236, 33.190072627931144), Offset(13.244382836612694, 30.510686536014962), Offset(11.409353826406043, 23.05882750860248), Offset(15.029393510076535, 14.865698083357398), Offset(19.119657851027682, 11.732035307116437), Offset(22.181561433566472, 10.327194014492921), Offset(24.549319100345187, 9.637024560095686), Offset(26.406516506834194, 9.36448501672809), Offset(27.85067669401468, 9.342322127398774), Offset(28.962368129917518, 9.43950727109096), Offset(29.807762692890815, 9.582022806077507), Offset(30.438561431422848, 9.729770800155638), Offset(30.89419677764727, 9.861451665612325), Offset(31.20484153286095, 9.966826116941988), Offset(31.39360858309835, 10.041768004618815), Offset(31.479212581732742, 10.084288975986702), ], ), _PathCubicTo( <Offset>[ Offset(18.0395385, 35.0694285), Offset(17.930325848774086, 35.009922992806736), Offset(17.547570026086344, 34.79006469124885), Offset(16.77400634956471, 34.28806903036052), Offset(15.420844231339236, 33.190072627931144), Offset(13.244382836612694, 30.510686536014962), Offset(11.409353826406043, 23.05882750860248), Offset(15.029393510076535, 14.865698083357398), Offset(19.119657851027682, 11.732035307116437), Offset(22.181561433566472, 10.327194014492921), Offset(24.549319100345187, 9.637024560095686), Offset(26.406516506834194, 9.36448501672809), Offset(27.85067669401468, 9.342322127398774), Offset(28.962368129917518, 9.43950727109096), Offset(29.807762692890815, 9.582022806077507), Offset(30.438561431422848, 9.729770800155638), Offset(30.89419677764727, 9.861451665612325), Offset(31.20484153286095, 9.966826116941988), Offset(31.39360858309835, 10.041768004618815), Offset(31.479212581732742, 10.084288975986702), ], <Offset>[ Offset(18.0395385, 24.851494500000005), Offset(18.03140674875334, 24.79248897638092), Offset(18.007265630974544, 24.58247657361781), Offset(17.98069080331527, 24.141636758008197), Offset(18.018927713746866, 23.30796063469829), Offset(18.432358104792343, 21.707296896827494), Offset(20.78182764456223, 18.880885444731472), Offset(24.96836586524185, 17.945607045938473), Offset(27.339118444797872, 18.63044701159424), Offset(28.751250053503288, 19.41072105191809), Offset(29.690585876942034, 20.12678131722444), Offset(30.323794871644772, 20.764887420234924), Offset(30.7430591574652, 21.315049606403473), Offset(31.021780794877273, 21.771047585874822), Offset(31.20729986811339, 22.13732789073227), Offset(31.32977092447313, 22.42240802683105), Offset(31.408615872948143, 22.635424461423554), Offset(31.456361381716757, 22.785091321150105), Offset(31.48117073286292, 22.87914099663591), Offset(31.489132596718107, 22.924219143929935), ], <Offset>[ Offset(18.0395385, 24.851494500000005), Offset(18.03140674875334, 24.79248897638092), Offset(18.007265630974544, 24.58247657361781), Offset(17.98069080331527, 24.141636758008197), Offset(18.018927713746866, 23.30796063469829), Offset(18.432358104792343, 21.707296896827494), Offset(20.78182764456223, 18.880885444731472), Offset(24.96836586524185, 17.945607045938473), Offset(27.339118444797872, 18.63044701159424), Offset(28.751250053503288, 19.41072105191809), Offset(29.690585876942034, 20.12678131722444), Offset(30.323794871644772, 20.764887420234924), Offset(30.7430591574652, 21.315049606403473), Offset(31.021780794877273, 21.771047585874822), Offset(31.20729986811339, 22.13732789073227), Offset(31.32977092447313, 22.42240802683105), Offset(31.408615872948143, 22.635424461423554), Offset(31.456361381716757, 22.785091321150105), Offset(31.48117073286292, 22.87914099663591), Offset(31.489132596718107, 22.924219143929935), ], ), _PathClose( ), ], ), _PathFrames( opacities: <double>[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.146341463415, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(38.4754065, 12.930571500000003), Offset(38.58420249824743, 13.074311090509312), Offset(38.958753405272866, 13.593014979491326), Offset(39.681353877395566, 14.717501347764943), Offset(40.81424909635481, 16.97499694074188), Offset(42.09177519604353, 21.812626187468076), Offset(40.07226456015313, 32.75156733986101), Offset(30.404015687772564, 41.41677887928036), Offset(23.131665728574156, 43.11751518769206), Offset(18.248832701912562, 43.147546502121095), Offset(14.709216935380839, 42.647364420401686), Offset(12.093148156910111, 41.89991362061406), Offset(10.17205040681474, 41.06799659214333), Offset(8.761348274429261, 40.276669949708825), Offset(7.729483069896876, 39.58425817327465), Offset(6.984240879680973, 39.012903777386256), Offset(6.460825892510038, 38.56723091380506), Offset(6.1132707969656215, 38.242773757104516), Offset(5.908580590220735, 38.03120045351832), Offset(5.820845611647898, 37.923977703167765), ], ), _PathCubicTo( <Offset>[ Offset(38.4754065, 12.930571500000003), Offset(38.58420249824743, 13.074311090509312), Offset(38.958753405272866, 13.593014979491326), Offset(39.681353877395566, 14.717501347764943), Offset(40.81424909635481, 16.97499694074188), Offset(42.09177519604353, 21.812626187468076), Offset(40.07226456015313, 32.75156733986101), Offset(30.404015687772564, 41.41677887928036), Offset(23.131665728574156, 43.11751518769206), Offset(18.248832701912562, 43.147546502121095), Offset(14.709216935380839, 42.647364420401686), Offset(12.093148156910111, 41.89991362061406), Offset(10.17205040681474, 41.06799659214333), Offset(8.761348274429261, 40.276669949708825), Offset(7.729483069896876, 39.58425817327465), Offset(6.984240879680973, 39.012903777386256), Offset(6.460825892510038, 38.56723091380506), Offset(6.1132707969656215, 38.242773757104516), Offset(5.908580590220735, 38.03120045351832), Offset(5.820845611647898, 37.923977703167765), ], <Offset>[ Offset(29.9604615, 12.930571500000003), Offset(30.069674151225918, 12.990077007193268), Offset(30.452429973913663, 13.20993530875116), Offset(31.225993650435292, 13.711930969639477), Offset(32.57915576866076, 14.80992737206886), Offset(34.755617163387306, 17.489313463985035), Offset(36.59064617359396, 24.94117249139752), Offset(32.970606489923455, 33.1343019166426), Offset(28.880342148972325, 36.26796469288357), Offset(25.81843856643354, 37.672805985507075), Offset(23.450680899654806, 38.36297543990432), Offset(21.593483493165806, 38.63551498327191), Offset(20.149323305985323, 38.657677872601234), Offset(19.03763187008248, 38.56049272890903), Offset(18.192237307109178, 38.417977193922496), Offset(17.56143856857715, 38.27022919984435), Offset(17.10580322235273, 38.13854833438767), Offset(16.795158467139053, 38.03317388305801), Offset(16.606391416901644, 37.95823199538118), Offset(16.520787418267258, 37.9157110240133), ], <Offset>[ Offset(29.9604615, 12.930571500000003), Offset(30.069674151225918, 12.990077007193268), Offset(30.452429973913663, 13.20993530875116), Offset(31.225993650435292, 13.711930969639477), Offset(32.57915576866076, 14.80992737206886), Offset(34.755617163387306, 17.489313463985035), Offset(36.59064617359396, 24.94117249139752), Offset(32.970606489923455, 33.1343019166426), Offset(28.880342148972325, 36.26796469288357), Offset(25.81843856643354, 37.672805985507075), Offset(23.450680899654806, 38.36297543990432), Offset(21.593483493165806, 38.63551498327191), Offset(20.149323305985323, 38.657677872601234), Offset(19.03763187008248, 38.56049272890903), Offset(18.192237307109178, 38.417977193922496), Offset(17.56143856857715, 38.27022919984435), Offset(17.10580322235273, 38.13854833438767), Offset(16.795158467139053, 38.03317388305801), Offset(16.606391416901644, 37.95823199538118), Offset(16.520787418267258, 37.9157110240133), ], ), _PathCubicTo( <Offset>[ Offset(29.9604615, 12.930571500000003), Offset(30.069674151225918, 12.990077007193268), Offset(30.452429973913663, 13.20993530875116), Offset(31.225993650435292, 13.711930969639477), Offset(32.57915576866076, 14.80992737206886), Offset(34.755617163387306, 17.489313463985035), Offset(36.59064617359396, 24.94117249139752), Offset(32.970606489923455, 33.1343019166426), Offset(28.880342148972325, 36.26796469288357), Offset(25.81843856643354, 37.672805985507075), Offset(23.450680899654806, 38.36297543990432), Offset(21.593483493165806, 38.63551498327191), Offset(20.149323305985323, 38.657677872601234), Offset(19.03763187008248, 38.56049272890903), Offset(18.192237307109178, 38.417977193922496), Offset(17.56143856857715, 38.27022919984435), Offset(17.10580322235273, 38.13854833438767), Offset(16.795158467139053, 38.03317388305801), Offset(16.606391416901644, 37.95823199538118), Offset(16.520787418267258, 37.9157110240133), ], <Offset>[ Offset(29.9604615, 23.148505500000002), Offset(29.968593251246663, 23.207511023619084), Offset(29.992734369025463, 23.4175234263822), Offset(30.019309196684734, 23.858363241991796), Offset(29.98107228625313, 24.692039365301717), Offset(29.567641895207657, 26.2927031031725), Offset(27.218172355437773, 29.119114555268528), Offset(23.031634134758143, 30.054392954061523), Offset(20.66088155520213, 29.369552988405765), Offset(19.248749946496723, 28.58927894808191), Offset(18.30941412305796, 27.87321868277556), Offset(17.676205128355228, 27.235112579765072), Offset(17.256940842534803, 26.684950393596534), Offset(16.978219205122727, 26.228952414125168), Offset(16.7927001318866, 25.862672109267738), Offset(16.67022907552687, 25.57759197316894), Offset(16.591384127051857, 25.364575538576442), Offset(16.543638618283246, 25.21490867884989), Offset(16.518829267137072, 25.12085900336409), Offset(16.510867403281896, 25.075780856070065), ], <Offset>[ Offset(29.9604615, 23.148505500000002), Offset(29.968593251246663, 23.207511023619084), Offset(29.992734369025463, 23.4175234263822), Offset(30.019309196684734, 23.858363241991796), Offset(29.98107228625313, 24.692039365301717), Offset(29.567641895207657, 26.2927031031725), Offset(27.218172355437773, 29.119114555268528), Offset(23.031634134758143, 30.054392954061523), Offset(20.66088155520213, 29.369552988405765), Offset(19.248749946496723, 28.58927894808191), Offset(18.30941412305796, 27.87321868277556), Offset(17.676205128355228, 27.235112579765072), Offset(17.256940842534803, 26.684950393596534), Offset(16.978219205122727, 26.228952414125168), Offset(16.7927001318866, 25.862672109267738), Offset(16.67022907552687, 25.57759197316894), Offset(16.591384127051857, 25.364575538576442), Offset(16.543638618283246, 25.21490867884989), Offset(16.518829267137072, 25.12085900336409), Offset(16.510867403281896, 25.075780856070065), ], ), _PathCubicTo( <Offset>[ Offset(29.9604615, 23.148505500000002), Offset(29.968593251246663, 23.207511023619084), Offset(29.992734369025463, 23.4175234263822), Offset(30.019309196684734, 23.858363241991796), Offset(29.98107228625313, 24.692039365301717), Offset(29.567641895207657, 26.2927031031725), Offset(27.218172355437773, 29.119114555268528), Offset(23.031634134758143, 30.054392954061523), Offset(20.66088155520213, 29.369552988405765), Offset(19.248749946496723, 28.58927894808191), Offset(18.30941412305796, 27.87321868277556), Offset(17.676205128355228, 27.235112579765072), Offset(17.256940842534803, 26.684950393596534), Offset(16.978219205122727, 26.228952414125168), Offset(16.7927001318866, 25.862672109267738), Offset(16.67022907552687, 25.57759197316894), Offset(16.591384127051857, 25.364575538576442), Offset(16.543638618283246, 25.21490867884989), Offset(16.518829267137072, 25.12085900336409), Offset(16.510867403281896, 25.075780856070065), ], <Offset>[ Offset(38.4754065, 23.148505500000002), Offset(38.48312159826818, 23.291745106935128), Offset(38.49905780038466, 23.800603097122366), Offset(38.474669423645004, 24.863933620117265), Offset(38.216165613947176, 26.85710893397474), Offset(36.90379992786388, 30.61601582665554), Offset(30.699790741996942, 36.92950940373201), Offset(20.465043332607248, 38.336869916699285), Offset(14.912205134803964, 36.219103483214255), Offset(11.679144081975746, 34.064019464695924), Offset(9.567950158783995, 32.15760766327293), Offset(8.175869792099533, 30.499511217107223), Offset(7.2796679433642195, 29.095269113138635), Offset(6.701935609469508, 27.945129634924964), Offset(6.3299458946742995, 27.028953088619883), Offset(6.093031386630692, 26.32026655071084), Offset(5.946406797209165, 25.793258117993837), Offset(5.861750948109816, 25.424508552896395), Offset(5.821018440456163, 25.19382746150123), Offset(5.810925596662535, 25.084047535224535), ], <Offset>[ Offset(38.4754065, 23.148505500000002), Offset(38.48312159826818, 23.291745106935128), Offset(38.49905780038466, 23.800603097122366), Offset(38.474669423645004, 24.863933620117265), Offset(38.216165613947176, 26.85710893397474), Offset(36.90379992786388, 30.61601582665554), Offset(30.699790741996942, 36.92950940373201), Offset(20.465043332607248, 38.336869916699285), Offset(14.912205134803964, 36.219103483214255), Offset(11.679144081975746, 34.064019464695924), Offset(9.567950158783995, 32.15760766327293), Offset(8.175869792099533, 30.499511217107223), Offset(7.2796679433642195, 29.095269113138635), Offset(6.701935609469508, 27.945129634924964), Offset(6.3299458946742995, 27.028953088619883), Offset(6.093031386630692, 26.32026655071084), Offset(5.946406797209165, 25.793258117993837), Offset(5.861750948109816, 25.424508552896395), Offset(5.821018440456163, 25.19382746150123), Offset(5.810925596662535, 25.084047535224535), ], ), _PathCubicTo( <Offset>[ Offset(38.4754065, 23.148505500000002), Offset(38.48312159826818, 23.291745106935128), Offset(38.49905780038466, 23.800603097122366), Offset(38.474669423645004, 24.863933620117265), Offset(38.216165613947176, 26.85710893397474), Offset(36.90379992786388, 30.61601582665554), Offset(30.699790741996942, 36.92950940373201), Offset(20.465043332607248, 38.336869916699285), Offset(14.912205134803964, 36.219103483214255), Offset(11.679144081975746, 34.064019464695924), Offset(9.567950158783995, 32.15760766327293), Offset(8.175869792099533, 30.499511217107223), Offset(7.2796679433642195, 29.095269113138635), Offset(6.701935609469508, 27.945129634924964), Offset(6.3299458946742995, 27.028953088619883), Offset(6.093031386630692, 26.32026655071084), Offset(5.946406797209165, 25.793258117993837), Offset(5.861750948109816, 25.424508552896395), Offset(5.821018440456163, 25.19382746150123), Offset(5.810925596662535, 25.084047535224535), ], <Offset>[ Offset(38.4754065, 12.930571500000003), Offset(38.58420249824743, 13.074311090509312), Offset(38.958753405272866, 13.593014979491326), Offset(39.681353877395566, 14.717501347764943), Offset(40.81424909635481, 16.97499694074188), Offset(42.09177519604353, 21.812626187468076), Offset(40.07226456015313, 32.75156733986101), Offset(30.404015687772564, 41.41677887928036), Offset(23.131665728574156, 43.11751518769206), Offset(18.248832701912562, 43.147546502121095), Offset(14.709216935380839, 42.647364420401686), Offset(12.093148156910111, 41.89991362061406), Offset(10.17205040681474, 41.06799659214333), Offset(8.761348274429261, 40.276669949708825), Offset(7.729483069896876, 39.58425817327465), Offset(6.984240879680973, 39.012903777386256), Offset(6.460825892510038, 38.56723091380506), Offset(6.1132707969656215, 38.242773757104516), Offset(5.908580590220735, 38.03120045351832), Offset(5.820845611647898, 37.923977703167765), ], <Offset>[ Offset(38.4754065, 12.930571500000003), Offset(38.58420249824743, 13.074311090509312), Offset(38.958753405272866, 13.593014979491326), Offset(39.681353877395566, 14.717501347764943), Offset(40.81424909635481, 16.97499694074188), Offset(42.09177519604353, 21.812626187468076), Offset(40.07226456015313, 32.75156733986101), Offset(30.404015687772564, 41.41677887928036), Offset(23.131665728574156, 43.11751518769206), Offset(18.248832701912562, 43.147546502121095), Offset(14.709216935380839, 42.647364420401686), Offset(12.093148156910111, 41.89991362061406), Offset(10.17205040681474, 41.06799659214333), Offset(8.761348274429261, 40.276669949708825), Offset(7.729483069896876, 39.58425817327465), Offset(6.984240879680973, 39.012903777386256), Offset(6.460825892510038, 38.56723091380506), Offset(6.1132707969656215, 38.242773757104516), Offset(5.908580590220735, 38.03120045351832), Offset(5.820845611647898, 37.923977703167765), ], ), _PathClose( ), ], ), _PathFrames( opacities: <double>[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.146341463415, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, ], commands: <_PathCommand>[ _PathMoveTo( <Offset>[ Offset(28.257472499999995, 12.930571500000006), Offset(28.366768481821616, 12.973230190530057), Offset(28.75116528764182, 13.133319374603126), Offset(29.53492160504324, 13.510816894014384), Offset(30.932137103121953, 14.376913458334252), Offset(33.28838555685606, 16.624650919288428), Offset(35.89432249628212, 23.37909352170482), Offset(33.48392465035364, 31.477806524115046), Offset(30.030077433051954, 34.89805459392186), Offset(27.33235973933773, 36.577857882184276), Offset(25.1989736925096, 37.50609764380484), Offset(23.49355056041695, 37.98263525580348), Offset(22.14477788581944, 38.17561412869281), Offset(21.092888589213125, 38.217257284749074), Offset(20.284788154551638, 38.18472099805207), Offset(19.676878106356384, 38.12169428433597), Offset(19.234798688321266, 38.052811818504196), Offset(18.93153600117374, 37.99125390824871), Offset(18.74595358223783, 37.94363830375375), Offset(18.66077577959113, 37.914057688182396), ], ), _PathCubicTo( <Offset>[ Offset(28.257472499999995, 12.930571500000006), Offset(28.366768481821616, 12.973230190530057), Offset(28.75116528764182, 13.133319374603126), Offset(29.53492160504324, 13.510816894014384), Offset(30.932137103121953, 14.376913458334252), Offset(33.28838555685606, 16.624650919288428), Offset(35.89432249628212, 23.37909352170482), Offset(33.48392465035364, 31.477806524115046), Offset(30.030077433051954, 34.89805459392186), Offset(27.33235973933773, 36.577857882184276), Offset(25.1989736925096, 37.50609764380484), Offset(23.49355056041695, 37.98263525580348), Offset(22.14477788581944, 38.17561412869281), Offset(21.092888589213125, 38.217257284749074), Offset(20.284788154551638, 38.18472099805207), Offset(19.676878106356384, 38.12169428433597), Offset(19.234798688321266, 38.052811818504196), Offset(18.93153600117374, 37.99125390824871), Offset(18.74595358223783, 37.94363830375375), Offset(18.66077577959113, 37.914057688182396), ], <Offset>[ Offset(19.742527499999994, 12.930571500000006), Offset(19.852240134800102, 12.888996107214012), Offset(20.244841856282616, 12.75023970386296), Offset(21.07956137808297, 12.505246515888919), Offset(22.697043775427904, 12.211843889661228), Offset(25.95222752419984, 12.30133819580539), Offset(32.41270410972295, 15.568698673241332), Offset(36.05051545250454, 23.195329561477283), Offset(35.77875385345012, 28.048504099113373), Offset(34.901965603858706, 31.10311736557026), Offset(33.940437656783566, 33.221708663307474), Offset(32.993885896672644, 34.71823661846133), Offset(32.12205078499002, 35.7652954091507), Offset(31.369172184866343, 36.50108006394928), Offset(30.74754239176394, 37.01844001869992), Offset(30.25407579525256, 37.379019706794075), Offset(29.879776018163955, 37.6241292390868), Offset(29.61342367134717, 37.781654034202205), Offset(29.44376440891874, 37.87066984561661), Offset(29.36071758621049, 37.90579100902793), ], <Offset>[ Offset(19.742527499999994, 12.930571500000006), Offset(19.852240134800102, 12.888996107214012), Offset(20.244841856282616, 12.75023970386296), Offset(21.07956137808297, 12.505246515888919), Offset(22.697043775427904, 12.211843889661228), Offset(25.95222752419984, 12.30133819580539), Offset(32.41270410972295, 15.568698673241332), Offset(36.05051545250454, 23.195329561477283), Offset(35.77875385345012, 28.048504099113373), Offset(34.901965603858706, 31.10311736557026), Offset(33.940437656783566, 33.221708663307474), Offset(32.993885896672644, 34.71823661846133), Offset(32.12205078499002, 35.7652954091507), Offset(31.369172184866343, 36.50108006394928), Offset(30.74754239176394, 37.01844001869992), Offset(30.25407579525256, 37.379019706794075), Offset(29.879776018163955, 37.6241292390868), Offset(29.61342367134717, 37.781654034202205), Offset(29.44376440891874, 37.87066984561661), Offset(29.36071758621049, 37.90579100902793), ], ), _PathCubicTo( <Offset>[ Offset(19.742527499999994, 12.930571500000006), Offset(19.852240134800102, 12.888996107214012), Offset(20.244841856282616, 12.75023970386296), Offset(21.07956137808297, 12.505246515888919), Offset(22.697043775427904, 12.211843889661228), Offset(25.95222752419984, 12.30133819580539), Offset(32.41270410972295, 15.568698673241332), Offset(36.05051545250454, 23.195329561477283), Offset(35.77875385345012, 28.048504099113373), Offset(34.901965603858706, 31.10311736557026), Offset(33.940437656783566, 33.221708663307474), Offset(32.993885896672644, 34.71823661846133), Offset(32.12205078499002, 35.7652954091507), Offset(31.369172184866343, 36.50108006394928), Offset(30.74754239176394, 37.01844001869992), Offset(30.25407579525256, 37.379019706794075), Offset(29.879776018163955, 37.6241292390868), Offset(29.61342367134717, 37.781654034202205), Offset(29.44376440891874, 37.87066984561661), Offset(29.36071758621049, 37.90579100902793), ], <Offset>[ Offset(19.742527499999998, 23.148505500000006), Offset(19.751159234820847, 23.10643012363983), Offset(19.785146251394416, 22.957827821494), Offset(19.872876924332413, 22.65167878824124), Offset(20.098960293020276, 22.093955882894086), Offset(20.764252256020193, 21.104727834992858), Offset(23.040230291566765, 19.74664073711234), Offset(26.111543097339222, 20.115420598896208), Offset(27.55929325967993, 21.15009239463557), Offset(28.33227698392189, 22.01959032814509), Offset(28.79917088018672, 22.731951906178715), Offset(29.076607531862066, 23.317834214954495), Offset(29.229668321539503, 23.792567930146006), Offset(29.309759519906592, 24.16953974916542), Offset(29.348005216541363, 24.46313493404516), Offset(29.362866302202278, 24.686382480118663), Offset(29.365356922863082, 24.85015644327557), Offset(29.361903822491364, 24.96338882999409), Offset(29.356202259154166, 25.033296853599516), Offset(29.350797571225126, 25.065860841084696), ], <Offset>[ Offset(19.742527499999998, 23.148505500000006), Offset(19.751159234820847, 23.10643012363983), Offset(19.785146251394416, 22.957827821494), Offset(19.872876924332413, 22.65167878824124), Offset(20.098960293020276, 22.093955882894086), Offset(20.764252256020193, 21.104727834992858), Offset(23.040230291566765, 19.74664073711234), Offset(26.111543097339222, 20.115420598896208), Offset(27.55929325967993, 21.15009239463557), Offset(28.33227698392189, 22.01959032814509), Offset(28.79917088018672, 22.731951906178715), Offset(29.076607531862066, 23.317834214954495), Offset(29.229668321539503, 23.792567930146006), Offset(29.309759519906592, 24.16953974916542), Offset(29.348005216541363, 24.46313493404516), Offset(29.362866302202278, 24.686382480118663), Offset(29.365356922863082, 24.85015644327557), Offset(29.361903822491364, 24.96338882999409), Offset(29.356202259154166, 25.033296853599516), Offset(29.350797571225126, 25.065860841084696), ], ), _PathCubicTo( <Offset>[ Offset(19.742527499999998, 23.148505500000006), Offset(19.751159234820847, 23.10643012363983), Offset(19.785146251394416, 22.957827821494), Offset(19.872876924332413, 22.65167878824124), Offset(20.098960293020276, 22.093955882894086), Offset(20.764252256020193, 21.104727834992858), Offset(23.040230291566765, 19.74664073711234), Offset(26.111543097339222, 20.115420598896208), Offset(27.55929325967993, 21.15009239463557), Offset(28.33227698392189, 22.01959032814509), Offset(28.79917088018672, 22.731951906178715), Offset(29.076607531862066, 23.317834214954495), Offset(29.229668321539503, 23.792567930146006), Offset(29.309759519906592, 24.16953974916542), Offset(29.348005216541363, 24.46313493404516), Offset(29.362866302202278, 24.686382480118663), Offset(29.365356922863082, 24.85015644327557), Offset(29.361903822491364, 24.96338882999409), Offset(29.356202259154166, 25.033296853599516), Offset(29.350797571225126, 25.065860841084696), ], <Offset>[ Offset(28.2574725, 23.148505500000006), Offset(28.26568758184236, 23.190664206955873), Offset(28.29146968275362, 23.340907492234166), Offset(28.328237151292683, 23.657249166366704), Offset(28.334053620714325, 24.25902545156711), Offset(28.100410288676414, 25.428040558475896), Offset(26.521848678125934, 27.55703558557583), Offset(23.544952295188327, 28.39789756153397), Offset(21.810616839281764, 27.99964288944406), Offset(20.762671119400913, 27.4943308447591), Offset(20.057706915912753, 27.016340886676083), Offset(19.57627219560637, 26.582232852296645), Offset(19.25239542236892, 26.202886649688107), Offset(19.033475924253374, 25.885716969965216), Offset(18.88525097932906, 25.629415913397306), Offset(18.7856686133061, 25.429057057660565), Offset(18.720379593020393, 25.278839022692964), Offset(18.680016152317933, 25.172988704040595), Offset(18.65839143247326, 25.106265311736657), Offset(18.650855764605765, 25.074127520239166), ], <Offset>[ Offset(28.2574725, 23.148505500000006), Offset(28.26568758184236, 23.190664206955873), Offset(28.29146968275362, 23.340907492234166), Offset(28.328237151292683, 23.657249166366704), Offset(28.334053620714325, 24.25902545156711), Offset(28.100410288676414, 25.428040558475896), Offset(26.521848678125934, 27.55703558557583), Offset(23.544952295188327, 28.39789756153397), Offset(21.810616839281764, 27.99964288944406), Offset(20.762671119400913, 27.4943308447591), Offset(20.057706915912753, 27.016340886676083), Offset(19.57627219560637, 26.582232852296645), Offset(19.25239542236892, 26.202886649688107), Offset(19.033475924253374, 25.885716969965216), Offset(18.88525097932906, 25.629415913397306), Offset(18.7856686133061, 25.429057057660565), Offset(18.720379593020393, 25.278839022692964), Offset(18.680016152317933, 25.172988704040595), Offset(18.65839143247326, 25.106265311736657), Offset(18.650855764605765, 25.074127520239166), ], ), _PathCubicTo( <Offset>[ Offset(28.2574725, 23.148505500000006), Offset(28.26568758184236, 23.190664206955873), Offset(28.29146968275362, 23.340907492234166), Offset(28.328237151292683, 23.657249166366704), Offset(28.334053620714325, 24.25902545156711), Offset(28.100410288676414, 25.428040558475896), Offset(26.521848678125934, 27.55703558557583), Offset(23.544952295188327, 28.39789756153397), Offset(21.810616839281764, 27.99964288944406), Offset(20.762671119400913, 27.4943308447591), Offset(20.057706915912753, 27.016340886676083), Offset(19.57627219560637, 26.582232852296645), Offset(19.25239542236892, 26.202886649688107), Offset(19.033475924253374, 25.885716969965216), Offset(18.88525097932906, 25.629415913397306), Offset(18.7856686133061, 25.429057057660565), Offset(18.720379593020393, 25.278839022692964), Offset(18.680016152317933, 25.172988704040595), Offset(18.65839143247326, 25.106265311736657), Offset(18.650855764605765, 25.074127520239166), ], <Offset>[ Offset(28.257472499999995, 12.930571500000006), Offset(28.366768481821616, 12.973230190530057), Offset(28.75116528764182, 13.133319374603126), Offset(29.53492160504324, 13.510816894014384), Offset(30.932137103121953, 14.376913458334252), Offset(33.28838555685606, 16.624650919288428), Offset(35.89432249628212, 23.37909352170482), Offset(33.48392465035364, 31.477806524115046), Offset(30.030077433051954, 34.89805459392186), Offset(27.33235973933773, 36.577857882184276), Offset(25.1989736925096, 37.50609764380484), Offset(23.49355056041695, 37.98263525580348), Offset(22.14477788581944, 38.17561412869281), Offset(21.092888589213125, 38.217257284749074), Offset(20.284788154551638, 38.18472099805207), Offset(19.676878106356384, 38.12169428433597), Offset(19.234798688321266, 38.052811818504196), Offset(18.93153600117374, 37.99125390824871), Offset(18.74595358223783, 37.94363830375375), Offset(18.66077577959113, 37.914057688182396), ], <Offset>[ Offset(28.257472499999995, 12.930571500000006), Offset(28.366768481821616, 12.973230190530057), Offset(28.75116528764182, 13.133319374603126), Offset(29.53492160504324, 13.510816894014384), Offset(30.932137103121953, 14.376913458334252), Offset(33.28838555685606, 16.624650919288428), Offset(35.89432249628212, 23.37909352170482), Offset(33.48392465035364, 31.477806524115046), Offset(30.030077433051954, 34.89805459392186), Offset(27.33235973933773, 36.577857882184276), Offset(25.1989736925096, 37.50609764380484), Offset(23.49355056041695, 37.98263525580348), Offset(22.14477788581944, 38.17561412869281), Offset(21.092888589213125, 38.217257284749074), Offset(20.284788154551638, 38.18472099805207), Offset(19.676878106356384, 38.12169428433597), Offset(19.234798688321266, 38.052811818504196), Offset(18.93153600117374, 37.99125390824871), Offset(18.74595358223783, 37.94363830375375), Offset(18.66077577959113, 37.914057688182396), ], ), _PathClose( ), ], ), ], matchTextDirection: true, );
flutter/packages/flutter/lib/src/material/animated_icons/data/list_view.g.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/animated_icons/data/list_view.g.dart", "repo_id": "flutter", "token_count": 113363 }
626
// 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 'package:flutter/widgets.dart'; import 'banner_theme.dart'; import 'color_scheme.dart'; import 'colors.dart'; import 'divider.dart'; import 'material.dart'; import 'scaffold.dart'; import 'text_theme.dart'; import 'theme.dart'; // Examples can assume: // late BuildContext context; const Duration _materialBannerTransitionDuration = Duration(milliseconds: 250); const Curve _materialBannerHeightCurve = Curves.fastOutSlowIn; const double _kMaxContentTextScaleFactor = 1.5; /// Specify how a [MaterialBanner] was closed. /// /// The [ScaffoldMessengerState.showMaterialBanner] function returns a /// [ScaffoldFeatureController]. The value of the controller's closed property /// is a Future that resolves to a MaterialBannerClosedReason. Applications that need /// to know how a [MaterialBanner] was closed can use this value. /// /// Example: /// /// ```dart /// ScaffoldMessenger.of(context).showMaterialBanner( /// const MaterialBanner( /// content: Text('Message...'), /// actions: <Widget>[ /// // ... /// ], /// ) /// ).closed.then((MaterialBannerClosedReason reason) { /// // ... /// }); /// ``` enum MaterialBannerClosedReason { /// The material banner was closed through a [SemanticsAction.dismiss]. dismiss, /// The material banner was closed by a user's swipe. swipe, /// The material banner was closed by the [ScaffoldFeatureController] close callback /// or by calling [ScaffoldMessengerState.hideCurrentMaterialBanner] directly. hide, /// The material banner was closed by a call to [ScaffoldMessengerState.removeCurrentMaterialBanner]. remove, } /// A Material Design banner. /// /// A banner displays an important, succinct message, and provides actions for /// users to address (or dismiss the banner). A user action is required for it /// to be dismissed. /// /// Banners should be displayed at the top of the screen, below a top app bar. /// They are persistent and non-modal, allowing the user to either ignore them or /// interact with them at any time. /// /// {@tool dartpad} /// Banners placed directly into the widget tree are static. /// /// ** See code in examples/api/lib/material/banner/material_banner.0.dart ** /// {@end-tool} /// /// {@tool dartpad} /// MaterialBanner's can also be presented through a [ScaffoldMessenger]. /// Here is an example where ScaffoldMessengerState.showMaterialBanner() is used to show the MaterialBanner. /// /// ** See code in examples/api/lib/material/banner/material_banner.1.dart ** /// {@end-tool} /// /// The [actions] will be placed beside the [content] if there is only one. /// Otherwise, the [actions] will be placed below the [content]. Use /// [forceActionsBelow] to override this behavior. /// /// If the [actions] placed below the [content], they will be laid out in a row. /// If there isn't sufficient room to display everything, they are laid out /// in a column instead. /// /// The [actions] and [content] must be provided. An optional leading widget /// (typically an [Image]) can also be provided. The [contentTextStyle] and /// [backgroundColor] can be provided to customize the banner. /// /// This widget is unrelated to the widgets library [Banner] widget. class MaterialBanner extends StatefulWidget { /// Creates a [MaterialBanner]. /// /// The length of the [actions] list must not be empty. The [elevation] must /// be null or non-negative. const MaterialBanner({ super.key, required this.content, this.contentTextStyle, required this.actions, this.elevation, this.leading, this.backgroundColor, this.surfaceTintColor, this.shadowColor, this.dividerColor, this.padding, this.margin, this.leadingPadding, this.forceActionsBelow = false, this.overflowAlignment = OverflowBarAlignment.end, this.animation, this.onVisible, }) : assert(elevation == null || elevation >= 0.0); /// The content of the [MaterialBanner]. /// /// Typically a [Text] widget. final Widget content; /// Style for the text in the [content] of the [MaterialBanner]. /// /// If `null`, [MaterialBannerThemeData.contentTextStyle] is used. If that is /// also `null`, [TextTheme.bodyMedium] of [ThemeData.textTheme] is used. final TextStyle? contentTextStyle; /// The set of actions that are displayed at the bottom or trailing side of /// the [MaterialBanner]. /// /// Typically this is a list of [TextButton] widgets. final List<Widget> actions; /// The z-coordinate at which to place the material banner. /// /// This controls the size of the shadow below the material banner. /// /// Defines the banner's [Material.elevation]. /// /// If this property is null, then [MaterialBannerThemeData.elevation] of /// [ThemeData.bannerTheme] is used, if that is also null, the default value is 0. /// If the elevation is 0, the [Scaffold]'s body will be pushed down by the /// MaterialBanner when used with [ScaffoldMessenger]. final double? elevation; /// The (optional) leading widget of the [MaterialBanner]. /// /// Typically an [Icon] widget. final Widget? leading; /// The color of the surface of this [MaterialBanner]. /// /// If `null`, [MaterialBannerThemeData.backgroundColor] is used. If that is /// also `null`, [ColorScheme.surfaceContainerLow] of [ThemeData.colorScheme] is used. final Color? backgroundColor; /// The color used as an overlay on [backgroundColor] to indicate elevation. /// /// If null, [MaterialBannerThemeData.surfaceTintColor] is used. If that /// is also null, the default value is [Colors.transparent]. /// /// 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. final Color? surfaceTintColor; /// The color of the shadow below the [MaterialBanner]. /// /// If this property is null, then [MaterialBannerThemeData.shadowColor] of /// [ThemeData.bannerTheme] is used. If that is also null, the default value /// is null. final Color? shadowColor; /// The color of the divider. /// /// If this property is null, then [MaterialBannerThemeData.dividerColor] of /// [ThemeData.bannerTheme] is used. If that is also null, the default value /// is [ColorScheme.surfaceVariant]. final Color? dividerColor; /// The amount of space by which to inset the [content]. /// /// If the [actions] are below the [content], this defaults to /// `EdgeInsetsDirectional.only(start: 16.0, top: 24.0, end: 16.0, bottom: 4.0)`. /// /// If the [actions] are trailing the [content], this defaults to /// `EdgeInsetsDirectional.only(start: 16.0, top: 2.0)`. final EdgeInsetsGeometry? padding; /// Empty space to surround the [MaterialBanner]. /// /// If the [margin] is null then this defaults to /// 0 if the banner's [elevation] is 0, 10 otherwise. final EdgeInsetsGeometry? margin; /// The amount of space by which to inset the [leading] widget. /// /// This defaults to `EdgeInsetsDirectional.only(end: 16.0)`. final EdgeInsetsGeometry? leadingPadding; /// An override to force the [actions] to be below the [content] regardless of /// how many there are. /// /// If this is true, the [actions] will be placed below the [content]. If /// this is false, the [actions] will be placed on the trailing side of the /// [content] if [actions]'s length is 1 and below the [content] if greater /// than 1. /// /// Defaults to false. final bool forceActionsBelow; /// The horizontal alignment of the [actions] when the [actions] laid out in a column. /// /// Defaults to [OverflowBarAlignment.end]. final OverflowBarAlignment overflowAlignment; /// The animation driving the entrance and exit of the material banner when presented by the [ScaffoldMessenger]. final Animation<double>? animation; /// Called the first time that the material banner is visible within a [Scaffold] when presented by the [ScaffoldMessenger]. final VoidCallback? onVisible; // API for ScaffoldMessengerState.showMaterialBanner(): /// Creates an animation controller useful for driving a [MaterialBanner]'s entrance and exit animation. static AnimationController createAnimationController({ required TickerProvider vsync }) { return AnimationController( duration: _materialBannerTransitionDuration, debugLabel: 'MaterialBanner', vsync: vsync, ); } /// Creates a copy of this material banner but with the animation replaced with the given animation. /// /// If the original material banner lacks a key, the newly created material banner will /// use the given fallback key. MaterialBanner withAnimation(Animation<double> newAnimation, { Key? fallbackKey }) { return MaterialBanner( key: key ?? fallbackKey, content: content, contentTextStyle: contentTextStyle, actions: actions, elevation: elevation, leading: leading, backgroundColor: backgroundColor, surfaceTintColor: surfaceTintColor, shadowColor: shadowColor, dividerColor: dividerColor, padding: padding, margin: margin, leadingPadding: leadingPadding, forceActionsBelow: forceActionsBelow, overflowAlignment: overflowAlignment, animation: newAnimation, onVisible: onVisible, ); } @override State<MaterialBanner> createState() => _MaterialBannerState(); } class _MaterialBannerState extends State<MaterialBanner> { bool _wasVisible = false; @override void initState() { super.initState(); widget.animation?.addStatusListener(_onAnimationStatusChanged); } @override void didUpdateWidget(MaterialBanner oldWidget) { super.didUpdateWidget(oldWidget); if (widget.animation != oldWidget.animation) { oldWidget.animation?.removeStatusListener(_onAnimationStatusChanged); widget.animation?.addStatusListener(_onAnimationStatusChanged); } } @override void dispose() { widget.animation?.removeStatusListener(_onAnimationStatusChanged); super.dispose(); } void _onAnimationStatusChanged(AnimationStatus animationStatus) { switch (animationStatus) { case AnimationStatus.dismissed: case AnimationStatus.forward: case AnimationStatus.reverse: break; case AnimationStatus.completed: if (widget.onVisible != null && !_wasVisible) { widget.onVisible!(); } _wasVisible = true; } } @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); final bool accessibleNavigation = MediaQuery.accessibleNavigationOf(context); assert(widget.actions.isNotEmpty); final ThemeData theme = Theme.of(context); final MaterialBannerThemeData bannerTheme = MaterialBannerTheme.of(context); final MaterialBannerThemeData defaults = theme.useMaterial3 ? _BannerDefaultsM3(context) : _BannerDefaultsM2(context); final bool isSingleRow = widget.actions.length == 1 && !widget.forceActionsBelow; final EdgeInsetsGeometry padding = widget.padding ?? bannerTheme.padding ?? (isSingleRow ? const EdgeInsetsDirectional.only(start: 16.0, top: 2.0) : const EdgeInsetsDirectional.only(start: 16.0, top: 24.0, end: 16.0, bottom: 4.0)); final EdgeInsetsGeometry leadingPadding = widget.leadingPadding ?? bannerTheme.leadingPadding ?? const EdgeInsetsDirectional.only(end: 16.0); final Widget actionsBar = Container( alignment: AlignmentDirectional.centerEnd, constraints: const BoxConstraints(minHeight: 52.0), padding: const EdgeInsets.symmetric(horizontal: 8), child: OverflowBar( overflowAlignment: widget.overflowAlignment, spacing: 8, children: widget.actions, ), ); final double elevation = widget.elevation ?? bannerTheme.elevation ?? 0.0; final EdgeInsetsGeometry margin = widget.margin ?? EdgeInsets.only(bottom: elevation > 0 ? 10.0 : 0.0); final Color backgroundColor = widget.backgroundColor ?? bannerTheme.backgroundColor ?? defaults.backgroundColor!; final Color? surfaceTintColor = widget.surfaceTintColor ?? bannerTheme.surfaceTintColor ?? defaults.surfaceTintColor; final Color? shadowColor = widget.shadowColor ?? bannerTheme.shadowColor; final Color? dividerColor = widget.dividerColor ?? bannerTheme.dividerColor ?? defaults.dividerColor; final TextStyle? textStyle = widget.contentTextStyle ?? bannerTheme.contentTextStyle ?? defaults.contentTextStyle; Widget materialBanner = Container( margin: margin, child: Material( elevation: elevation, color: backgroundColor, surfaceTintColor: surfaceTintColor, shadowColor: shadowColor, child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Padding( padding: padding, child: Row( children: <Widget>[ if (widget.leading != null) Padding( padding: leadingPadding, child: widget.leading, ), MediaQuery.withClampedTextScaling( // Set maximum text scale factor to _kMaxContentTextScaleFactor for the // content to keep the visual hierarchy the same even with larger font // sizes. maxScaleFactor: _kMaxContentTextScaleFactor, child: Expanded( child: DefaultTextStyle( style: textStyle!, child: widget.content, ), ), ), if (isSingleRow) MediaQuery.withClampedTextScaling( // Set maximum text scale factor to _kMaxContentTextScaleFactor for the // actionsBar to keep the visual hierarchy the same even with larger font // sizes. maxScaleFactor: _kMaxContentTextScaleFactor, child: actionsBar, ), ], ), ), if (!isSingleRow) actionsBar, if (elevation == 0) Divider(height: 0, color: dividerColor), ], ), ), ); // This provides a static banner for backwards compatibility. if (widget.animation == null) { return materialBanner; } materialBanner = SafeArea( child: materialBanner, ); final CurvedAnimation heightAnimation = CurvedAnimation(parent: widget.animation!, curve: _materialBannerHeightCurve); final Animation<Offset> slideOutAnimation = Tween<Offset>( begin: const Offset(0.0, -1.0), end: Offset.zero, ).animate(CurvedAnimation( parent: widget.animation!, curve: const Threshold(0.0), )); materialBanner = Semantics( container: true, liveRegion: true, onDismiss: () { ScaffoldMessenger.of(context).removeCurrentMaterialBanner(reason: MaterialBannerClosedReason.dismiss); }, child: accessibleNavigation ? materialBanner : SlideTransition( position: slideOutAnimation, child: materialBanner, ), ); final Widget materialBannerTransition; if (accessibleNavigation) { materialBannerTransition = materialBanner; } else { materialBannerTransition = AnimatedBuilder( animation: heightAnimation, builder: (BuildContext context, Widget? child) { return Align( alignment: AlignmentDirectional.bottomStart, heightFactor: heightAnimation.value, child: child, ); }, child: materialBanner, ); } return Hero( tag: '<MaterialBanner Hero tag - ${widget.content}>', child: ClipRect(child: materialBannerTransition), ); } } class _BannerDefaultsM2 extends MaterialBannerThemeData { _BannerDefaultsM2(this.context) : _theme = Theme.of(context), super(elevation: 0.0); final BuildContext context; final ThemeData _theme; @override Color? get backgroundColor => _theme.colorScheme.surface; @override TextStyle? get contentTextStyle => _theme.textTheme.bodyMedium; } // BEGIN GENERATED TOKEN PROPERTIES - Banner // Do not edit by hand. The code between the "BEGIN GENERATED" and // "END GENERATED" comments are generated from data in the Material // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. class _BannerDefaultsM3 extends MaterialBannerThemeData { _BannerDefaultsM3(this.context) : super(elevation: 1.0); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; late final TextTheme _textTheme = Theme.of(context).textTheme; @override Color? get backgroundColor => _colors.surfaceContainerLow; @override Color? get surfaceTintColor => Colors.transparent; @override Color? get dividerColor => _colors.outlineVariant; @override TextStyle? get contentTextStyle => _textTheme.bodyMedium; } // END GENERATED TOKEN PROPERTIES - Banner
flutter/packages/flutter/lib/src/material/banner.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/banner.dart", "repo_id": "flutter", "token_count": 6084 }
627
// 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:ui' show lerpDouble; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'theme.dart'; /// Defines default property values for descendant [Card] widgets. /// /// Descendant widgets obtain the current [CardTheme] object using /// `CardTheme.of(context)`. Instances of [CardTheme] can be /// customized with [CardTheme.copyWith]. /// /// Typically a [CardTheme] is specified as part of the overall [Theme] /// with [ThemeData.cardTheme]. /// /// All [CardTheme] properties are `null` by default. When null, the [Card] /// will use the values from [ThemeData] if they exist, otherwise it will /// provide its own defaults. /// /// See also: /// /// * [ThemeData], which describes the overall theme information for the /// application. @immutable class CardTheme with Diagnosticable { /// Creates a theme that can be used for [ThemeData.cardTheme]. /// /// The [elevation] must be null or non-negative. const CardTheme({ this.clipBehavior, this.color, this.shadowColor, this.surfaceTintColor, this.elevation, this.margin, this.shape, }) : assert(elevation == null || elevation >= 0.0); /// Overrides the default value for [Card.clipBehavior]. /// /// If null, [Card] uses [Clip.none]. final Clip? clipBehavior; /// Overrides the default value for [Card.color]. /// /// If null, [Card] uses [ThemeData.cardColor]. final Color? color; /// Overrides the default value for [Card.shadowColor]. /// /// If null, [Card] defaults to fully opaque black. final Color? shadowColor; /// Overrides the default value for [Card.surfaceTintColor]. /// /// If null, [Card] will not display an overlay color. /// /// See [Material.surfaceTintColor] for more details. final Color? surfaceTintColor; /// Overrides the default value for [Card.elevation]. /// /// If null, [Card] uses a default of 1.0. final double? elevation; /// Overrides the default value for [Card.margin]. /// /// If null, [Card] uses a default margin of 4.0 logical pixels on all sides: /// `EdgeInsets.all(4.0)`. final EdgeInsetsGeometry? margin; /// Overrides the default value for [Card.shape]. /// /// If null, [Card] then uses a [RoundedRectangleBorder] with a circular /// corner radius of 12.0 and if [ThemeData.useMaterial3] is false, /// then the circular corner radius will be 4.0. final ShapeBorder? shape; /// Creates a copy of this object with the given fields replaced with the /// new values. CardTheme copyWith({ Clip? clipBehavior, Color? color, Color? shadowColor, Color? surfaceTintColor, double? elevation, EdgeInsetsGeometry? margin, ShapeBorder? shape, }) { return CardTheme( clipBehavior: clipBehavior ?? this.clipBehavior, color: color ?? this.color, shadowColor: shadowColor ?? this.shadowColor, surfaceTintColor: surfaceTintColor ?? this.surfaceTintColor, elevation: elevation ?? this.elevation, margin: margin ?? this.margin, shape: shape ?? this.shape, ); } /// The [ThemeData.cardTheme] property of the ambient [Theme]. static CardTheme of(BuildContext context) { return Theme.of(context).cardTheme; } /// Linearly interpolate between two Card themes. /// /// {@macro dart.ui.shadow.lerp} static CardTheme lerp(CardTheme? a, CardTheme? b, double t) { if (identical(a, b) && a != null) { return a; } return CardTheme( clipBehavior: t < 0.5 ? a?.clipBehavior : b?.clipBehavior, color: Color.lerp(a?.color, b?.color, t), shadowColor: Color.lerp(a?.shadowColor, b?.shadowColor, t), surfaceTintColor: Color.lerp(a?.surfaceTintColor, b?.surfaceTintColor, t), elevation: lerpDouble(a?.elevation, b?.elevation, t), margin: EdgeInsetsGeometry.lerp(a?.margin, b?.margin, t), shape: ShapeBorder.lerp(a?.shape, b?.shape, t), ); } @override int get hashCode => Object.hash( clipBehavior, color, shadowColor, surfaceTintColor, elevation, margin, shape, ); @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is CardTheme && other.clipBehavior == clipBehavior && other.color == color && other.shadowColor == shadowColor && other.surfaceTintColor == surfaceTintColor && other.elevation == elevation && other.margin == margin && other.shape == shape; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<Clip>('clipBehavior', clipBehavior, defaultValue: null)); properties.add(ColorProperty('color', color, defaultValue: null)); properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null)); properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, defaultValue: null)); properties.add(DiagnosticsProperty<double>('elevation', elevation, defaultValue: null)); properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('margin', margin, defaultValue: null)); properties.add(DiagnosticsProperty<ShapeBorder>('shape', shape, defaultValue: null)); } }
flutter/packages/flutter/lib/src/material/card_theme.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/card_theme.dart", "repo_id": "flutter", "token_count": 1867 }
628
// 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 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'app_bar.dart'; import 'back_button.dart'; import 'button_style.dart'; import 'calendar_date_picker.dart'; import 'color_scheme.dart'; import 'date.dart'; import 'date_picker_theme.dart'; import 'debug.dart'; import 'dialog.dart'; import 'dialog_theme.dart'; import 'divider.dart'; import 'icon_button.dart'; import 'icons.dart'; import 'ink_well.dart'; import 'input_border.dart'; import 'input_date_picker_form_field.dart'; import 'input_decorator.dart'; import 'material.dart'; import 'material_localizations.dart'; import 'material_state.dart'; import 'scaffold.dart'; import 'text_button.dart'; import 'text_field.dart'; import 'text_theme.dart'; import 'theme.dart'; // The M3 sizes are coming from the tokens, but are hand coded, // as the current token DB does not contain landscape versions. const Size _calendarPortraitDialogSizeM2 = Size(330.0, 518.0); const Size _calendarPortraitDialogSizeM3 = Size(328.0, 512.0); const Size _calendarLandscapeDialogSize = Size(496.0, 346.0); const Size _inputPortraitDialogSizeM2 = Size(330.0, 270.0); const Size _inputPortraitDialogSizeM3 = Size(328.0, 270.0); const Size _inputLandscapeDialogSize = Size(496, 160.0); const Size _inputRangeLandscapeDialogSize = Size(496, 164.0); const Duration _dialogSizeAnimationDuration = Duration(milliseconds: 200); const double _inputFormPortraitHeight = 98.0; const double _inputFormLandscapeHeight = 108.0; const double _kMaxTextScaleFactor = 1.3; /// Shows a dialog containing a Material Design date picker. /// /// The returned [Future] resolves to the date selected by the user when the /// user confirms the dialog. If the user cancels the dialog, null is returned. /// /// When the date picker is first displayed, if [initialDate] is not null, it /// will show the month of [initialDate], with [initialDate] selected. Otherwise /// it will show the [currentDate]'s month. /// /// The [firstDate] is the earliest allowable date. The [lastDate] is the latest /// allowable date. If [initialDate] is not null, it must either fall between /// these dates, or be equal to one of them. For each of these [DateTime] /// parameters, only their dates are considered. Their time fields are ignored. /// They must all be non-null. /// /// The [currentDate] represents the current day (i.e. today). This /// date will be highlighted in the day grid. If null, the date of /// [DateTime.now] will be used. /// /// An optional [initialEntryMode] argument can be used to display the date /// picker in the [DatePickerEntryMode.calendar] (a calendar month grid) /// or [DatePickerEntryMode.input] (a text input field) mode. /// It defaults to [DatePickerEntryMode.calendar]. /// /// {@template flutter.material.date_picker.switchToInputEntryModeIcon} /// An optional [switchToInputEntryModeIcon] argument can be used to /// display a custom Icon in the corner of the dialog /// when [DatePickerEntryMode] is [DatePickerEntryMode.calendar]. Clicking on /// icon changes the [DatePickerEntryMode] to [DatePickerEntryMode.input]. /// If null, `Icon(useMaterial3 ? Icons.edit_outlined : Icons.edit)` is used. /// {@endtemplate} /// /// {@template flutter.material.date_picker.switchToCalendarEntryModeIcon} /// An optional [switchToCalendarEntryModeIcon] argument can be used to /// display a custom Icon in the corner of the dialog /// when [DatePickerEntryMode] is [DatePickerEntryMode.input]. Clicking on /// icon changes the [DatePickerEntryMode] to [DatePickerEntryMode.calendar]. /// If null, `Icon(Icons.calendar_today)` is used. /// {@endtemplate} /// /// An optional [selectableDayPredicate] function can be passed in to only allow /// certain days for selection. If provided, only the days that /// [selectableDayPredicate] returns true for will be selectable. For example, /// this can be used to only allow weekdays for selection. If provided, it must /// return true for [initialDate]. /// /// The following optional string parameters allow you to override the default /// text used for various parts of the dialog: /// /// * [helpText], label displayed at the top of the dialog. /// * [cancelText], label on the cancel button. /// * [confirmText], label on the ok button. /// * [errorFormatText], message used when the input text isn't in a proper date format. /// * [errorInvalidText], message used when the input text isn't a selectable date. /// * [fieldHintText], text used to prompt the user when no text has been entered in the field. /// * [fieldLabelText], label for the date text input field. /// /// An optional [locale] argument can be used to set the locale for the date /// picker. It defaults to the ambient locale provided by [Localizations]. /// /// An optional [textDirection] argument can be used to set the text direction /// ([TextDirection.ltr] or [TextDirection.rtl]) for the date picker. It /// defaults to the ambient text direction provided by [Directionality]. If both /// [locale] and [textDirection] are non-null, [textDirection] overrides the /// direction chosen for the [locale]. /// /// The [context], [barrierDismissible], [barrierColor], [barrierLabel], /// [useRootNavigator] and [routeSettings] arguments are passed to [showDialog], /// the documentation for which discusses how it is used. /// /// The [builder] parameter can be used to wrap the dialog widget /// to add inherited widgets like [Theme]. /// /// An optional [initialDatePickerMode] argument can be used to have the /// calendar date picker initially appear in the [DatePickerMode.year] or /// [DatePickerMode.day] mode. It defaults to [DatePickerMode.day]. /// /// {@macro flutter.widgets.RawDialogRoute} /// /// ### State Restoration /// /// Using this method will not enable state restoration for the date picker. /// In order to enable state restoration for a date picker, use /// [Navigator.restorablePush] or [Navigator.restorablePushNamed] with /// [DatePickerDialog]. /// /// For more information about state restoration, see [RestorationManager]. /// /// {@macro flutter.widgets.RestorationManager} /// /// {@tool dartpad} /// This sample demonstrates how to create a restorable Material date picker. /// This is accomplished by enabling state restoration by specifying /// [MaterialApp.restorationScopeId] and using [Navigator.restorablePush] to /// push [DatePickerDialog] when the button is tapped. /// /// ** See code in examples/api/lib/material/date_picker/show_date_picker.0.dart ** /// {@end-tool} /// /// See also: /// /// * [showDateRangePicker], which shows a Material Design date range picker /// used to select a range of dates. /// * [CalendarDatePicker], which provides the calendar grid used by the date picker dialog. /// * [InputDatePickerFormField], which provides a text input field for entering dates. /// * [DisplayFeatureSubScreen], which documents the specifics of how /// [DisplayFeature]s can split the screen into sub-screens. /// * [showTimePicker], which shows a dialog that contains a Material Design time picker. Future<DateTime?> showDatePicker({ required BuildContext context, DateTime? initialDate, required DateTime firstDate, required DateTime lastDate, DateTime? currentDate, DatePickerEntryMode initialEntryMode = DatePickerEntryMode.calendar, SelectableDayPredicate? selectableDayPredicate, String? helpText, String? cancelText, String? confirmText, Locale? locale, bool barrierDismissible = true, Color? barrierColor, String? barrierLabel, bool useRootNavigator = true, RouteSettings? routeSettings, TextDirection? textDirection, TransitionBuilder? builder, DatePickerMode initialDatePickerMode = DatePickerMode.day, String? errorFormatText, String? errorInvalidText, String? fieldHintText, String? fieldLabelText, TextInputType? keyboardType, Offset? anchorPoint, final ValueChanged<DatePickerEntryMode>? onDatePickerModeChange, final Icon? switchToInputEntryModeIcon, final Icon? switchToCalendarEntryModeIcon, }) async { initialDate = initialDate == null ? null : DateUtils.dateOnly(initialDate); firstDate = DateUtils.dateOnly(firstDate); lastDate = DateUtils.dateOnly(lastDate); assert( !lastDate.isBefore(firstDate), 'lastDate $lastDate must be on or after firstDate $firstDate.', ); assert( initialDate == null || !initialDate.isBefore(firstDate), 'initialDate $initialDate must be on or after firstDate $firstDate.', ); assert( initialDate == null || !initialDate.isAfter(lastDate), 'initialDate $initialDate must be on or before lastDate $lastDate.', ); assert( selectableDayPredicate == null || initialDate == null || selectableDayPredicate(initialDate), 'Provided initialDate $initialDate must satisfy provided selectableDayPredicate.', ); assert(debugCheckHasMaterialLocalizations(context)); Widget dialog = DatePickerDialog( initialDate: initialDate, firstDate: firstDate, lastDate: lastDate, currentDate: currentDate, initialEntryMode: initialEntryMode, selectableDayPredicate: selectableDayPredicate, helpText: helpText, cancelText: cancelText, confirmText: confirmText, initialCalendarMode: initialDatePickerMode, errorFormatText: errorFormatText, errorInvalidText: errorInvalidText, fieldHintText: fieldHintText, fieldLabelText: fieldLabelText, keyboardType: keyboardType, onDatePickerModeChange: onDatePickerModeChange, switchToInputEntryModeIcon: switchToInputEntryModeIcon, switchToCalendarEntryModeIcon: switchToCalendarEntryModeIcon, ); if (textDirection != null) { dialog = Directionality( textDirection: textDirection, child: dialog, ); } if (locale != null) { dialog = Localizations.override( context: context, locale: locale, child: dialog, ); } return showDialog<DateTime>( context: context, barrierDismissible: barrierDismissible, barrierColor: barrierColor, barrierLabel: barrierLabel, useRootNavigator: useRootNavigator, routeSettings: routeSettings, builder: (BuildContext context) { return builder == null ? dialog : builder(context, dialog); }, anchorPoint: anchorPoint, ); } /// A Material-style date picker dialog. /// /// It is used internally by [showDatePicker] or can be directly pushed /// onto the [Navigator] stack to enable state restoration. See /// [showDatePicker] for a state restoration app example. /// /// See also: /// /// * [showDatePicker], which is a way to display the date picker. class DatePickerDialog extends StatefulWidget { /// A Material-style date picker dialog. DatePickerDialog({ super.key, DateTime? initialDate, required DateTime firstDate, required DateTime lastDate, DateTime? currentDate, this.initialEntryMode = DatePickerEntryMode.calendar, this.selectableDayPredicate, this.cancelText, this.confirmText, this.helpText, this.initialCalendarMode = DatePickerMode.day, this.errorFormatText, this.errorInvalidText, this.fieldHintText, this.fieldLabelText, this.keyboardType, this.restorationId, this.onDatePickerModeChange, this.switchToInputEntryModeIcon, this.switchToCalendarEntryModeIcon, }) : initialDate = initialDate == null ? null : DateUtils.dateOnly(initialDate), firstDate = DateUtils.dateOnly(firstDate), lastDate = DateUtils.dateOnly(lastDate), currentDate = DateUtils.dateOnly(currentDate ?? DateTime.now()) { assert( !this.lastDate.isBefore(this.firstDate), 'lastDate ${this.lastDate} must be on or after firstDate ${this.firstDate}.', ); assert( initialDate == null || !this.initialDate!.isBefore(this.firstDate), 'initialDate ${this.initialDate} must be on or after firstDate ${this.firstDate}.', ); assert( initialDate == null || !this.initialDate!.isAfter(this.lastDate), 'initialDate ${this.initialDate} must be on or before lastDate ${this.lastDate}.', ); assert( selectableDayPredicate == null || initialDate == null || selectableDayPredicate!(this.initialDate!), 'Provided initialDate ${this.initialDate} must satisfy provided selectableDayPredicate', ); } /// The initially selected [DateTime] that the picker should display. /// /// If this is null, there is no selected date. A date must be selected to /// submit the dialog. final DateTime? initialDate; /// The earliest allowable [DateTime] that the user can select. final DateTime firstDate; /// The latest allowable [DateTime] that the user can select. final DateTime lastDate; /// The [DateTime] representing today. It will be highlighted in the day grid. final DateTime currentDate; /// The initial mode of date entry method for the date picker dialog. /// /// See [DatePickerEntryMode] for more details on the different data entry /// modes available. final DatePickerEntryMode initialEntryMode; /// Function to provide full control over which [DateTime] can be selected. final SelectableDayPredicate? selectableDayPredicate; /// The text that is displayed on the cancel button. final String? cancelText; /// The text that is displayed on the confirm button. final String? confirmText; /// The text that is displayed at the top of the header. /// /// This is used to indicate to the user what they are selecting a date for. final String? helpText; /// The initial display of the calendar picker. final DatePickerMode initialCalendarMode; /// The error text displayed if the entered date is not in the correct format. final String? errorFormatText; /// The error text displayed if the date is not valid. /// /// A date is not valid if it is earlier than [firstDate], later than /// [lastDate], or doesn't pass the [selectableDayPredicate]. final String? errorInvalidText; /// The hint text displayed in the [TextField]. /// /// If this is null, it will default to the date format string. For example, /// 'mm/dd/yyyy' for en_US. final String? fieldHintText; /// The label text displayed in the [TextField]. /// /// If this is null, it will default to the words representing the date format /// string. For example, 'Month, Day, Year' for en_US. final String? fieldLabelText; /// {@template flutter.material.datePickerDialog} /// The keyboard type of the [TextField]. /// /// If this is null, it will default to [TextInputType.datetime] /// {@endtemplate} final TextInputType? keyboardType; /// Restoration ID to save and restore the state of the [DatePickerDialog]. /// /// If it is non-null, the date picker will persist and restore the /// date selected on the dialog. /// /// The state of this widget is persisted in a [RestorationBucket] claimed /// from the surrounding [RestorationScope] using the provided restoration ID. /// /// See also: /// /// * [RestorationManager], which explains how state restoration works in /// Flutter. final String? restorationId; /// Called when the [DatePickerDialog] is toggled between /// [DatePickerEntryMode.calendar],[DatePickerEntryMode.input]. /// /// An example of how this callback might be used is an app that saves the /// user's preferred entry mode and uses it to initialize the /// `initialEntryMode` parameter the next time the date picker is shown. final ValueChanged<DatePickerEntryMode>? onDatePickerModeChange; /// {@macro flutter.material.date_picker.switchToInputEntryModeIcon} final Icon? switchToInputEntryModeIcon; /// {@macro flutter.material.date_picker.switchToCalendarEntryModeIcon} final Icon? switchToCalendarEntryModeIcon; @override State<DatePickerDialog> createState() => _DatePickerDialogState(); } class _DatePickerDialogState extends State<DatePickerDialog> with RestorationMixin { late final RestorableDateTimeN _selectedDate = RestorableDateTimeN(widget.initialDate); late final _RestorableDatePickerEntryMode _entryMode = _RestorableDatePickerEntryMode(widget.initialEntryMode); final _RestorableAutovalidateMode _autovalidateMode = _RestorableAutovalidateMode(AutovalidateMode.disabled); @override void dispose() { _selectedDate.dispose(); _entryMode.dispose(); _autovalidateMode.dispose(); super.dispose(); } @override String? get restorationId => widget.restorationId; @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_selectedDate, 'selected_date'); registerForRestoration(_autovalidateMode, 'autovalidateMode'); registerForRestoration(_entryMode, 'calendar_entry_mode'); } final GlobalKey _calendarPickerKey = GlobalKey(); final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); void _handleOk() { if (_entryMode.value == DatePickerEntryMode.input || _entryMode.value == DatePickerEntryMode.inputOnly) { final FormState form = _formKey.currentState!; if (!form.validate()) { setState(() => _autovalidateMode.value = AutovalidateMode.always); return; } form.save(); } Navigator.pop(context, _selectedDate.value); } void _handleCancel() { Navigator.pop(context); } void _handleOnDatePickerModeChange() { widget.onDatePickerModeChange?.call(_entryMode.value); } void _handleEntryModeToggle() { setState(() { switch (_entryMode.value) { case DatePickerEntryMode.calendar: _autovalidateMode.value = AutovalidateMode.disabled; _entryMode.value = DatePickerEntryMode.input; _handleOnDatePickerModeChange(); case DatePickerEntryMode.input: _formKey.currentState!.save(); _entryMode.value = DatePickerEntryMode.calendar; _handleOnDatePickerModeChange(); case DatePickerEntryMode.calendarOnly: case DatePickerEntryMode.inputOnly: assert(false, 'Can not change entry mode from ${_entryMode.value}'); } }); } void _handleDateChanged(DateTime date) { setState(() { _selectedDate.value = date; }); } Size _dialogSize(BuildContext context) { final bool useMaterial3 = Theme.of(context).useMaterial3; final bool isCalendar = switch (_entryMode.value) { DatePickerEntryMode.calendar || DatePickerEntryMode.calendarOnly => true, DatePickerEntryMode.input || DatePickerEntryMode.inputOnly => false, }; final Orientation orientation = MediaQuery.orientationOf(context); return switch ((isCalendar, orientation)) { (true, Orientation.portrait) when useMaterial3 => _calendarPortraitDialogSizeM3, (false, Orientation.portrait) when useMaterial3 => _inputPortraitDialogSizeM3, (true, Orientation.portrait) => _calendarPortraitDialogSizeM2, (false, Orientation.portrait) => _inputPortraitDialogSizeM2, (true, Orientation.landscape) => _calendarLandscapeDialogSize, (false, Orientation.landscape) => _inputLandscapeDialogSize, }; } static const Map<ShortcutActivator, Intent> _formShortcutMap = <ShortcutActivator, Intent>{ // Pressing enter on the field will move focus to the next field or control. SingleActivator(LogicalKeyboardKey.enter): NextFocusIntent(), }; @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final bool useMaterial3 = theme.useMaterial3; final MaterialLocalizations localizations = MaterialLocalizations.of(context); final Orientation orientation = MediaQuery.orientationOf(context); final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context); final DatePickerThemeData defaults = DatePickerTheme.defaults(context); final TextTheme textTheme = theme.textTheme; // There's no M3 spec for a landscape layout input (not calendar) // date picker. To ensure that the date displayed in the input // date picker's header fits in landscape mode, we override the M3 // default here. TextStyle? headlineStyle; if (useMaterial3) { headlineStyle = datePickerTheme.headerHeadlineStyle ?? defaults.headerHeadlineStyle; switch (_entryMode.value) { case DatePickerEntryMode.input: case DatePickerEntryMode.inputOnly: if (orientation == Orientation.landscape) { headlineStyle = textTheme.headlineSmall; } case DatePickerEntryMode.calendar: case DatePickerEntryMode.calendarOnly: // M3 default is OK. } } else { headlineStyle = orientation == Orientation.landscape ? textTheme.headlineSmall : textTheme.headlineMedium; } final Color? headerForegroundColor = datePickerTheme.headerForegroundColor ?? defaults.headerForegroundColor; headlineStyle = headlineStyle?.copyWith(color: headerForegroundColor); final Widget actions = Container( alignment: AlignmentDirectional.centerEnd, constraints: const BoxConstraints(minHeight: 52.0), padding: const EdgeInsets.symmetric(horizontal: 8), child: OverflowBar( spacing: 8, children: <Widget>[ TextButton( style: datePickerTheme.cancelButtonStyle ?? defaults.cancelButtonStyle, onPressed: _handleCancel, child: Text(widget.cancelText ?? ( useMaterial3 ? localizations.cancelButtonLabel : localizations.cancelButtonLabel.toUpperCase() )), ), TextButton( style: datePickerTheme.confirmButtonStyle ?? defaults.confirmButtonStyle, onPressed: _handleOk, child: Text(widget.confirmText ?? localizations.okButtonLabel), ), ], ), ); CalendarDatePicker calendarDatePicker() { return CalendarDatePicker( key: _calendarPickerKey, initialDate: _selectedDate.value, firstDate: widget.firstDate, lastDate: widget.lastDate, currentDate: widget.currentDate, onDateChanged: _handleDateChanged, selectableDayPredicate: widget.selectableDayPredicate, initialCalendarMode: widget.initialCalendarMode, ); } Form inputDatePicker() { return Form( key: _formKey, autovalidateMode: _autovalidateMode.value, child: Container( padding: const EdgeInsets.symmetric(horizontal: 24), height: orientation == Orientation.portrait ? _inputFormPortraitHeight : _inputFormLandscapeHeight, child: Shortcuts( shortcuts: _formShortcutMap, child: Column( children: <Widget>[ const Spacer(), InputDatePickerFormField( initialDate: _selectedDate.value, firstDate: widget.firstDate, lastDate: widget.lastDate, onDateSubmitted: _handleDateChanged, onDateSaved: _handleDateChanged, selectableDayPredicate: widget.selectableDayPredicate, errorFormatText: widget.errorFormatText, errorInvalidText: widget.errorInvalidText, fieldHintText: widget.fieldHintText, fieldLabelText: widget.fieldLabelText, keyboardType: widget.keyboardType, autofocus: true, ), const Spacer(), ], ), ), ), ); } final Widget picker; final Widget? entryModeButton; switch (_entryMode.value) { case DatePickerEntryMode.calendar: picker = calendarDatePicker(); entryModeButton = IconButton( icon: widget.switchToInputEntryModeIcon ?? Icon(useMaterial3 ? Icons.edit_outlined : Icons.edit), color: headerForegroundColor, tooltip: localizations.inputDateModeButtonLabel, onPressed: _handleEntryModeToggle, ); case DatePickerEntryMode.calendarOnly: picker = calendarDatePicker(); entryModeButton = null; case DatePickerEntryMode.input: picker = inputDatePicker(); entryModeButton = IconButton( icon: widget.switchToCalendarEntryModeIcon ?? const Icon(Icons.calendar_today), color: headerForegroundColor, tooltip: localizations.calendarModeButtonLabel, onPressed: _handleEntryModeToggle, ); case DatePickerEntryMode.inputOnly: picker = inputDatePicker(); entryModeButton = null; } final Widget header = _DatePickerHeader( helpText: widget.helpText ?? ( useMaterial3 ? localizations.datePickerHelpText : localizations.datePickerHelpText.toUpperCase() ), titleText: _selectedDate.value == null ? '' : localizations.formatMediumDate(_selectedDate.value!), titleStyle: headlineStyle, orientation: orientation, isShort: orientation == Orientation.landscape, entryModeButton: entryModeButton, ); // Constrain the textScaleFactor to the largest supported value to prevent // layout issues. // 14 is a common font size used to compute the effective text scale. const double fontSizeToScale = 14.0; final double textScaleFactor = MediaQuery.textScalerOf(context).clamp(maxScaleFactor: _kMaxTextScaleFactor).scale(fontSizeToScale) / fontSizeToScale; final Size dialogSize = _dialogSize(context) * textScaleFactor; final DialogTheme dialogTheme = theme.dialogTheme; return Dialog( backgroundColor: datePickerTheme.backgroundColor ?? defaults.backgroundColor, elevation: useMaterial3 ? datePickerTheme.elevation ?? defaults.elevation! : datePickerTheme.elevation ?? dialogTheme.elevation ?? 24, shadowColor: datePickerTheme.shadowColor ?? defaults.shadowColor, surfaceTintColor: datePickerTheme.surfaceTintColor ?? defaults.surfaceTintColor, shape: useMaterial3 ? datePickerTheme.shape ?? defaults.shape : datePickerTheme.shape ?? dialogTheme.shape ?? defaults.shape, insetPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0), clipBehavior: Clip.antiAlias, child: AnimatedContainer( width: dialogSize.width, height: dialogSize.height, duration: _dialogSizeAnimationDuration, curve: Curves.easeIn, child: MediaQuery.withClampedTextScaling( // Constrain the textScaleFactor to the largest supported value to prevent // layout issues. maxScaleFactor: _kMaxTextScaleFactor, child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { final Size portraitDialogSize = useMaterial3 ? _inputPortraitDialogSizeM3 : _inputPortraitDialogSizeM2; // Make sure the portrait dialog can fit the contents comfortably when // resized from the landscape dialog. final bool isFullyPortrait = constraints.maxHeight >= math.min(dialogSize.height, portraitDialogSize.height); switch (orientation) { case Orientation.portrait: return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ header, if (useMaterial3) Divider(height: 0, color: datePickerTheme.dividerColor), if (isFullyPortrait) ...<Widget>[ Expanded(child: picker), actions, ], ], ); case Orientation.landscape: return Row( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ header, if (useMaterial3) VerticalDivider(width: 0, color: datePickerTheme.dividerColor), Flexible( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Expanded(child: picker), actions, ], ), ), ], ); } }), ), ), ); } } // A restorable [DatePickerEntryMode] value. // // This serializes each entry as a unique `int` value. class _RestorableDatePickerEntryMode extends RestorableValue<DatePickerEntryMode> { _RestorableDatePickerEntryMode( DatePickerEntryMode defaultValue, ) : _defaultValue = defaultValue; final DatePickerEntryMode _defaultValue; @override DatePickerEntryMode createDefaultValue() => _defaultValue; @override void didUpdateValue(DatePickerEntryMode? oldValue) { assert(debugIsSerializableForRestoration(value.index)); notifyListeners(); } @override DatePickerEntryMode fromPrimitives(Object? data) => DatePickerEntryMode.values[data! as int]; @override Object? toPrimitives() => value.index; } // A restorable [AutovalidateMode] value. // // This serializes each entry as a unique `int` value. class _RestorableAutovalidateMode extends RestorableValue<AutovalidateMode> { _RestorableAutovalidateMode( AutovalidateMode defaultValue, ) : _defaultValue = defaultValue; final AutovalidateMode _defaultValue; @override AutovalidateMode createDefaultValue() => _defaultValue; @override void didUpdateValue(AutovalidateMode? oldValue) { assert(debugIsSerializableForRestoration(value.index)); notifyListeners(); } @override AutovalidateMode fromPrimitives(Object? data) => AutovalidateMode.values[data! as int]; @override Object? toPrimitives() => value.index; } /// Re-usable widget that displays the selected date (in large font) and the /// help text above it. /// /// These types include: /// /// * Single Date picker with calendar mode. /// * Single Date picker with text input mode. /// * Date Range picker with text input mode. /// /// [helpText], [orientation], [icon], [onIconPressed] are required and must be /// non-null. class _DatePickerHeader extends StatelessWidget { /// Creates a header for use in a date picker dialog. const _DatePickerHeader({ required this.helpText, required this.titleText, this.titleSemanticsLabel, required this.titleStyle, required this.orientation, this.isShort = false, this.entryModeButton, }); static const double _datePickerHeaderLandscapeWidth = 152.0; static const double _datePickerHeaderPortraitHeight = 120.0; static const double _headerPaddingLandscape = 16.0; /// The text that is displayed at the top of the header. /// /// This is used to indicate to the user what they are selecting a date for. final String helpText; /// The text that is displayed at the center of the header. final String titleText; /// The semantic label associated with the [titleText]. final String? titleSemanticsLabel; /// The [TextStyle] that the title text is displayed with. final TextStyle? titleStyle; /// The orientation is used to decide how to layout its children. final Orientation orientation; /// Indicates the header is being displayed in a shorter/narrower context. /// /// This will be used to tighten up the space between the help text and date /// text if `true`. Additionally, it will use a smaller typography style if /// `true`. /// /// This is necessary for displaying the manual input mode in /// landscape orientation, in order to account for the keyboard height. final bool isShort; final Widget? entryModeButton; @override Widget build(BuildContext context) { final DatePickerThemeData themeData = DatePickerTheme.of(context); final DatePickerThemeData defaults = DatePickerTheme.defaults(context); final Color? backgroundColor = themeData.headerBackgroundColor ?? defaults.headerBackgroundColor; final Color? foregroundColor = themeData.headerForegroundColor ?? defaults.headerForegroundColor; final TextStyle? helpStyle = (themeData.headerHelpStyle ?? defaults.headerHelpStyle)?.copyWith( color: foregroundColor, ); final Text help = Text( helpText, style: helpStyle, maxLines: 1, overflow: TextOverflow.ellipsis, ); final Text title = Text( titleText, semanticsLabel: titleSemanticsLabel ?? titleText, style: titleStyle, maxLines: orientation == Orientation.portrait ? 1 : 2, overflow: TextOverflow.ellipsis, ); switch (orientation) { case Orientation.portrait: return Semantics( container: true, child: SizedBox( height: _datePickerHeaderPortraitHeight, child: Material( color: backgroundColor, child: Padding( padding: const EdgeInsetsDirectional.only( start: 24, end: 12, bottom: 12, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ const SizedBox(height: 16), help, const Flexible(child: SizedBox(height: 38)), Row( children: <Widget>[ Expanded(child: title), if (entryModeButton != null) Semantics( container: true, child: entryModeButton, ), ], ), ], ), ), ), ), ); case Orientation.landscape: return Semantics( container: true, child:SizedBox( width: _datePickerHeaderLandscapeWidth, child: Material( color: backgroundColor, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ const SizedBox(height: 16), Padding( padding: const EdgeInsets.symmetric( horizontal: _headerPaddingLandscape, ), child: help, ), SizedBox(height: isShort ? 16 : 56), Expanded( child: Padding( padding: const EdgeInsets.symmetric( horizontal: _headerPaddingLandscape, ), child: title, ), ), if (entryModeButton != null) Padding( padding: const EdgeInsets.symmetric(horizontal: 4), child: Semantics( container: true, child: entryModeButton, ), ), ], ), ), ), ); } } } /// Shows a full screen modal dialog containing a Material Design date range /// picker. /// /// The returned [Future] resolves to the [DateTimeRange] selected by the user /// when the user saves their selection. If the user cancels the dialog, null is /// returned. /// /// If [initialDateRange] is non-null, then it will be used as the initially /// selected date range. If it is provided, `initialDateRange.start` must be /// before or on `initialDateRange.end`. /// /// The [firstDate] is the earliest allowable date. The [lastDate] is the latest /// allowable date. /// /// If an initial date range is provided, `initialDateRange.start` /// and `initialDateRange.end` must both fall between or on [firstDate] and /// [lastDate]. For all of these [DateTime] values, only their dates are /// considered. Their time fields are ignored. /// /// The [currentDate] represents the current day (i.e. today). This /// date will be highlighted in the day grid. If null, the date of /// `DateTime.now()` will be used. /// /// An optional [initialEntryMode] argument can be used to display the date /// picker in the [DatePickerEntryMode.calendar] (a scrollable calendar month /// grid) or [DatePickerEntryMode.input] (two text input fields) mode. /// It defaults to [DatePickerEntryMode.calendar]. /// /// {@macro flutter.material.date_picker.switchToInputEntryModeIcon} /// /// {@macro flutter.material.date_picker.switchToCalendarEntryModeIcon} /// /// The following optional string parameters allow you to override the default /// text used for various parts of the dialog: /// /// * [helpText], the label displayed at the top of the dialog. /// * [cancelText], the label on the cancel button for the text input mode. /// * [confirmText],the label on the ok button for the text input mode. /// * [saveText], the label on the save button for the fullscreen calendar /// mode. /// * [errorFormatText], the message used when an input text isn't in a proper /// date format. /// * [errorInvalidText], the message used when an input text isn't a /// selectable date. /// * [errorInvalidRangeText], the message used when the date range is /// invalid (e.g. start date is after end date). /// * [fieldStartHintText], the text used to prompt the user when no text has /// been entered in the start field. /// * [fieldEndHintText], the text used to prompt the user when no text has /// been entered in the end field. /// * [fieldStartLabelText], the label for the start date text input field. /// * [fieldEndLabelText], the label for the end date text input field. /// /// An optional [locale] argument can be used to set the locale for the date /// picker. It defaults to the ambient locale provided by [Localizations]. /// /// An optional [textDirection] argument can be used to set the text direction /// ([TextDirection.ltr] or [TextDirection.rtl]) for the date picker. It /// defaults to the ambient text direction provided by [Directionality]. If both /// [locale] and [textDirection] are non-null, [textDirection] overrides the /// direction chosen for the [locale]. /// /// The [context], [barrierDismissible], [barrierColor], [barrierLabel], /// [useRootNavigator] and [routeSettings] arguments are passed to [showDialog], /// the documentation for which discusses how it is used. /// /// The [builder] parameter can be used to wrap the dialog widget /// to add inherited widgets like [Theme]. /// /// {@macro flutter.widgets.RawDialogRoute} /// /// ### State Restoration /// /// Using this method will not enable state restoration for the date range picker. /// In order to enable state restoration for a date range picker, use /// [Navigator.restorablePush] or [Navigator.restorablePushNamed] with /// [DateRangePickerDialog]. /// /// For more information about state restoration, see [RestorationManager]. /// /// {@macro flutter.widgets.RestorationManager} /// /// {@tool dartpad} /// This sample demonstrates how to create a restorable Material date range picker. /// This is accomplished by enabling state restoration by specifying /// [MaterialApp.restorationScopeId] and using [Navigator.restorablePush] to /// push [DateRangePickerDialog] when the button is tapped. /// /// ** See code in examples/api/lib/material/date_picker/show_date_range_picker.0.dart ** /// {@end-tool} /// /// See also: /// /// * [showDatePicker], which shows a Material Design date picker used to /// select a single date. /// * [DateTimeRange], which is used to describe a date range. /// * [DisplayFeatureSubScreen], which documents the specifics of how /// [DisplayFeature]s can split the screen into sub-screens. Future<DateTimeRange?> showDateRangePicker({ required BuildContext context, DateTimeRange? initialDateRange, required DateTime firstDate, required DateTime lastDate, DateTime? currentDate, DatePickerEntryMode initialEntryMode = DatePickerEntryMode.calendar, String? helpText, String? cancelText, String? confirmText, String? saveText, String? errorFormatText, String? errorInvalidText, String? errorInvalidRangeText, String? fieldStartHintText, String? fieldEndHintText, String? fieldStartLabelText, String? fieldEndLabelText, Locale? locale, bool barrierDismissible = true, Color? barrierColor, String? barrierLabel, bool useRootNavigator = true, RouteSettings? routeSettings, TextDirection? textDirection, TransitionBuilder? builder, Offset? anchorPoint, TextInputType keyboardType = TextInputType.datetime, final Icon? switchToInputEntryModeIcon, final Icon? switchToCalendarEntryModeIcon, }) async { assert( initialDateRange == null || !initialDateRange.start.isAfter(initialDateRange.end), "initialDateRange's start date must not be after it's end date.", ); initialDateRange = initialDateRange == null ? null : DateUtils.datesOnly(initialDateRange); firstDate = DateUtils.dateOnly(firstDate); lastDate = DateUtils.dateOnly(lastDate); assert( !lastDate.isBefore(firstDate), 'lastDate $lastDate must be on or after firstDate $firstDate.', ); assert( initialDateRange == null || !initialDateRange.start.isBefore(firstDate), "initialDateRange's start date must be on or after firstDate $firstDate.", ); assert( initialDateRange == null || !initialDateRange.end.isBefore(firstDate), "initialDateRange's end date must be on or after firstDate $firstDate.", ); assert( initialDateRange == null || !initialDateRange.start.isAfter(lastDate), "initialDateRange's start date must be on or before lastDate $lastDate.", ); assert( initialDateRange == null || !initialDateRange.end.isAfter(lastDate), "initialDateRange's end date must be on or before lastDate $lastDate.", ); currentDate = DateUtils.dateOnly(currentDate ?? DateTime.now()); assert(debugCheckHasMaterialLocalizations(context)); Widget dialog = DateRangePickerDialog( initialDateRange: initialDateRange, firstDate: firstDate, lastDate: lastDate, currentDate: currentDate, initialEntryMode: initialEntryMode, helpText: helpText, cancelText: cancelText, confirmText: confirmText, saveText: saveText, errorFormatText: errorFormatText, errorInvalidText: errorInvalidText, errorInvalidRangeText: errorInvalidRangeText, fieldStartHintText: fieldStartHintText, fieldEndHintText: fieldEndHintText, fieldStartLabelText: fieldStartLabelText, fieldEndLabelText: fieldEndLabelText, keyboardType: keyboardType, switchToInputEntryModeIcon: switchToInputEntryModeIcon, switchToCalendarEntryModeIcon: switchToCalendarEntryModeIcon, ); if (textDirection != null) { dialog = Directionality( textDirection: textDirection, child: dialog, ); } if (locale != null) { dialog = Localizations.override( context: context, locale: locale, child: dialog, ); } return showDialog<DateTimeRange>( context: context, barrierDismissible: barrierDismissible, barrierColor: barrierColor, barrierLabel: barrierLabel, useRootNavigator: useRootNavigator, routeSettings: routeSettings, useSafeArea: false, builder: (BuildContext context) { return builder == null ? dialog : builder(context, dialog); }, anchorPoint: anchorPoint, ); } /// Returns a locale-appropriate string to describe the start of a date range. /// /// If `startDate` is null, then it defaults to 'Start Date', otherwise if it /// is in the same year as the `endDate` then it will use the short month /// day format (i.e. 'Jan 21'). Otherwise it will return the short date format /// (i.e. 'Jan 21, 2020'). String _formatRangeStartDate(MaterialLocalizations localizations, DateTime? startDate, DateTime? endDate) { return startDate == null ? localizations.dateRangeStartLabel : (endDate == null || startDate.year == endDate.year) ? localizations.formatShortMonthDay(startDate) : localizations.formatShortDate(startDate); } /// Returns an locale-appropriate string to describe the end of a date range. /// /// If `endDate` is null, then it defaults to 'End Date', otherwise if it /// is in the same year as the `startDate` and the `currentDate` then it will /// just use the short month day format (i.e. 'Jan 21'), otherwise it will /// include the year (i.e. 'Jan 21, 2020'). String _formatRangeEndDate(MaterialLocalizations localizations, DateTime? startDate, DateTime? endDate, DateTime currentDate) { return endDate == null ? localizations.dateRangeEndLabel : (startDate != null && startDate.year == endDate.year && startDate.year == currentDate.year) ? localizations.formatShortMonthDay(endDate) : localizations.formatShortDate(endDate); } /// A Material-style date range picker dialog. /// /// It is used internally by [showDateRangePicker] or can be directly pushed /// onto the [Navigator] stack to enable state restoration. See /// [showDateRangePicker] for a state restoration app example. /// /// See also: /// /// * [showDateRangePicker], which is a way to display the date picker. class DateRangePickerDialog extends StatefulWidget { /// A Material-style date range picker dialog. const DateRangePickerDialog({ super.key, this.initialDateRange, required this.firstDate, required this.lastDate, this.currentDate, this.initialEntryMode = DatePickerEntryMode.calendar, this.helpText, this.cancelText, this.confirmText, this.saveText, this.errorInvalidRangeText, this.errorFormatText, this.errorInvalidText, this.fieldStartHintText, this.fieldEndHintText, this.fieldStartLabelText, this.fieldEndLabelText, this.keyboardType = TextInputType.datetime, this.restorationId, this.switchToInputEntryModeIcon, this.switchToCalendarEntryModeIcon, }); /// The date range that the date range picker starts with when it opens. /// /// If an initial date range is provided, `initialDateRange.start` /// and `initialDateRange.end` must both fall between or on [firstDate] and /// [lastDate]. For all of these [DateTime] values, only their dates are /// considered. Their time fields are ignored. /// /// If [initialDateRange] is non-null, then it will be used as the initially /// selected date range. If it is provided, `initialDateRange.start` must be /// before or on `initialDateRange.end`. final DateTimeRange? initialDateRange; /// The earliest allowable date on the date range. final DateTime firstDate; /// The latest allowable date on the date range. final DateTime lastDate; /// The [currentDate] represents the current day (i.e. today). /// /// This date will be highlighted in the day grid. /// /// If `null`, the date of `DateTime.now()` will be used. final DateTime? currentDate; /// The initial date range picker entry mode. /// /// The date range has two main modes: [DatePickerEntryMode.calendar] (a /// scrollable calendar month grid) or [DatePickerEntryMode.input] (two text /// input fields) mode. /// /// It defaults to [DatePickerEntryMode.calendar]. final DatePickerEntryMode initialEntryMode; /// The label on the cancel button for the text input mode. /// /// If null, the localized value of /// [MaterialLocalizations.cancelButtonLabel] is used. final String? cancelText; /// The label on the "OK" button for the text input mode. /// /// If null, the localized value of /// [MaterialLocalizations.okButtonLabel] is used. final String? confirmText; /// The label on the save button for the fullscreen calendar mode. /// /// If null, the localized value of /// [MaterialLocalizations.saveButtonLabel] is used. final String? saveText; /// The label displayed at the top of the dialog. /// /// If null, the localized value of /// [MaterialLocalizations.dateRangePickerHelpText] is used. final String? helpText; /// The message used when the date range is invalid (e.g. start date is after /// end date). /// /// If null, the localized value of /// [MaterialLocalizations.invalidDateRangeLabel] is used. final String? errorInvalidRangeText; /// The message used when an input text isn't in a proper date format. /// /// If null, the localized value of /// [MaterialLocalizations.invalidDateFormatLabel] is used. final String? errorFormatText; /// The message used when an input text isn't a selectable date. /// /// If null, the localized value of /// [MaterialLocalizations.dateOutOfRangeLabel] is used. final String? errorInvalidText; /// The text used to prompt the user when no text has been entered in the /// start field. /// /// If null, the localized value of /// [MaterialLocalizations.dateHelpText] is used. final String? fieldStartHintText; /// The text used to prompt the user when no text has been entered in the /// end field. /// /// If null, the localized value of [MaterialLocalizations.dateHelpText] is /// used. final String? fieldEndHintText; /// The label for the start date text input field. /// /// If null, the localized value of [MaterialLocalizations.dateRangeStartLabel] /// is used. final String? fieldStartLabelText; /// The label for the end date text input field. /// /// If null, the localized value of [MaterialLocalizations.dateRangeEndLabel] /// is used. final String? fieldEndLabelText; /// {@macro flutter.material.datePickerDialog} final TextInputType keyboardType; /// Restoration ID to save and restore the state of the [DateRangePickerDialog]. /// /// If it is non-null, the date range picker will persist and restore the /// date range selected on the dialog. /// /// The state of this widget is persisted in a [RestorationBucket] claimed /// from the surrounding [RestorationScope] using the provided restoration ID. /// /// See also: /// /// * [RestorationManager], which explains how state restoration works in /// Flutter. final String? restorationId; /// {@macro flutter.material.date_picker.switchToInputEntryModeIcon} final Icon? switchToInputEntryModeIcon; /// {@macro flutter.material.date_picker.switchToCalendarEntryModeIcon} final Icon? switchToCalendarEntryModeIcon; @override State<DateRangePickerDialog> createState() => _DateRangePickerDialogState(); } class _DateRangePickerDialogState extends State<DateRangePickerDialog> with RestorationMixin { late final _RestorableDatePickerEntryMode _entryMode = _RestorableDatePickerEntryMode(widget.initialEntryMode); late final RestorableDateTimeN _selectedStart = RestorableDateTimeN(widget.initialDateRange?.start); late final RestorableDateTimeN _selectedEnd = RestorableDateTimeN(widget.initialDateRange?.end); final RestorableBool _autoValidate = RestorableBool(false); final GlobalKey _calendarPickerKey = GlobalKey(); final GlobalKey<_InputDateRangePickerState> _inputPickerKey = GlobalKey<_InputDateRangePickerState>(); @override String? get restorationId => widget.restorationId; @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_entryMode, 'entry_mode'); registerForRestoration(_selectedStart, 'selected_start'); registerForRestoration(_selectedEnd, 'selected_end'); registerForRestoration(_autoValidate, 'autovalidate'); } @override void dispose() { _entryMode.dispose(); _selectedStart.dispose(); _selectedEnd.dispose(); _autoValidate.dispose(); super.dispose(); } void _handleOk() { if (_entryMode.value == DatePickerEntryMode.input || _entryMode.value == DatePickerEntryMode.inputOnly) { final _InputDateRangePickerState picker = _inputPickerKey.currentState!; if (!picker.validate()) { setState(() { _autoValidate.value = true; }); return; } } final DateTimeRange? selectedRange = _hasSelectedDateRange ? DateTimeRange(start: _selectedStart.value!, end: _selectedEnd.value!) : null; Navigator.pop(context, selectedRange); } void _handleCancel() { Navigator.pop(context); } void _handleEntryModeToggle() { setState(() { switch (_entryMode.value) { case DatePickerEntryMode.calendar: _autoValidate.value = false; _entryMode.value = DatePickerEntryMode.input; case DatePickerEntryMode.input: // Validate the range dates if (_selectedStart.value != null && (_selectedStart.value!.isBefore(widget.firstDate) || _selectedStart.value!.isAfter(widget.lastDate))) { _selectedStart.value = null; // With no valid start date, having an end date makes no sense for the UI. _selectedEnd.value = null; } if (_selectedEnd.value != null && (_selectedEnd.value!.isBefore(widget.firstDate) || _selectedEnd.value!.isAfter(widget.lastDate))) { _selectedEnd.value = null; } // If invalid range (start after end), then just use the start date if (_selectedStart.value != null && _selectedEnd.value != null && _selectedStart.value!.isAfter(_selectedEnd.value!)) { _selectedEnd.value = null; } _entryMode.value = DatePickerEntryMode.calendar; case DatePickerEntryMode.calendarOnly: case DatePickerEntryMode.inputOnly: assert(false, 'Can not change entry mode from $_entryMode'); } }); } void _handleStartDateChanged(DateTime? date) { setState(() => _selectedStart.value = date); } void _handleEndDateChanged(DateTime? date) { setState(() => _selectedEnd.value = date); } bool get _hasSelectedDateRange => _selectedStart.value != null && _selectedEnd.value != null; @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final bool useMaterial3 = theme.useMaterial3; final Orientation orientation = MediaQuery.orientationOf(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context); final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context); final DatePickerThemeData defaults = DatePickerTheme.defaults(context); final Widget contents; final Size size; final double? elevation; final Color? shadowColor; final Color? surfaceTintColor; final ShapeBorder? shape; final EdgeInsets insetPadding; final bool showEntryModeButton = _entryMode.value == DatePickerEntryMode.calendar || _entryMode.value == DatePickerEntryMode.input; switch (_entryMode.value) { case DatePickerEntryMode.calendar: case DatePickerEntryMode.calendarOnly: contents = _CalendarRangePickerDialog( key: _calendarPickerKey, selectedStartDate: _selectedStart.value, selectedEndDate: _selectedEnd.value, firstDate: widget.firstDate, lastDate: widget.lastDate, currentDate: widget.currentDate, onStartDateChanged: _handleStartDateChanged, onEndDateChanged: _handleEndDateChanged, onConfirm: _hasSelectedDateRange ? _handleOk : null, onCancel: _handleCancel, entryModeButton: showEntryModeButton ? IconButton( icon: widget.switchToInputEntryModeIcon ?? Icon(useMaterial3 ? Icons.edit_outlined : Icons.edit), padding: EdgeInsets.zero, tooltip: localizations.inputDateModeButtonLabel, onPressed: _handleEntryModeToggle, ) : null, confirmText: widget.saveText ?? ( useMaterial3 ? localizations.saveButtonLabel : localizations.saveButtonLabel.toUpperCase() ), helpText: widget.helpText ?? ( useMaterial3 ? localizations.dateRangePickerHelpText : localizations.dateRangePickerHelpText.toUpperCase() ), ); size = MediaQuery.sizeOf(context); insetPadding = EdgeInsets.zero; elevation = datePickerTheme.rangePickerElevation ?? defaults.rangePickerElevation!; shadowColor = datePickerTheme.rangePickerShadowColor ?? defaults.rangePickerShadowColor!; surfaceTintColor = datePickerTheme.rangePickerSurfaceTintColor ?? defaults.rangePickerSurfaceTintColor!; shape = datePickerTheme.rangePickerShape ?? defaults.rangePickerShape; case DatePickerEntryMode.input: case DatePickerEntryMode.inputOnly: contents = _InputDateRangePickerDialog( selectedStartDate: _selectedStart.value, selectedEndDate: _selectedEnd.value, currentDate: widget.currentDate, picker: Container( padding: const EdgeInsets.symmetric(horizontal: 24), height: orientation == Orientation.portrait ? _inputFormPortraitHeight : _inputFormLandscapeHeight, child: Column( children: <Widget>[ const Spacer(), _InputDateRangePicker( key: _inputPickerKey, initialStartDate: _selectedStart.value, initialEndDate: _selectedEnd.value, firstDate: widget.firstDate, lastDate: widget.lastDate, onStartDateChanged: _handleStartDateChanged, onEndDateChanged: _handleEndDateChanged, autofocus: true, autovalidate: _autoValidate.value, helpText: widget.helpText, errorInvalidRangeText: widget.errorInvalidRangeText, errorFormatText: widget.errorFormatText, errorInvalidText: widget.errorInvalidText, fieldStartHintText: widget.fieldStartHintText, fieldEndHintText: widget.fieldEndHintText, fieldStartLabelText: widget.fieldStartLabelText, fieldEndLabelText: widget.fieldEndLabelText, keyboardType: widget.keyboardType, ), const Spacer(), ], ), ), onConfirm: _handleOk, onCancel: _handleCancel, entryModeButton: showEntryModeButton ? IconButton( icon: widget.switchToCalendarEntryModeIcon ?? const Icon(Icons.calendar_today), padding: EdgeInsets.zero, tooltip: localizations.calendarModeButtonLabel, onPressed: _handleEntryModeToggle, ) : null, confirmText: widget.confirmText ?? localizations.okButtonLabel, cancelText: widget.cancelText ?? ( useMaterial3 ? localizations.cancelButtonLabel : localizations.cancelButtonLabel.toUpperCase() ), helpText: widget.helpText ?? ( useMaterial3 ? localizations.dateRangePickerHelpText : localizations.dateRangePickerHelpText.toUpperCase() ), ); final DialogTheme dialogTheme = theme.dialogTheme; size = orientation == Orientation.portrait ? (useMaterial3 ? _inputPortraitDialogSizeM3 : _inputPortraitDialogSizeM2) : _inputRangeLandscapeDialogSize; elevation = useMaterial3 ? datePickerTheme.elevation ?? defaults.elevation! : datePickerTheme.elevation ?? dialogTheme.elevation ?? 24; shadowColor = datePickerTheme.shadowColor ?? defaults.shadowColor; surfaceTintColor = datePickerTheme.surfaceTintColor ?? defaults.surfaceTintColor; shape = useMaterial3 ? datePickerTheme.shape ?? defaults.shape : datePickerTheme.shape ?? dialogTheme.shape ?? defaults.shape; insetPadding = const EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0); } return Dialog( insetPadding: insetPadding, backgroundColor: datePickerTheme.backgroundColor ?? defaults.backgroundColor, elevation: elevation, shadowColor: shadowColor, surfaceTintColor: surfaceTintColor, shape: shape, clipBehavior: Clip.antiAlias, child: AnimatedContainer( width: size.width, height: size.height, duration: _dialogSizeAnimationDuration, curve: Curves.easeIn, child: MediaQuery.withClampedTextScaling( maxScaleFactor: _kMaxTextScaleFactor, child: Builder(builder: (BuildContext context) { return contents; }), ), ), ); } } class _CalendarRangePickerDialog extends StatelessWidget { const _CalendarRangePickerDialog({ super.key, required this.selectedStartDate, required this.selectedEndDate, required this.firstDate, required this.lastDate, required this.currentDate, required this.onStartDateChanged, required this.onEndDateChanged, required this.onConfirm, required this.onCancel, required this.confirmText, required this.helpText, this.entryModeButton, }); final DateTime? selectedStartDate; final DateTime? selectedEndDate; final DateTime firstDate; final DateTime lastDate; final DateTime? currentDate; final ValueChanged<DateTime> onStartDateChanged; final ValueChanged<DateTime?> onEndDateChanged; final VoidCallback? onConfirm; final VoidCallback? onCancel; final String confirmText; final String helpText; final Widget? entryModeButton; @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final bool useMaterial3 = theme.useMaterial3; final MaterialLocalizations localizations = MaterialLocalizations.of(context); final Orientation orientation = MediaQuery.orientationOf(context); final DatePickerThemeData themeData = DatePickerTheme.of(context); final DatePickerThemeData defaults = DatePickerTheme.defaults(context); final Color? dialogBackground = themeData.rangePickerBackgroundColor ?? defaults.rangePickerBackgroundColor; final Color? headerBackground = themeData.rangePickerHeaderBackgroundColor ?? defaults.rangePickerHeaderBackgroundColor; final Color? headerForeground = themeData.rangePickerHeaderForegroundColor ?? defaults.rangePickerHeaderForegroundColor; final Color? headerDisabledForeground = headerForeground?.withOpacity(0.38); final TextStyle? headlineStyle = themeData.rangePickerHeaderHeadlineStyle ?? defaults.rangePickerHeaderHeadlineStyle; final TextStyle? headlineHelpStyle = (themeData.rangePickerHeaderHelpStyle ?? defaults.rangePickerHeaderHelpStyle)?.apply(color: headerForeground); final String startDateText = _formatRangeStartDate(localizations, selectedStartDate, selectedEndDate); final String endDateText = _formatRangeEndDate(localizations, selectedStartDate, selectedEndDate, DateTime.now()); final TextStyle? startDateStyle = headlineStyle?.apply( color: selectedStartDate != null ? headerForeground : headerDisabledForeground, ); final TextStyle? endDateStyle = headlineStyle?.apply( color: selectedEndDate != null ? headerForeground : headerDisabledForeground, ); final ButtonStyle buttonStyle = TextButton.styleFrom( foregroundColor: headerForeground, disabledForegroundColor: headerDisabledForeground ); final IconThemeData iconTheme = IconThemeData(color: headerForeground); return SafeArea( top: false, left: false, right: false, child: Scaffold( appBar: AppBar( iconTheme: iconTheme, actionsIconTheme: iconTheme, elevation: useMaterial3 ? 0 : null, scrolledUnderElevation: useMaterial3 ? 0 : null, backgroundColor: useMaterial3 ? headerBackground : null, leading: CloseButton( onPressed: onCancel, ), actions: <Widget>[ if (orientation == Orientation.landscape && entryModeButton != null) entryModeButton!, TextButton( style: buttonStyle, onPressed: onConfirm, child: Text(confirmText), ), const SizedBox(width: 8), ], bottom: PreferredSize( preferredSize: const Size(double.infinity, 64), child: Row(children: <Widget>[ SizedBox(width: MediaQuery.sizeOf(context).width < 360 ? 42 : 72), Expanded( child: Semantics( label: '$helpText $startDateText to $endDateText', excludeSemantics: true, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text(helpText, style: headlineHelpStyle), const SizedBox(height: 8), Row( children: <Widget>[ Text( startDateText, style: startDateStyle, maxLines: 1, overflow: TextOverflow.ellipsis, ), Text(' – ', style: startDateStyle, ), Flexible( child: Text( endDateText, style: endDateStyle, maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ], ), const SizedBox(height: 16), ], ), ), ), if (orientation == Orientation.portrait && entryModeButton != null) Padding( padding: const EdgeInsets.symmetric(horizontal: 8.0), child: IconTheme( data: iconTheme, child: entryModeButton!, ), ), ]), ), ), backgroundColor: dialogBackground, body: _CalendarDateRangePicker( initialStartDate: selectedStartDate, initialEndDate: selectedEndDate, firstDate: firstDate, lastDate: lastDate, currentDate: currentDate, onStartDateChanged: onStartDateChanged, onEndDateChanged: onEndDateChanged, ), ), ); } } const Duration _monthScrollDuration = Duration(milliseconds: 200); const double _monthItemHeaderHeight = 58.0; const double _monthItemFooterHeight = 12.0; const double _monthItemRowHeight = 42.0; const double _monthItemSpaceBetweenRows = 8.0; const double _horizontalPadding = 8.0; const double _maxCalendarWidthLandscape = 384.0; const double _maxCalendarWidthPortrait = 480.0; /// Displays a scrollable calendar grid that allows a user to select a range /// of dates. class _CalendarDateRangePicker extends StatefulWidget { /// Creates a scrollable calendar grid for picking date ranges. _CalendarDateRangePicker({ DateTime? initialStartDate, DateTime? initialEndDate, required DateTime firstDate, required DateTime lastDate, DateTime? currentDate, required this.onStartDateChanged, required this.onEndDateChanged, }) : initialStartDate = initialStartDate != null ? DateUtils.dateOnly(initialStartDate) : null, initialEndDate = initialEndDate != null ? DateUtils.dateOnly(initialEndDate) : null, firstDate = DateUtils.dateOnly(firstDate), lastDate = DateUtils.dateOnly(lastDate), currentDate = DateUtils.dateOnly(currentDate ?? DateTime.now()) { assert( this.initialStartDate == null || this.initialEndDate == null || !this.initialStartDate!.isAfter(initialEndDate!), 'initialStartDate must be on or before initialEndDate.', ); assert( !this.lastDate.isBefore(this.firstDate), 'firstDate must be on or before lastDate.', ); } /// The [DateTime] that represents the start of the initial date range selection. final DateTime? initialStartDate; /// The [DateTime] that represents the end of the initial date range selection. final DateTime? initialEndDate; /// The earliest allowable [DateTime] that the user can select. final DateTime firstDate; /// The latest allowable [DateTime] that the user can select. final DateTime lastDate; /// The [DateTime] representing today. It will be highlighted in the day grid. final DateTime currentDate; /// Called when the user changes the start date of the selected range. final ValueChanged<DateTime>? onStartDateChanged; /// Called when the user changes the end date of the selected range. final ValueChanged<DateTime?>? onEndDateChanged; @override _CalendarDateRangePickerState createState() => _CalendarDateRangePickerState(); } class _CalendarDateRangePickerState extends State<_CalendarDateRangePicker> { final GlobalKey _scrollViewKey = GlobalKey(); DateTime? _startDate; DateTime? _endDate; int _initialMonthIndex = 0; late ScrollController _controller; late bool _showWeekBottomDivider; @override void initState() { super.initState(); _controller = ScrollController(); _controller.addListener(_scrollListener); _startDate = widget.initialStartDate; _endDate = widget.initialEndDate; // Calculate the index for the initially displayed month. This is needed to // divide the list of months into two `SliverList`s. final DateTime initialDate = widget.initialStartDate ?? widget.currentDate; if (!initialDate.isBefore(widget.firstDate) && !initialDate.isAfter(widget.lastDate)) { _initialMonthIndex = DateUtils.monthDelta(widget.firstDate, initialDate); } _showWeekBottomDivider = _initialMonthIndex != 0; } @override void dispose() { _controller.dispose(); super.dispose(); } void _scrollListener() { if (_controller.offset <= _controller.position.minScrollExtent) { setState(() { _showWeekBottomDivider = false; }); } else if (!_showWeekBottomDivider) { setState(() { _showWeekBottomDivider = true; }); } } int get _numberOfMonths => DateUtils.monthDelta(widget.firstDate, widget.lastDate) + 1; void _vibrate() { switch (Theme.of(context).platform) { case TargetPlatform.android: case TargetPlatform.fuchsia: HapticFeedback.vibrate(); case TargetPlatform.iOS: case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: break; } } // This updates the selected date range using this logic: // // * From the unselected state, selecting one date creates the start date. // * If the next selection is before the start date, reset date range and // set the start date to that selection. // * If the next selection is on or after the start date, set the end date // to that selection. // * After both start and end dates are selected, any subsequent selection // resets the date range and sets start date to that selection. void _updateSelection(DateTime date) { _vibrate(); setState(() { if (_startDate != null && _endDate == null && !date.isBefore(_startDate!)) { _endDate = date; widget.onEndDateChanged?.call(_endDate); } else { _startDate = date; widget.onStartDateChanged?.call(_startDate!); if (_endDate != null) { _endDate = null; widget.onEndDateChanged?.call(_endDate); } } }); } Widget _buildMonthItem(BuildContext context, int index, bool beforeInitialMonth) { final int monthIndex = beforeInitialMonth ? _initialMonthIndex - index - 1 : _initialMonthIndex + index; final DateTime month = DateUtils.addMonthsToMonthDate(widget.firstDate, monthIndex); return _MonthItem( selectedDateStart: _startDate, selectedDateEnd: _endDate, currentDate: widget.currentDate, firstDate: widget.firstDate, lastDate: widget.lastDate, displayedMonth: month, onChanged: _updateSelection, ); } @override Widget build(BuildContext context) { const Key sliverAfterKey = Key('sliverAfterKey'); return Column( children: <Widget>[ const _DayHeaders(), if (_showWeekBottomDivider) const Divider(height: 0), Expanded( child: _CalendarKeyboardNavigator( firstDate: widget.firstDate, lastDate: widget.lastDate, initialFocusedDay: _startDate ?? widget.initialStartDate ?? widget.currentDate, // In order to prevent performance issues when displaying the // correct initial month, 2 `SliverList`s are used to split the // months. The first item in the second SliverList is the initial // month to be displayed. child: CustomScrollView( key: _scrollViewKey, controller: _controller, center: sliverAfterKey, slivers: <Widget>[ SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => _buildMonthItem(context, index, true), childCount: _initialMonthIndex, ), ), SliverList( key: sliverAfterKey, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => _buildMonthItem(context, index, false), childCount: _numberOfMonths - _initialMonthIndex, ), ), ], ), ), ), ], ); } } class _CalendarKeyboardNavigator extends StatefulWidget { const _CalendarKeyboardNavigator({ required this.child, required this.firstDate, required this.lastDate, required this.initialFocusedDay, }); final Widget child; final DateTime firstDate; final DateTime lastDate; final DateTime initialFocusedDay; @override _CalendarKeyboardNavigatorState createState() => _CalendarKeyboardNavigatorState(); } class _CalendarKeyboardNavigatorState extends State<_CalendarKeyboardNavigator> { final Map<ShortcutActivator, Intent> _shortcutMap = const <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.arrowLeft): DirectionalFocusIntent(TraversalDirection.left), SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent(TraversalDirection.right), SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent(TraversalDirection.down), SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent(TraversalDirection.up), }; late Map<Type, Action<Intent>> _actionMap; late FocusNode _dayGridFocus; TraversalDirection? _dayTraversalDirection; DateTime? _focusedDay; @override void initState() { super.initState(); _actionMap = <Type, Action<Intent>>{ NextFocusIntent: CallbackAction<NextFocusIntent>(onInvoke: _handleGridNextFocus), PreviousFocusIntent: CallbackAction<PreviousFocusIntent>(onInvoke: _handleGridPreviousFocus), DirectionalFocusIntent: CallbackAction<DirectionalFocusIntent>(onInvoke: _handleDirectionFocus), }; _dayGridFocus = FocusNode(debugLabel: 'Day Grid'); } @override void dispose() { _dayGridFocus.dispose(); super.dispose(); } void _handleGridFocusChange(bool focused) { setState(() { if (focused) { _focusedDay ??= widget.initialFocusedDay; } }); } /// Move focus to the next element after the day grid. void _handleGridNextFocus(NextFocusIntent intent) { _dayGridFocus.requestFocus(); _dayGridFocus.nextFocus(); } /// Move focus to the previous element before the day grid. void _handleGridPreviousFocus(PreviousFocusIntent intent) { _dayGridFocus.requestFocus(); _dayGridFocus.previousFocus(); } /// Move the internal focus date in the direction of the given intent. /// /// This will attempt to move the focused day to the next selectable day in /// the given direction. If the new date is not in the current month, then /// the page view will be scrolled to show the new date's month. /// /// For horizontal directions, it will move forward or backward a day (depending /// on the current [TextDirection]). For vertical directions it will move up and /// down a week at a time. void _handleDirectionFocus(DirectionalFocusIntent intent) { assert(_focusedDay != null); setState(() { final DateTime? nextDate = _nextDateInDirection(_focusedDay!, intent.direction); if (nextDate != null) { _focusedDay = nextDate; _dayTraversalDirection = intent.direction; } }); } static const Map<TraversalDirection, int> _directionOffset = <TraversalDirection, int>{ TraversalDirection.up: -DateTime.daysPerWeek, TraversalDirection.right: 1, TraversalDirection.down: DateTime.daysPerWeek, TraversalDirection.left: -1, }; int _dayDirectionOffset(TraversalDirection traversalDirection, TextDirection textDirection) { // Swap left and right if the text direction if RTL if (textDirection == TextDirection.rtl) { if (traversalDirection == TraversalDirection.left) { traversalDirection = TraversalDirection.right; } else if (traversalDirection == TraversalDirection.right) { traversalDirection = TraversalDirection.left; } } return _directionOffset[traversalDirection]!; } DateTime? _nextDateInDirection(DateTime date, TraversalDirection direction) { final TextDirection textDirection = Directionality.of(context); final DateTime nextDate = DateUtils.addDaysToDate(date, _dayDirectionOffset(direction, textDirection)); if (!nextDate.isBefore(widget.firstDate) && !nextDate.isAfter(widget.lastDate)) { return nextDate; } return null; } @override Widget build(BuildContext context) { return FocusableActionDetector( shortcuts: _shortcutMap, actions: _actionMap, focusNode: _dayGridFocus, onFocusChange: _handleGridFocusChange, child: _FocusedDate( date: _dayGridFocus.hasFocus ? _focusedDay : null, scrollDirection: _dayGridFocus.hasFocus ? _dayTraversalDirection : null, child: widget.child, ), ); } } /// InheritedWidget indicating what the current focused date is for its children. /// /// This is used by the [_MonthPicker] to let its children [_DayPicker]s know /// what the currently focused date (if any) should be. class _FocusedDate extends InheritedWidget { const _FocusedDate({ required super.child, this.date, this.scrollDirection, }); final DateTime? date; final TraversalDirection? scrollDirection; @override bool updateShouldNotify(_FocusedDate oldWidget) { return !DateUtils.isSameDay(date, oldWidget.date) || scrollDirection != oldWidget.scrollDirection; } static _FocusedDate? maybeOf(BuildContext context) { return context.dependOnInheritedWidgetOfExactType<_FocusedDate>(); } } class _DayHeaders extends StatelessWidget { const _DayHeaders(); /// Builds widgets showing abbreviated days of week. The first widget in the /// returned list corresponds to the first day of week for the current locale. /// /// Examples: /// /// ┌ Sunday is the first day of week in the US (en_US) /// | /// S M T W T F S ← the returned list contains these widgets /// _ _ _ _ _ 1 2 /// 3 4 5 6 7 8 9 /// /// ┌ But it's Monday in the UK (en_GB) /// | /// M T W T F S S ← the returned list contains these widgets /// _ _ _ _ 1 2 3 /// 4 5 6 7 8 9 10 /// List<Widget> _getDayHeaders(TextStyle headerStyle, MaterialLocalizations localizations) { final List<Widget> result = <Widget>[]; for (int i = localizations.firstDayOfWeekIndex; result.length < DateTime.daysPerWeek; i = (i + 1) % DateTime.daysPerWeek) { final String weekday = localizations.narrowWeekdays[i]; result.add(ExcludeSemantics( child: Center(child: Text(weekday, style: headerStyle)), )); } return result; } @override Widget build(BuildContext context) { final ThemeData themeData = Theme.of(context); final ColorScheme colorScheme = themeData.colorScheme; final TextStyle textStyle = themeData.textTheme.titleSmall!.apply(color: colorScheme.onSurface); final MaterialLocalizations localizations = MaterialLocalizations.of(context); final List<Widget> labels = _getDayHeaders(textStyle, localizations); // Add leading and trailing containers for edges of the custom grid layout. labels.insert(0, Container()); labels.add(Container()); return Container( constraints: BoxConstraints( maxWidth: MediaQuery.orientationOf(context) == Orientation.landscape ? _maxCalendarWidthLandscape : _maxCalendarWidthPortrait, maxHeight: _monthItemRowHeight, ), child: GridView.custom( shrinkWrap: true, gridDelegate: _monthItemGridDelegate, childrenDelegate: SliverChildListDelegate( labels, addRepaintBoundaries: false, ), ), ); } } class _MonthItemGridDelegate extends SliverGridDelegate { const _MonthItemGridDelegate(); @override SliverGridLayout getLayout(SliverConstraints constraints) { final double tileWidth = (constraints.crossAxisExtent - 2 * _horizontalPadding) / DateTime.daysPerWeek; return _MonthSliverGridLayout( crossAxisCount: DateTime.daysPerWeek + 2, dayChildWidth: tileWidth, edgeChildWidth: _horizontalPadding, reverseCrossAxis: axisDirectionIsReversed(constraints.crossAxisDirection), ); } @override bool shouldRelayout(_MonthItemGridDelegate oldDelegate) => false; } const _MonthItemGridDelegate _monthItemGridDelegate = _MonthItemGridDelegate(); class _MonthSliverGridLayout extends SliverGridLayout { /// Creates a layout that uses equally sized and spaced tiles for each day of /// the week and an additional edge tile for padding at the start and end of /// each row. /// /// This is necessary to facilitate the painting of the range highlight /// correctly. const _MonthSliverGridLayout({ required this.crossAxisCount, required this.dayChildWidth, required this.edgeChildWidth, required this.reverseCrossAxis, }) : assert(crossAxisCount > 0), assert(dayChildWidth >= 0), assert(edgeChildWidth >= 0); /// The number of children in the cross axis. final int crossAxisCount; /// The width in logical pixels of the day child widgets. final double dayChildWidth; /// The width in logical pixels of the edge child widgets. final double edgeChildWidth; /// Whether the children should be placed in the opposite order of increasing /// coordinates in the cross axis. /// /// For example, if the cross axis is horizontal, the children are placed from /// left to right when [reverseCrossAxis] is false and from right to left when /// [reverseCrossAxis] is true. /// /// Typically set to the return value of [axisDirectionIsReversed] applied to /// the [SliverConstraints.crossAxisDirection]. final bool reverseCrossAxis; /// The number of logical pixels from the leading edge of one row to the /// leading edge of the next row. double get _rowHeight { return _monthItemRowHeight + _monthItemSpaceBetweenRows; } /// The height in logical pixels of the children widgets. double get _childHeight { return _monthItemRowHeight; } @override int getMinChildIndexForScrollOffset(double scrollOffset) { return crossAxisCount * (scrollOffset ~/ _rowHeight); } @override int getMaxChildIndexForScrollOffset(double scrollOffset) { final int mainAxisCount = (scrollOffset / _rowHeight).ceil(); return math.max(0, crossAxisCount * mainAxisCount - 1); } double _getCrossAxisOffset(double crossAxisStart, bool isPadding) { if (reverseCrossAxis) { return ((crossAxisCount - 2) * dayChildWidth + 2 * edgeChildWidth) - crossAxisStart - (isPadding ? edgeChildWidth : dayChildWidth); } return crossAxisStart; } @override SliverGridGeometry getGeometryForChildIndex(int index) { final int adjustedIndex = index % crossAxisCount; final bool isEdge = adjustedIndex == 0 || adjustedIndex == crossAxisCount - 1; final double crossAxisStart = math.max(0, (adjustedIndex - 1) * dayChildWidth + edgeChildWidth); return SliverGridGeometry( scrollOffset: (index ~/ crossAxisCount) * _rowHeight, crossAxisOffset: _getCrossAxisOffset(crossAxisStart, isEdge), mainAxisExtent: _childHeight, crossAxisExtent: isEdge ? edgeChildWidth : dayChildWidth, ); } @override double computeMaxScrollOffset(int childCount) { assert(childCount >= 0); final int mainAxisCount = ((childCount - 1) ~/ crossAxisCount) + 1; final double mainAxisSpacing = _rowHeight - _childHeight; return _rowHeight * mainAxisCount - mainAxisSpacing; } } /// Displays the days of a given month and allows choosing a date range. /// /// The days are arranged in a rectangular grid with one column for each day of /// the week. class _MonthItem extends StatefulWidget { /// Creates a month item. _MonthItem({ required this.selectedDateStart, required this.selectedDateEnd, required this.currentDate, required this.onChanged, required this.firstDate, required this.lastDate, required this.displayedMonth, }) : assert(!firstDate.isAfter(lastDate)), assert(selectedDateStart == null || !selectedDateStart.isBefore(firstDate)), assert(selectedDateEnd == null || !selectedDateEnd.isBefore(firstDate)), assert(selectedDateStart == null || !selectedDateStart.isAfter(lastDate)), assert(selectedDateEnd == null || !selectedDateEnd.isAfter(lastDate)), assert(selectedDateStart == null || selectedDateEnd == null || !selectedDateStart.isAfter(selectedDateEnd)); /// The currently selected start date. /// /// This date is highlighted in the picker. final DateTime? selectedDateStart; /// The currently selected end date. /// /// This date is highlighted in the picker. final DateTime? selectedDateEnd; /// The current date at the time the picker is displayed. final DateTime currentDate; /// Called when the user picks a day. final ValueChanged<DateTime> onChanged; /// The earliest date the user is permitted to pick. final DateTime firstDate; /// The latest date the user is permitted to pick. final DateTime lastDate; /// The month whose days are displayed by this picker. final DateTime displayedMonth; @override _MonthItemState createState() => _MonthItemState(); } class _MonthItemState extends State<_MonthItem> { /// List of [FocusNode]s, one for each day of the month. late List<FocusNode> _dayFocusNodes; @override void initState() { super.initState(); final int daysInMonth = DateUtils.getDaysInMonth(widget.displayedMonth.year, widget.displayedMonth.month); _dayFocusNodes = List<FocusNode>.generate( daysInMonth, (int index) => FocusNode(skipTraversal: true, debugLabel: 'Day ${index + 1}'), ); } @override void didChangeDependencies() { super.didChangeDependencies(); // Check to see if the focused date is in this month, if so focus it. final DateTime? focusedDate = _FocusedDate.maybeOf(context)?.date; if (focusedDate != null && DateUtils.isSameMonth(widget.displayedMonth, focusedDate)) { _dayFocusNodes[focusedDate.day - 1].requestFocus(); } } @override void dispose() { for (final FocusNode node in _dayFocusNodes) { node.dispose(); } super.dispose(); } Color _highlightColor(BuildContext context) { return DatePickerTheme.of(context).rangeSelectionBackgroundColor ?? DatePickerTheme.defaults(context).rangeSelectionBackgroundColor!; } void _dayFocusChanged(bool focused) { if (focused) { final TraversalDirection? focusDirection = _FocusedDate.maybeOf(context)?.scrollDirection; if (focusDirection != null) { ScrollPositionAlignmentPolicy policy = ScrollPositionAlignmentPolicy.explicit; switch (focusDirection) { case TraversalDirection.up: case TraversalDirection.left: policy = ScrollPositionAlignmentPolicy.keepVisibleAtStart; case TraversalDirection.right: case TraversalDirection.down: policy = ScrollPositionAlignmentPolicy.keepVisibleAtEnd; } Scrollable.ensureVisible(primaryFocus!.context!, duration: _monthScrollDuration, alignmentPolicy: policy, ); } } } Widget _buildDayItem(BuildContext context, DateTime dayToBuild, int firstDayOffset, int daysInMonth) { final int day = dayToBuild.day; final bool isDisabled = dayToBuild.isAfter(widget.lastDate) || dayToBuild.isBefore(widget.firstDate); final bool isRangeSelected = widget.selectedDateStart != null && widget.selectedDateEnd != null; final bool isSelectedDayStart = widget.selectedDateStart != null && dayToBuild.isAtSameMomentAs(widget.selectedDateStart!); final bool isSelectedDayEnd = widget.selectedDateEnd != null && dayToBuild.isAtSameMomentAs(widget.selectedDateEnd!); final bool isInRange = isRangeSelected && dayToBuild.isAfter(widget.selectedDateStart!) && dayToBuild.isBefore(widget.selectedDateEnd!); final bool isOneDayRange = isRangeSelected && widget.selectedDateStart == widget.selectedDateEnd; final bool isToday = DateUtils.isSameDay(widget.currentDate, dayToBuild); return _DayItem( day: dayToBuild, focusNode: _dayFocusNodes[day - 1], onChanged: widget.onChanged, onFocusChange: _dayFocusChanged, highlightColor: _highlightColor(context), isDisabled: isDisabled, isRangeSelected: isRangeSelected, isSelectedDayStart: isSelectedDayStart, isSelectedDayEnd: isSelectedDayEnd, isInRange: isInRange, isOneDayRange: isOneDayRange, isToday: isToday, ); } Widget _buildEdgeContainer(BuildContext context, bool isHighlighted) { return Container(color: isHighlighted ? _highlightColor(context) : null); } @override Widget build(BuildContext context) { final ThemeData themeData = Theme.of(context); final TextTheme textTheme = themeData.textTheme; final MaterialLocalizations localizations = MaterialLocalizations.of(context); final int year = widget.displayedMonth.year; final int month = widget.displayedMonth.month; final int daysInMonth = DateUtils.getDaysInMonth(year, month); final int dayOffset = DateUtils.firstDayOffset(year, month, localizations); final int weeks = ((daysInMonth + dayOffset) / DateTime.daysPerWeek).ceil(); final double gridHeight = weeks * _monthItemRowHeight + (weeks - 1) * _monthItemSpaceBetweenRows; final List<Widget> dayItems = <Widget>[]; // 1-based day of month, e.g. 1-31 for January, and 1-29 for February on // a leap year. for (int day = 0 - dayOffset + 1; day <= daysInMonth; day += 1) { if (day < 1) { dayItems.add(Container()); } else { final DateTime dayToBuild = DateTime(year, month, day); final Widget dayItem = _buildDayItem( context, dayToBuild, dayOffset, daysInMonth, ); dayItems.add(dayItem); } } // Add the leading/trailing edge containers to each week in order to // correctly extend the range highlight. final List<Widget> paddedDayItems = <Widget>[]; for (int i = 0; i < weeks; i++) { final int start = i * DateTime.daysPerWeek; final int end = math.min( start + DateTime.daysPerWeek, dayItems.length, ); final List<Widget> weekList = dayItems.sublist(start, end); final DateTime dateAfterLeadingPadding = DateTime(year, month, start - dayOffset + 1); // Only color the edge container if it is after the start date and // on/before the end date. final bool isLeadingInRange = !(dayOffset > 0 && i == 0) && widget.selectedDateStart != null && widget.selectedDateEnd != null && dateAfterLeadingPadding.isAfter(widget.selectedDateStart!) && !dateAfterLeadingPadding.isAfter(widget.selectedDateEnd!); weekList.insert(0, _buildEdgeContainer(context, isLeadingInRange)); // Only add a trailing edge container if it is for a full week and not a // partial week. if (end < dayItems.length || (end == dayItems.length && dayItems.length % DateTime.daysPerWeek == 0)) { final DateTime dateBeforeTrailingPadding = DateTime(year, month, end - dayOffset); // Only color the edge container if it is on/after the start date and // before the end date. final bool isTrailingInRange = widget.selectedDateStart != null && widget.selectedDateEnd != null && !dateBeforeTrailingPadding.isBefore(widget.selectedDateStart!) && dateBeforeTrailingPadding.isBefore(widget.selectedDateEnd!); weekList.add(_buildEdgeContainer(context, isTrailingInRange)); } paddedDayItems.addAll(weekList); } final double maxWidth = MediaQuery.orientationOf(context) == Orientation.landscape ? _maxCalendarWidthLandscape : _maxCalendarWidthPortrait; return Column( children: <Widget>[ Container( constraints: BoxConstraints(maxWidth: maxWidth), height: _monthItemHeaderHeight, padding: const EdgeInsets.symmetric(horizontal: 16), alignment: AlignmentDirectional.centerStart, child: ExcludeSemantics( child: Text( localizations.formatMonthYear(widget.displayedMonth), style: textTheme.bodyMedium!.apply(color: themeData.colorScheme.onSurface), ), ), ), Container( constraints: BoxConstraints( maxWidth: maxWidth, maxHeight: gridHeight, ), child: GridView.custom( physics: const NeverScrollableScrollPhysics(), gridDelegate: _monthItemGridDelegate, childrenDelegate: SliverChildListDelegate( paddedDayItems, addRepaintBoundaries: false, ), ), ), const SizedBox(height: _monthItemFooterHeight), ], ); } } class _DayItem extends StatefulWidget { const _DayItem({ required this.day, required this.focusNode, required this.onChanged, required this.onFocusChange, required this.highlightColor, required this.isDisabled, required this.isRangeSelected, required this.isSelectedDayStart, required this.isSelectedDayEnd, required this.isInRange, required this.isOneDayRange, required this.isToday, }); final DateTime day; final FocusNode focusNode; final ValueChanged<DateTime> onChanged; final ValueChanged<bool> onFocusChange; final Color highlightColor; final bool isDisabled; final bool isRangeSelected; final bool isSelectedDayStart; final bool isSelectedDayEnd; final bool isInRange; final bool isOneDayRange; final bool isToday; @override State<_DayItem> createState() => _DayItemState(); } class _DayItemState extends State<_DayItem> { final MaterialStatesController _statesController = MaterialStatesController(); @override void dispose() { _statesController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final ColorScheme colorScheme = theme.colorScheme; final TextTheme textTheme = theme.textTheme; final MaterialLocalizations localizations = MaterialLocalizations.of(context); final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context); final DatePickerThemeData defaults = DatePickerTheme.defaults(context); final TextDirection textDirection = Directionality.of(context); final Color highlightColor = widget.highlightColor; BoxDecoration? decoration; TextStyle? itemStyle = textTheme.bodyMedium; T? effectiveValue<T>(T? Function(DatePickerThemeData? theme) getProperty) { return getProperty(datePickerTheme) ?? getProperty(defaults); } T? resolve<T>(MaterialStateProperty<T>? Function(DatePickerThemeData? theme) getProperty, Set<MaterialState> states) { return effectiveValue( (DatePickerThemeData? theme) { return getProperty(theme)?.resolve(states); }, ); } final Set<MaterialState> states = <MaterialState>{ if (widget.isDisabled) MaterialState.disabled, if (widget.isSelectedDayStart || widget.isSelectedDayEnd) MaterialState.selected, }; _statesController.value = states; final Color? dayForegroundColor = resolve<Color?>((DatePickerThemeData? theme) => theme?.dayForegroundColor, states); final Color? dayBackgroundColor = resolve<Color?>((DatePickerThemeData? theme) => theme?.dayBackgroundColor, states); final MaterialStateProperty<Color?> dayOverlayColor = MaterialStateProperty.resolveWith<Color?>( (Set<MaterialState> states) => effectiveValue( (DatePickerThemeData? theme) => widget.isInRange ? theme?.rangeSelectionOverlayColor?.resolve(states) : theme?.dayOverlayColor?.resolve(states), ) ); _HighlightPainter? highlightPainter; if (widget.isSelectedDayStart || widget.isSelectedDayEnd) { // The selected start and end dates gets a circle background // highlight, and a contrasting text color. itemStyle = textTheme.bodyMedium?.apply(color: dayForegroundColor); decoration = BoxDecoration( color: dayBackgroundColor, shape: BoxShape.circle, ); if (widget.isRangeSelected && !widget.isOneDayRange) { final _HighlightPainterStyle style = widget.isSelectedDayStart ? _HighlightPainterStyle.highlightTrailing : _HighlightPainterStyle.highlightLeading; highlightPainter = _HighlightPainter( color: highlightColor, style: style, textDirection: textDirection, ); } } else if (widget.isInRange) { // The days within the range get a light background highlight. highlightPainter = _HighlightPainter( color: highlightColor, style: _HighlightPainterStyle.highlightAll, textDirection: textDirection, ); } else if (widget.isDisabled) { itemStyle = textTheme.bodyMedium?.apply(color: colorScheme.onSurface.withOpacity(0.38)); } else if (widget.isToday) { // The current day gets a different text color and a circle stroke // border. itemStyle = textTheme.bodyMedium?.apply(color: colorScheme.primary); decoration = BoxDecoration( border: Border.all(color: colorScheme.primary), shape: BoxShape.circle, ); } final String dayText = localizations.formatDecimal(widget.day.day); // We want the day of month to be spoken first irrespective of the // locale-specific preferences or TextDirection. This is because // an accessibility user is more likely to be interested in the // day of month before the rest of the date, as they are looking // for the day of month. To do that we prepend day of month to the // formatted full date. final String semanticLabelSuffix = widget.isToday ? ', ${localizations.currentDateLabel}' : ''; String semanticLabel = '$dayText, ${localizations.formatFullDate(widget.day)}$semanticLabelSuffix'; if (widget.isSelectedDayStart) { semanticLabel = localizations.dateRangeStartDateSemanticLabel(semanticLabel); } else if (widget.isSelectedDayEnd) { semanticLabel = localizations.dateRangeEndDateSemanticLabel(semanticLabel); } Widget dayWidget = Container( decoration: decoration, child: Center( child: Semantics( label: semanticLabel, selected: widget.isSelectedDayStart || widget.isSelectedDayEnd, child: ExcludeSemantics( child: Text(dayText, style: itemStyle), ), ), ), ); if (highlightPainter != null) { dayWidget = CustomPaint( painter: highlightPainter, child: dayWidget, ); } if (!widget.isDisabled) { dayWidget = InkResponse( focusNode: widget.focusNode, onTap: () => widget.onChanged(widget.day), radius: _monthItemRowHeight / 2 + 4, statesController: _statesController, overlayColor: dayOverlayColor, onFocusChange: widget.onFocusChange, child: dayWidget, ); } return dayWidget; } } /// Determines which style to use to paint the highlight. enum _HighlightPainterStyle { /// Paints nothing. none, /// Paints a rectangle that occupies the leading half of the space. highlightLeading, /// Paints a rectangle that occupies the trailing half of the space. highlightTrailing, /// Paints a rectangle that occupies all available space. highlightAll, } /// This custom painter will add a background highlight to its child. /// /// This highlight will be drawn depending on the [style], [color], and /// [textDirection] supplied. It will either paint a rectangle on the /// left/right, a full rectangle, or nothing at all. This logic is determined by /// a combination of the [style] and [textDirection]. class _HighlightPainter extends CustomPainter { _HighlightPainter({ required this.color, this.style = _HighlightPainterStyle.none, this.textDirection, }); final Color color; final _HighlightPainterStyle style; final TextDirection? textDirection; @override void paint(Canvas canvas, Size size) { if (style == _HighlightPainterStyle.none) { return; } final Paint paint = Paint() ..color = color ..style = PaintingStyle.fill; final bool rtl = switch (textDirection) { TextDirection.rtl || null => true, TextDirection.ltr => false, }; switch (style) { case _HighlightPainterStyle.highlightLeading when rtl: case _HighlightPainterStyle.highlightTrailing when !rtl: canvas.drawRect(Rect.fromLTWH(size.width / 2, 0, size.width / 2, size.height), paint); case _HighlightPainterStyle.highlightLeading: case _HighlightPainterStyle.highlightTrailing: canvas.drawRect(Rect.fromLTWH(0, 0, size.width / 2, size.height), paint); case _HighlightPainterStyle.highlightAll: canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint); case _HighlightPainterStyle.none: break; } } @override bool shouldRepaint(CustomPainter oldDelegate) => false; } class _InputDateRangePickerDialog extends StatelessWidget { const _InputDateRangePickerDialog({ required this.selectedStartDate, required this.selectedEndDate, required this.currentDate, required this.picker, required this.onConfirm, required this.onCancel, required this.confirmText, required this.cancelText, required this.helpText, required this.entryModeButton, }); final DateTime? selectedStartDate; final DateTime? selectedEndDate; final DateTime? currentDate; final Widget picker; final VoidCallback onConfirm; final VoidCallback onCancel; final String? confirmText; final String? cancelText; final String? helpText; final Widget? entryModeButton; String _formatDateRange(BuildContext context, DateTime? start, DateTime? end, DateTime now) { final MaterialLocalizations localizations = MaterialLocalizations.of(context); final String startText = _formatRangeStartDate(localizations, start, end); final String endText = _formatRangeEndDate(localizations, start, end, now); if (start == null || end == null) { return localizations.unspecifiedDateRange; } if (Directionality.of(context) == TextDirection.ltr) { return '$startText – $endText'; } else { return '$endText – $startText'; } } @override Widget build(BuildContext context) { final bool useMaterial3 = Theme.of(context).useMaterial3; final MaterialLocalizations localizations = MaterialLocalizations.of(context); final Orientation orientation = MediaQuery.orientationOf(context); final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context); final DatePickerThemeData defaults = DatePickerTheme.defaults(context); // There's no M3 spec for a landscape layout input (not calendar) // date range picker. To ensure that the date range displayed in the // input date range picker's header fits in landscape mode, we override // the M3 default here. TextStyle? headlineStyle = (orientation == Orientation.portrait) ? datePickerTheme.headerHeadlineStyle ?? defaults.headerHeadlineStyle : Theme.of(context).textTheme.headlineSmall; final Color? headerForegroundColor = datePickerTheme.headerForegroundColor ?? defaults.headerForegroundColor; headlineStyle = headlineStyle?.copyWith(color: headerForegroundColor); final String dateText = _formatDateRange(context, selectedStartDate, selectedEndDate, currentDate!); final String semanticDateText = selectedStartDate != null && selectedEndDate != null ? '${localizations.formatMediumDate(selectedStartDate!)} – ${localizations.formatMediumDate(selectedEndDate!)}' : ''; final Widget header = _DatePickerHeader( helpText: helpText ?? ( useMaterial3 ? localizations.dateRangePickerHelpText : localizations.dateRangePickerHelpText.toUpperCase() ), titleText: dateText, titleSemanticsLabel: semanticDateText, titleStyle: headlineStyle, orientation: orientation, isShort: orientation == Orientation.landscape, entryModeButton: entryModeButton, ); final Widget actions = Container( alignment: AlignmentDirectional.centerEnd, constraints: const BoxConstraints(minHeight: 52.0), padding: const EdgeInsets.symmetric(horizontal: 8), child: OverflowBar( spacing: 8, children: <Widget>[ TextButton( onPressed: onCancel, child: Text(cancelText ?? ( useMaterial3 ? localizations.cancelButtonLabel : localizations.cancelButtonLabel.toUpperCase() )), ), TextButton( onPressed: onConfirm, child: Text(confirmText ?? localizations.okButtonLabel), ), ], ), ); // 14 is a common font size used to compute the effective text scale. const double fontSizeToScale = 14.0; final double textScaleFactor = MediaQuery.textScalerOf(context).clamp(maxScaleFactor: _kMaxTextScaleFactor).scale(fontSizeToScale) / fontSizeToScale; final Size dialogSize = (useMaterial3 ? _inputPortraitDialogSizeM3 : _inputPortraitDialogSizeM2) * textScaleFactor; switch (orientation) { case Orientation.portrait: return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { final Size portraitDialogSize = useMaterial3 ? _inputPortraitDialogSizeM3 : _inputPortraitDialogSizeM2; // Make sure the portrait dialog can fit the contents comfortably when // resized from the landscape dialog. final bool isFullyPortrait = constraints.maxHeight >= math.min(dialogSize.height, portraitDialogSize.height); return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ header, if (isFullyPortrait) ...<Widget>[ Expanded(child: picker), actions, ], ], ); } ); case Orientation.landscape: return Row( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ header, Flexible( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Expanded(child: picker), actions, ], ), ), ], ); } } } /// Provides a pair of text fields that allow the user to enter the start and /// end dates that represent a range of dates. class _InputDateRangePicker extends StatefulWidget { /// Creates a row with two text fields configured to accept the start and end dates /// of a date range. _InputDateRangePicker({ super.key, DateTime? initialStartDate, DateTime? initialEndDate, required DateTime firstDate, required DateTime lastDate, required this.onStartDateChanged, required this.onEndDateChanged, this.helpText, this.errorFormatText, this.errorInvalidText, this.errorInvalidRangeText, this.fieldStartHintText, this.fieldEndHintText, this.fieldStartLabelText, this.fieldEndLabelText, this.autofocus = false, this.autovalidate = false, this.keyboardType = TextInputType.datetime, }) : initialStartDate = initialStartDate == null ? null : DateUtils.dateOnly(initialStartDate), initialEndDate = initialEndDate == null ? null : DateUtils.dateOnly(initialEndDate), firstDate = DateUtils.dateOnly(firstDate), lastDate = DateUtils.dateOnly(lastDate); /// The [DateTime] that represents the start of the initial date range selection. final DateTime? initialStartDate; /// The [DateTime] that represents the end of the initial date range selection. final DateTime? initialEndDate; /// The earliest allowable [DateTime] that the user can select. final DateTime firstDate; /// The latest allowable [DateTime] that the user can select. final DateTime lastDate; /// Called when the user changes the start date of the selected range. final ValueChanged<DateTime?>? onStartDateChanged; /// Called when the user changes the end date of the selected range. final ValueChanged<DateTime?>? onEndDateChanged; /// The text that is displayed at the top of the header. /// /// This is used to indicate to the user what they are selecting a date for. final String? helpText; /// Error text used to indicate the text in a field is not a valid date. final String? errorFormatText; /// Error text used to indicate the date in a field is not in the valid range /// of [firstDate] - [lastDate]. final String? errorInvalidText; /// Error text used to indicate the dates given don't form a valid date /// range (i.e. the start date is after the end date). final String? errorInvalidRangeText; /// Hint text shown when the start date field is empty. final String? fieldStartHintText; /// Hint text shown when the end date field is empty. final String? fieldEndHintText; /// Label used for the start date field. final String? fieldStartLabelText; /// Label used for the end date field. final String? fieldEndLabelText; /// {@macro flutter.widgets.editableText.autofocus} final bool autofocus; /// If true, the date fields will validate and update their error text /// immediately after every change. Otherwise, you must call /// [_InputDateRangePickerState.validate] to validate. final bool autovalidate; /// {@macro flutter.material.datePickerDialog} final TextInputType keyboardType; @override _InputDateRangePickerState createState() => _InputDateRangePickerState(); } /// The current state of an [_InputDateRangePicker]. Can be used to /// [validate] the date field entries. class _InputDateRangePickerState extends State<_InputDateRangePicker> { late String _startInputText; late String _endInputText; DateTime? _startDate; DateTime? _endDate; late TextEditingController _startController; late TextEditingController _endController; String? _startErrorText; String? _endErrorText; bool _autoSelected = false; @override void initState() { super.initState(); _startDate = widget.initialStartDate; _startController = TextEditingController(); _endDate = widget.initialEndDate; _endController = TextEditingController(); } @override void dispose() { _startController.dispose(); _endController.dispose(); super.dispose(); } @override void didChangeDependencies() { super.didChangeDependencies(); final MaterialLocalizations localizations = MaterialLocalizations.of(context); if (_startDate != null) { _startInputText = localizations.formatCompactDate(_startDate!); final bool selectText = widget.autofocus && !_autoSelected; _updateController(_startController, _startInputText, selectText); _autoSelected = selectText; } if (_endDate != null) { _endInputText = localizations.formatCompactDate(_endDate!); _updateController(_endController, _endInputText, false); } } /// Validates that the text in the start and end fields represent a valid /// date range. /// /// Will return true if the range is valid. If not, it will /// return false and display an appropriate error message under one of the /// text fields. bool validate() { String? startError = _validateDate(_startDate); final String? endError = _validateDate(_endDate); if (startError == null && endError == null) { if (_startDate!.isAfter(_endDate!)) { startError = widget.errorInvalidRangeText ?? MaterialLocalizations.of(context).invalidDateRangeLabel; } } setState(() { _startErrorText = startError; _endErrorText = endError; }); return startError == null && endError == null; } DateTime? _parseDate(String? text) { final MaterialLocalizations localizations = MaterialLocalizations.of(context); return localizations.parseCompactDate(text); } String? _validateDate(DateTime? date) { if (date == null) { return widget.errorFormatText ?? MaterialLocalizations.of(context).invalidDateFormatLabel; } else if (date.isBefore(widget.firstDate) || date.isAfter(widget.lastDate)) { return widget.errorInvalidText ?? MaterialLocalizations.of(context).dateOutOfRangeLabel; } return null; } void _updateController(TextEditingController controller, String text, bool selectText) { TextEditingValue textEditingValue = controller.value.copyWith(text: text); if (selectText) { textEditingValue = textEditingValue.copyWith(selection: TextSelection( baseOffset: 0, extentOffset: text.length, )); } controller.value = textEditingValue; } void _handleStartChanged(String text) { setState(() { _startInputText = text; _startDate = _parseDate(text); widget.onStartDateChanged?.call(_startDate); }); if (widget.autovalidate) { validate(); } } void _handleEndChanged(String text) { setState(() { _endInputText = text; _endDate = _parseDate(text); widget.onEndDateChanged?.call(_endDate); }); if (widget.autovalidate) { validate(); } } @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final bool useMaterial3 = theme.useMaterial3; final MaterialLocalizations localizations = MaterialLocalizations.of(context); final InputDecorationTheme inputTheme = theme.inputDecorationTheme; final InputBorder inputBorder = inputTheme.border ?? (useMaterial3 ? const OutlineInputBorder() : const UnderlineInputBorder()); return Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Expanded( child: TextField( controller: _startController, decoration: InputDecoration( border: inputBorder, filled: inputTheme.filled, hintText: widget.fieldStartHintText ?? localizations.dateHelpText, labelText: widget.fieldStartLabelText ?? localizations.dateRangeStartLabel, errorText: _startErrorText, ), keyboardType: widget.keyboardType, onChanged: _handleStartChanged, autofocus: widget.autofocus, ), ), const SizedBox(width: 8), Expanded( child: TextField( controller: _endController, decoration: InputDecoration( border: inputBorder, filled: inputTheme.filled, hintText: widget.fieldEndHintText ?? localizations.dateHelpText, labelText: widget.fieldEndLabelText ?? localizations.dateRangeEndLabel, errorText: _endErrorText, ), keyboardType: widget.keyboardType, onChanged: _handleEndChanged, ), ), ], ); } }
flutter/packages/flutter/lib/src/material/date_picker.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/date_picker.dart", "repo_id": "flutter", "token_count": 42542 }
629
// 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:ui' show lerpDouble; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'button_style.dart'; import 'button_style_button.dart'; import 'color_scheme.dart'; import 'colors.dart'; import 'constants.dart'; import 'elevated_button_theme.dart'; import 'ink_ripple.dart'; import 'ink_well.dart'; import 'material_state.dart'; import 'theme.dart'; import 'theme_data.dart'; /// A Material Design "elevated button". /// /// Use elevated buttons to add dimension to otherwise mostly flat /// layouts, e.g. in long busy lists of content, or in wide /// spaces. Avoid using elevated buttons on already-elevated content /// such as dialogs or cards. /// /// An elevated button is a label [child] displayed on a [Material] /// widget whose [Material.elevation] increases when the button is /// pressed. The label's [Text] and [Icon] widgets are displayed in /// [style]'s [ButtonStyle.foregroundColor] and the button's filled /// background is the [ButtonStyle.backgroundColor]. /// /// The elevated button's default style is defined by /// [defaultStyleOf]. The style of this elevated button can be /// overridden with its [style] parameter. The style of all elevated /// buttons in a subtree can be overridden with the /// [ElevatedButtonTheme], and the style of all of the elevated /// buttons in an app can be overridden with the [Theme]'s /// [ThemeData.elevatedButtonTheme] property. /// /// The static [styleFrom] method is a convenient way to create a /// elevated button [ButtonStyle] from simple values. /// /// If [onPressed] and [onLongPress] callbacks are null, then the /// button will be disabled. /// /// {@tool dartpad} /// This sample produces an enabled and a disabled ElevatedButton. /// /// ** See code in examples/api/lib/material/elevated_button/elevated_button.0.dart ** /// {@end-tool} /// /// See also: /// /// * [FilledButton], a filled button that doesn't elevate when pressed. /// * [FilledButton.tonal], a filled button variant that uses a secondary fill color. /// * [OutlinedButton], a button with an outlined border and no fill color. /// * [TextButton], a button with no outline or fill color. /// * <https://material.io/design/components/buttons.html> /// * <https://m3.material.io/components/buttons> class ElevatedButton extends ButtonStyleButton { /// Create an ElevatedButton. const ElevatedButton({ super.key, required super.onPressed, super.onLongPress, super.onHover, super.onFocusChange, super.style, super.focusNode, super.autofocus = false, super.clipBehavior, super.statesController, required super.child, super.iconAlignment, }); /// Create an elevated button from a pair of widgets that serve as the button's /// [icon] and [label]. /// /// The icon and label are arranged in a row and padded by 12 logical pixels /// at the start, and 16 at the end, with an 8 pixel gap in between. /// /// If [icon] is null, will create an [ElevatedButton] instead. /// /// {@macro flutter.material.ButtonStyleButton.iconAlignment} /// factory ElevatedButton.icon({ Key? key, required VoidCallback? onPressed, VoidCallback? onLongPress, ValueChanged<bool>? onHover, ValueChanged<bool>? onFocusChange, ButtonStyle? style, FocusNode? focusNode, bool? autofocus, Clip? clipBehavior, MaterialStatesController? statesController, Widget? icon, required Widget label, IconAlignment iconAlignment = IconAlignment.start, }) { if (icon == null) { return ElevatedButton( key: key, onPressed: onPressed, onLongPress: onLongPress, onHover: onHover, onFocusChange: onFocusChange, style: style, focusNode: focusNode, autofocus: autofocus ?? false, clipBehavior: clipBehavior ?? Clip.none, statesController: statesController, child: label, ); } return _ElevatedButtonWithIcon( key: key, onPressed: onPressed, onLongPress: onLongPress, onHover: onHover, onFocusChange: onFocusChange, style: style, focusNode: focusNode, autofocus: autofocus ?? false, clipBehavior: clipBehavior ?? Clip.none, statesController: statesController, icon: icon, label: label, iconAlignment: iconAlignment, ); } /// A static convenience method that constructs an elevated button /// [ButtonStyle] given simple values. /// /// The [foregroundColor] and [disabledForegroundColor] colors are used /// to create a [MaterialStateProperty] [ButtonStyle.foregroundColor], and /// a derived [ButtonStyle.overlayColor] if [overlayColor] isn't specified. /// /// If [overlayColor] is specified and its value is [Colors.transparent] /// then the pressed/focused/hovered highlights are effectively defeated. /// Otherwise a [MaterialStateProperty] with the same opacities as the /// default is created. /// /// The [backgroundColor] and [disabledBackgroundColor] colors are /// used to create a [MaterialStateProperty] [ButtonStyle.backgroundColor]. /// /// Similarly, the [enabledMouseCursor] and [disabledMouseCursor] /// parameters are used to construct [ButtonStyle.mouseCursor] and /// [iconColor], [disabledIconColor] are used to construct /// [ButtonStyle.iconColor]. /// /// The button's elevations are defined relative to the [elevation] /// parameter. The disabled elevation is the same as the parameter /// value, [elevation] + 2 is used when the button is hovered /// or focused, and elevation + 6 is used when the button is pressed. /// /// All of the other parameters are either used directly or used to /// create a [MaterialStateProperty] with a single value for all /// states. /// /// All parameters default to null, by default this method returns /// a [ButtonStyle] that doesn't override anything. /// /// For example, to override the default text and icon colors for a /// [ElevatedButton], as well as its overlay color, with all of the /// standard opacity adjustments for the pressed, focused, and /// hovered states, one could write: /// /// ```dart /// ElevatedButton( /// style: ElevatedButton.styleFrom(foregroundColor: Colors.green), /// onPressed: () { /// // ... /// }, /// child: const Text('Jump'), /// ), /// ``` /// /// And to change the fill color: /// /// ```dart /// ElevatedButton( /// style: ElevatedButton.styleFrom(backgroundColor: Colors.green), /// onPressed: () { /// // ... /// }, /// child: const Text('Meow'), /// ), /// ``` /// static ButtonStyle styleFrom({ Color? foregroundColor, Color? backgroundColor, Color? disabledForegroundColor, Color? disabledBackgroundColor, Color? shadowColor, Color? surfaceTintColor, Color? iconColor, Color? disabledIconColor, Color? overlayColor, double? elevation, TextStyle? textStyle, EdgeInsetsGeometry? padding, Size? minimumSize, Size? fixedSize, Size? maximumSize, BorderSide? side, OutlinedBorder? shape, MouseCursor? enabledMouseCursor, MouseCursor? disabledMouseCursor, VisualDensity? visualDensity, MaterialTapTargetSize? tapTargetSize, Duration? animationDuration, bool? enableFeedback, AlignmentGeometry? alignment, InteractiveInkFeatureFactory? splashFactory, ButtonLayerBuilder? backgroundBuilder, ButtonLayerBuilder? foregroundBuilder, }) { final MaterialStateProperty<Color?>? foregroundColorProp = switch ((foregroundColor, disabledForegroundColor)) { (null, null) => null, (_, _) => _ElevatedButtonDefaultColor(foregroundColor, disabledForegroundColor), }; final MaterialStateProperty<Color?>? backgroundColorProp = switch ((backgroundColor, disabledBackgroundColor)) { (null, null) => null, (_, _) => _ElevatedButtonDefaultColor(backgroundColor, disabledBackgroundColor), }; final MaterialStateProperty<Color?>? iconColorProp = switch ((iconColor, disabledIconColor)) { (null, null) => null, (_, _) => _ElevatedButtonDefaultColor(iconColor, disabledIconColor), }; final MaterialStateProperty<Color?>? overlayColorProp = switch ((foregroundColor, overlayColor)) { (null, null) => null, (_, final Color overlayColor) when overlayColor.value == 0 => const MaterialStatePropertyAll<Color?>(Colors.transparent), (_, _) => _ElevatedButtonDefaultOverlay((overlayColor ?? foregroundColor)!), }; final MaterialStateProperty<double>? elevationValue = switch (elevation) { null => null, _ => _ElevatedButtonDefaultElevation(elevation), }; final MaterialStateProperty<MouseCursor?> mouseCursor = _ElevatedButtonDefaultMouseCursor(enabledMouseCursor, disabledMouseCursor); return ButtonStyle( textStyle: MaterialStatePropertyAll<TextStyle?>(textStyle), backgroundColor: backgroundColorProp, foregroundColor: foregroundColorProp, overlayColor: overlayColorProp, shadowColor: ButtonStyleButton.allOrNull<Color>(shadowColor), surfaceTintColor: ButtonStyleButton.allOrNull<Color>(surfaceTintColor), iconColor: iconColorProp, elevation: elevationValue, padding: ButtonStyleButton.allOrNull<EdgeInsetsGeometry>(padding), minimumSize: ButtonStyleButton.allOrNull<Size>(minimumSize), fixedSize: ButtonStyleButton.allOrNull<Size>(fixedSize), maximumSize: ButtonStyleButton.allOrNull<Size>(maximumSize), side: ButtonStyleButton.allOrNull<BorderSide>(side), shape: ButtonStyleButton.allOrNull<OutlinedBorder>(shape), mouseCursor: mouseCursor, visualDensity: visualDensity, tapTargetSize: tapTargetSize, animationDuration: animationDuration, enableFeedback: enableFeedback, alignment: alignment, splashFactory: splashFactory, backgroundBuilder: backgroundBuilder, foregroundBuilder: foregroundBuilder, ); } /// Defines the button's default appearance. /// /// The button [child]'s [Text] and [Icon] widgets are rendered with /// the [ButtonStyle]'s foreground color. The button's [InkWell] adds /// the style's overlay color when the button is focused, hovered /// or pressed. The button's background color becomes its [Material] /// color. /// /// All of the ButtonStyle's defaults appear below. In this list /// "Theme.foo" is shorthand for `Theme.of(context).foo`. Color /// scheme values like "onSurface(0.38)" are shorthand for /// `onSurface.withOpacity(0.38)`. [MaterialStateProperty] valued /// properties that are not followed by a sublist have the same /// value for all states, otherwise the values are as specified for /// each state, and "others" means all other states. /// /// {@template flutter.material.elevated_button.default_font_size} /// The "default font size" below refers to the font size specified in the /// [defaultStyleOf] method (or 14.0 if unspecified), scaled by the /// `MediaQuery.textScalerOf(context).scale` method. The names of the /// EdgeInsets constructors and `EdgeInsetsGeometry.lerp` have been abbreviated /// for readability. /// {@endtemplate} /// /// The color of the [ButtonStyle.textStyle] is not used, the /// [ButtonStyle.foregroundColor] color is used instead. /// /// ## Material 2 defaults /// /// * `textStyle` - Theme.textTheme.button /// * `backgroundColor` /// * disabled - Theme.colorScheme.onSurface(0.12) /// * others - Theme.colorScheme.primary /// * `foregroundColor` /// * disabled - Theme.colorScheme.onSurface(0.38) /// * others - Theme.colorScheme.onPrimary /// * `overlayColor` /// * hovered - Theme.colorScheme.onPrimary(0.08) /// * focused or pressed - Theme.colorScheme.onPrimary(0.12) /// * `shadowColor` - Theme.shadowColor /// * `elevation` /// * disabled - 0 /// * default - 2 /// * hovered or focused - 4 /// * pressed - 8 /// * `padding` /// * `default font size <= 14` - horizontal(16) /// * `14 < default font size <= 28` - lerp(horizontal(16), horizontal(8)) /// * `28 < default font size <= 36` - lerp(horizontal(8), horizontal(4)) /// * `36 < default font size` - horizontal(4) /// * `minimumSize` - Size(64, 36) /// * `fixedSize` - null /// * `maximumSize` - Size.infinite /// * `side` - null /// * `shape` - RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)) /// * `mouseCursor` /// * disabled - SystemMouseCursors.basic /// * others - SystemMouseCursors.click /// * `visualDensity` - theme.visualDensity /// * `tapTargetSize` - theme.materialTapTargetSize /// * `animationDuration` - kThemeChangeDuration /// * `enableFeedback` - true /// * `alignment` - Alignment.center /// * `splashFactory` - InkRipple.splashFactory /// /// The default padding values for the [ElevatedButton.icon] factory are slightly different: /// /// * `padding` /// * `default font size <= 14` - start(12) end(16) /// * `14 < default font size <= 28` - lerp(start(12) end(16), horizontal(8)) /// * `28 < default font size <= 36` - lerp(horizontal(8), horizontal(4)) /// * `36 < default font size` - horizontal(4) /// /// The default value for `side`, which defines the appearance of the button's /// outline, is null. That means that the outline is defined by the button /// shape's [OutlinedBorder.side]. Typically the default value of an /// [OutlinedBorder]'s side is [BorderSide.none], so an outline is not drawn. /// /// ## Material 3 defaults /// /// If [ThemeData.useMaterial3] is set to true the following defaults will /// be used: /// /// * `textStyle` - Theme.textTheme.labelLarge /// * `backgroundColor` /// * disabled - Theme.colorScheme.onSurface(0.12) /// * others - Theme.colorScheme.surfaceContainerLow /// * `foregroundColor` /// * disabled - Theme.colorScheme.onSurface(0.38) /// * others - Theme.colorScheme.primary /// * `overlayColor` /// * hovered - Theme.colorScheme.primary(0.08) /// * focused or pressed - Theme.colorScheme.primary(0.1) /// * `shadowColor` - Theme.colorScheme.shadow /// * `surfaceTintColor` - Colors.transparent /// * `elevation` /// * disabled - 0 /// * default - 1 /// * hovered - 3 /// * focused or pressed - 1 /// * `padding` /// * `default font size <= 14` - horizontal(24) /// * `14 < default font size <= 28` - lerp(horizontal(24), horizontal(12)) /// * `28 < default font size <= 36` - lerp(horizontal(12), horizontal(6)) /// * `36 < default font size` - horizontal(6) /// * `minimumSize` - Size(64, 40) /// * `fixedSize` - null /// * `maximumSize` - Size.infinite /// * `side` - null /// * `shape` - StadiumBorder() /// * `mouseCursor` /// * disabled - SystemMouseCursors.basic /// * others - SystemMouseCursors.click /// * `visualDensity` - Theme.visualDensity /// * `tapTargetSize` - Theme.materialTapTargetSize /// * `animationDuration` - kThemeChangeDuration /// * `enableFeedback` - true /// * `alignment` - Alignment.center /// * `splashFactory` - Theme.splashFactory /// /// For the [ElevatedButton.icon] factory, the start (generally the left) value of /// [padding] is reduced from 24 to 16. @override ButtonStyle defaultStyleOf(BuildContext context) { final ThemeData theme = Theme.of(context); final ColorScheme colorScheme = theme.colorScheme; return Theme.of(context).useMaterial3 ? _ElevatedButtonDefaultsM3(context) : styleFrom( backgroundColor: colorScheme.primary, foregroundColor: colorScheme.onPrimary, disabledBackgroundColor: colorScheme.onSurface.withOpacity(0.12), disabledForegroundColor: colorScheme.onSurface.withOpacity(0.38), shadowColor: theme.shadowColor, elevation: 2, textStyle: theme.textTheme.labelLarge, padding: _scaledPadding(context), minimumSize: const Size(64, 36), maximumSize: Size.infinite, shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4))), enabledMouseCursor: SystemMouseCursors.click, disabledMouseCursor: SystemMouseCursors.basic, visualDensity: theme.visualDensity, tapTargetSize: theme.materialTapTargetSize, animationDuration: kThemeChangeDuration, enableFeedback: true, alignment: Alignment.center, splashFactory: InkRipple.splashFactory, ); } /// Returns the [ElevatedButtonThemeData.style] of the closest /// [ElevatedButtonTheme] ancestor. @override ButtonStyle? themeStyleOf(BuildContext context) { return ElevatedButtonTheme.of(context).style; } } EdgeInsetsGeometry _scaledPadding(BuildContext context) { final ThemeData theme = Theme.of(context); final double padding1x = theme.useMaterial3 ? 24.0 : 16.0; final double defaultFontSize = theme.textTheme.labelLarge?.fontSize ?? 14.0; final double effectiveTextScale = MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0; return ButtonStyleButton.scaledPadding( EdgeInsets.symmetric(horizontal: padding1x), EdgeInsets.symmetric(horizontal: padding1x / 2), EdgeInsets.symmetric(horizontal: padding1x / 2 / 2), effectiveTextScale, ); } @immutable class _ElevatedButtonDefaultColor extends MaterialStateProperty<Color?> with Diagnosticable { _ElevatedButtonDefaultColor(this.color, this.disabled); final Color? color; final Color? disabled; @override Color? resolve(Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return disabled; } return color; } } @immutable class _ElevatedButtonDefaultOverlay extends MaterialStateProperty<Color?> with Diagnosticable { _ElevatedButtonDefaultOverlay(this.overlay); final Color overlay; @override Color? resolve(Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return overlay.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return overlay.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { return overlay.withOpacity(0.1); } return null; } } @immutable class _ElevatedButtonDefaultElevation extends MaterialStateProperty<double> with Diagnosticable { _ElevatedButtonDefaultElevation(this.elevation); final double elevation; @override double resolve(Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return 0; } if (states.contains(MaterialState.pressed)) { return elevation + 6; } if (states.contains(MaterialState.hovered)) { return elevation + 2; } if (states.contains(MaterialState.focused)) { return elevation + 2; } return elevation; } } @immutable class _ElevatedButtonDefaultMouseCursor extends MaterialStateProperty<MouseCursor?> with Diagnosticable { _ElevatedButtonDefaultMouseCursor(this.enabledCursor, this.disabledCursor); final MouseCursor? enabledCursor; final MouseCursor? disabledCursor; @override MouseCursor? resolve(Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return disabledCursor; } return enabledCursor; } } class _ElevatedButtonWithIcon extends ElevatedButton { _ElevatedButtonWithIcon({ super.key, required super.onPressed, super.onLongPress, super.onHover, super.onFocusChange, super.style, super.focusNode, bool? autofocus, super.clipBehavior, super.statesController, required Widget icon, required Widget label, super.iconAlignment, }) : super( autofocus: autofocus ?? false, child: _ElevatedButtonWithIconChild( icon: icon, label: label, buttonStyle: style, iconAlignment: iconAlignment, ), ); @override ButtonStyle defaultStyleOf(BuildContext context) { final bool useMaterial3 = Theme.of(context).useMaterial3; final ButtonStyle buttonStyle = super.defaultStyleOf(context); final double defaultFontSize = buttonStyle.textStyle?.resolve(const <MaterialState>{})?.fontSize ?? 14.0; final double effectiveTextScale = MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0; final EdgeInsetsGeometry scaledPadding = useMaterial3 ? ButtonStyleButton.scaledPadding( const EdgeInsetsDirectional.fromSTEB(16, 0, 24, 0), const EdgeInsetsDirectional.fromSTEB(8, 0, 12, 0), const EdgeInsetsDirectional.fromSTEB(4, 0, 6, 0), effectiveTextScale, ) : ButtonStyleButton.scaledPadding( const EdgeInsetsDirectional.fromSTEB(12, 0, 16, 0), const EdgeInsets.symmetric(horizontal: 8), const EdgeInsetsDirectional.fromSTEB(8, 0, 4, 0), effectiveTextScale, ); return buttonStyle.copyWith( padding: MaterialStatePropertyAll<EdgeInsetsGeometry>(scaledPadding), ); } } class _ElevatedButtonWithIconChild extends StatelessWidget { const _ElevatedButtonWithIconChild({ required this.label, required this.icon, required this.buttonStyle, required this.iconAlignment, }); final Widget label; final Widget icon; final ButtonStyle? buttonStyle; final IconAlignment iconAlignment; @override Widget build(BuildContext context) { final double defaultFontSize = buttonStyle?.textStyle?.resolve(const <MaterialState>{})?.fontSize ?? 14.0; final double scale = clampDouble(MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0, 1.0, 2.0) - 1.0; final double gap = lerpDouble(8, 4, scale)!; return Row( mainAxisSize: MainAxisSize.min, children: iconAlignment == IconAlignment.start ? <Widget>[icon, SizedBox(width: gap), Flexible(child: label)] : <Widget>[Flexible(child: label), SizedBox(width: gap), icon], ); } } // BEGIN GENERATED TOKEN PROPERTIES - ElevatedButton // Do not edit by hand. The code between the "BEGIN GENERATED" and // "END GENERATED" comments are generated from data in the Material // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. class _ElevatedButtonDefaultsM3 extends ButtonStyle { _ElevatedButtonDefaultsM3(this.context) : super( animationDuration: kThemeChangeDuration, enableFeedback: true, alignment: Alignment.center, ); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; @override MaterialStateProperty<TextStyle?> get textStyle => MaterialStatePropertyAll<TextStyle?>(Theme.of(context).textTheme.labelLarge); @override MaterialStateProperty<Color?>? get backgroundColor => MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return _colors.onSurface.withOpacity(0.12); } return _colors.surfaceContainerLow; }); @override MaterialStateProperty<Color?>? get foregroundColor => MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return _colors.onSurface.withOpacity(0.38); } return _colors.primary; }); @override MaterialStateProperty<Color?>? get overlayColor => MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return _colors.primary.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.primary.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { return _colors.primary.withOpacity(0.1); } return null; }); @override MaterialStateProperty<Color>? get shadowColor => MaterialStatePropertyAll<Color>(_colors.shadow); @override MaterialStateProperty<Color>? get surfaceTintColor => const MaterialStatePropertyAll<Color>(Colors.transparent); @override MaterialStateProperty<double>? get elevation => MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return 0.0; } if (states.contains(MaterialState.pressed)) { return 1.0; } if (states.contains(MaterialState.hovered)) { return 3.0; } if (states.contains(MaterialState.focused)) { return 1.0; } return 1.0; }); @override MaterialStateProperty<EdgeInsetsGeometry>? get padding => MaterialStatePropertyAll<EdgeInsetsGeometry>(_scaledPadding(context)); @override MaterialStateProperty<Size>? get minimumSize => const MaterialStatePropertyAll<Size>(Size(64.0, 40.0)); // No default fixedSize @override MaterialStateProperty<Size>? get maximumSize => const MaterialStatePropertyAll<Size>(Size.infinite); // No default side @override MaterialStateProperty<OutlinedBorder>? get shape => const MaterialStatePropertyAll<OutlinedBorder>(StadiumBorder()); @override MaterialStateProperty<MouseCursor?>? get mouseCursor => MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return SystemMouseCursors.basic; } return SystemMouseCursors.click; }); @override VisualDensity? get visualDensity => Theme.of(context).visualDensity; @override MaterialTapTargetSize? get tapTargetSize => Theme.of(context).materialTapTargetSize; @override InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory; } // END GENERATED TOKEN PROPERTIES - ElevatedButton
flutter/packages/flutter/lib/src/material/elevated_button.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/elevated_button.dart", "repo_id": "flutter", "token_count": 8794 }
630
// 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 'package:flutter/widgets.dart'; /// A tile in a Material Design grid list. /// /// A grid list is a [GridView] of tiles in a vertical and horizontal /// array. Each tile typically contains some visually rich content (e.g., an /// image) together with a [GridTileBar] in either a [header] or a [footer]. /// /// See also: /// /// * [GridView], which is a scrollable grid of tiles. /// * [GridTileBar], which is typically used in either the [header] or /// [footer]. /// * <https://material.io/design/components/image-lists.html> class GridTile extends StatelessWidget { /// Creates a grid tile. /// /// Must have a child. Does not typically have both a header and a footer. const GridTile({ super.key, this.header, this.footer, required this.child, }); /// The widget to show over the top of this grid tile. /// /// Typically a [GridTileBar]. final Widget? header; /// The widget to show over the bottom of this grid tile. /// /// Typically a [GridTileBar]. final Widget? footer; /// The widget that fills the tile. /// /// {@macro flutter.widgets.ProxyWidget.child} final Widget child; @override Widget build(BuildContext context) { if (header == null && footer == null) { return child; } return Stack( children: <Widget>[ Positioned.fill( child: child, ), if (header != null) Positioned( top: 0.0, left: 0.0, right: 0.0, child: header!, ), if (footer != null) Positioned( left: 0.0, bottom: 0.0, right: 0.0, child: footer!, ), ], ); } }
flutter/packages/flutter/lib/src/material/grid_tile.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/grid_tile.dart", "repo_id": "flutter", "token_count": 737 }
631
// 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:ui' show lerpDouble; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'list_tile.dart'; import 'material_state.dart'; import 'theme.dart'; import 'theme_data.dart'; // Examples can assume: // late BuildContext context; /// Used with [ListTileTheme] to define default property values for /// descendant [ListTile] widgets, as well as classes that build /// [ListTile]s, like [CheckboxListTile], [RadioListTile], and /// [SwitchListTile]. /// /// Descendant widgets obtain the current [ListTileThemeData] object /// using `ListTileTheme.of(context)`. Instances of /// [ListTileThemeData] can be customized with /// [ListTileThemeData.copyWith]. /// /// A [ListTileThemeData] is often specified as part of the /// overall [Theme] with [ThemeData.listTileTheme]. /// /// All [ListTileThemeData] properties are `null` by default. /// When a theme property is null, the [ListTile] will provide its own /// default based on the overall [Theme]'s textTheme and /// colorScheme. See the individual [ListTile] properties for details. /// /// The [Drawer] widget specifies a list tile theme for its children that /// defines [style] to be [ListTileStyle.drawer]. /// /// See also: /// /// * [ThemeData], which describes the overall theme information for the /// application. @immutable class ListTileThemeData with Diagnosticable { /// Creates a [ListTileThemeData]. const ListTileThemeData ({ this.dense, this.shape, this.style, this.selectedColor, this.iconColor, this.textColor, this.titleTextStyle, this.subtitleTextStyle, this.leadingAndTrailingTextStyle, this.contentPadding, this.tileColor, this.selectedTileColor, this.horizontalTitleGap, this.minVerticalPadding, this.minLeadingWidth, this.enableFeedback, this.mouseCursor, this.visualDensity, this.minTileHeight, this.titleAlignment, }); /// Overrides the default value of [ListTile.dense]. final bool? dense; /// Overrides the default value of [ListTile.shape]. final ShapeBorder? shape; /// Overrides the default value of [ListTile.style]. final ListTileStyle? style; /// Overrides the default value of [ListTile.selectedColor]. final Color? selectedColor; /// Overrides the default value of [ListTile.iconColor]. final Color? iconColor; /// Overrides the default value of [ListTile.textColor]. final Color? textColor; /// Overrides the default value of [ListTile.titleTextStyle]. final TextStyle? titleTextStyle; /// Overrides the default value of [ListTile.subtitleTextStyle]. final TextStyle? subtitleTextStyle; /// Overrides the default value of [ListTile.leadingAndTrailingTextStyle]. final TextStyle? leadingAndTrailingTextStyle; /// Overrides the default value of [ListTile.contentPadding]. final EdgeInsetsGeometry? contentPadding; /// Overrides the default value of [ListTile.tileColor]. final Color? tileColor; /// Overrides the default value of [ListTile.selectedTileColor]. final Color? selectedTileColor; /// Overrides the default value of [ListTile.horizontalTitleGap]. final double? horizontalTitleGap; /// Overrides the default value of [ListTile.minVerticalPadding]. final double? minVerticalPadding; /// Overrides the default value of [ListTile.minLeadingWidth]. final double? minLeadingWidth; /// Overrides the default value of [ListTile.minTileHeight]. final double? minTileHeight; /// Overrides the default value of [ListTile.enableFeedback]. final bool? enableFeedback; /// If specified, overrides the default value of [ListTile.mouseCursor]. final MaterialStateProperty<MouseCursor?>? mouseCursor; /// If specified, overrides the default value of [ListTile.visualDensity]. final VisualDensity? visualDensity; /// If specified, overrides the default value of [ListTile.titleAlignment]. final ListTileTitleAlignment? titleAlignment; /// Creates a copy of this object with the given fields replaced with the /// new values. ListTileThemeData copyWith({ bool? dense, ShapeBorder? shape, ListTileStyle? style, Color? selectedColor, Color? iconColor, Color? textColor, TextStyle? titleTextStyle, TextStyle? subtitleTextStyle, TextStyle? leadingAndTrailingTextStyle, EdgeInsetsGeometry? contentPadding, Color? tileColor, Color? selectedTileColor, double? horizontalTitleGap, double? minVerticalPadding, double? minLeadingWidth, double? minTileHeight, bool? enableFeedback, MaterialStateProperty<MouseCursor?>? mouseCursor, bool? isThreeLine, VisualDensity? visualDensity, ListTileTitleAlignment? titleAlignment, }) { return ListTileThemeData( dense: dense ?? this.dense, shape: shape ?? this.shape, style: style ?? this.style, selectedColor: selectedColor ?? this.selectedColor, iconColor: iconColor ?? this.iconColor, textColor: textColor ?? this.textColor, titleTextStyle: titleTextStyle ?? this.titleTextStyle, subtitleTextStyle: subtitleTextStyle ?? this.subtitleTextStyle, leadingAndTrailingTextStyle: leadingAndTrailingTextStyle ?? this.leadingAndTrailingTextStyle, contentPadding: contentPadding ?? this.contentPadding, tileColor: tileColor ?? this.tileColor, selectedTileColor: selectedTileColor ?? this.selectedTileColor, horizontalTitleGap: horizontalTitleGap ?? this.horizontalTitleGap, minVerticalPadding: minVerticalPadding ?? this.minVerticalPadding, minLeadingWidth: minLeadingWidth ?? this.minLeadingWidth, minTileHeight: minTileHeight ?? this.minTileHeight, enableFeedback: enableFeedback ?? this.enableFeedback, mouseCursor: mouseCursor ?? this.mouseCursor, visualDensity: visualDensity ?? this.visualDensity, titleAlignment: titleAlignment ?? this.titleAlignment, ); } /// Linearly interpolate between ListTileThemeData objects. static ListTileThemeData? lerp(ListTileThemeData? a, ListTileThemeData? b, double t) { if (identical(a, b)) { return a; } return ListTileThemeData( dense: t < 0.5 ? a?.dense : b?.dense, shape: ShapeBorder.lerp(a?.shape, b?.shape, t), style: t < 0.5 ? a?.style : b?.style, selectedColor: Color.lerp(a?.selectedColor, b?.selectedColor, t), iconColor: Color.lerp(a?.iconColor, b?.iconColor, t), textColor: Color.lerp(a?.textColor, b?.textColor, t), titleTextStyle: TextStyle.lerp(a?.titleTextStyle, b?.titleTextStyle, t), subtitleTextStyle: TextStyle.lerp(a?.subtitleTextStyle, b?.subtitleTextStyle, t), leadingAndTrailingTextStyle: TextStyle.lerp(a?.leadingAndTrailingTextStyle, b?.leadingAndTrailingTextStyle, t), contentPadding: EdgeInsetsGeometry.lerp(a?.contentPadding, b?.contentPadding, t), tileColor: Color.lerp(a?.tileColor, b?.tileColor, t), selectedTileColor: Color.lerp(a?.selectedTileColor, b?.selectedTileColor, t), horizontalTitleGap: lerpDouble(a?.horizontalTitleGap, b?.horizontalTitleGap, t), minVerticalPadding: lerpDouble(a?.minVerticalPadding, b?.minVerticalPadding, t), minLeadingWidth: lerpDouble(a?.minLeadingWidth, b?.minLeadingWidth, t), minTileHeight: lerpDouble(a?.minTileHeight, b?.minTileHeight, t), enableFeedback: t < 0.5 ? a?.enableFeedback : b?.enableFeedback, mouseCursor: t < 0.5 ? a?.mouseCursor : b?.mouseCursor, visualDensity: t < 0.5 ? a?.visualDensity : b?.visualDensity, titleAlignment: t < 0.5 ? a?.titleAlignment : b?.titleAlignment, ); } @override int get hashCode => Object.hash( dense, shape, style, selectedColor, iconColor, textColor, titleTextStyle, subtitleTextStyle, leadingAndTrailingTextStyle, contentPadding, tileColor, selectedTileColor, horizontalTitleGap, minVerticalPadding, minLeadingWidth, minTileHeight, enableFeedback, mouseCursor, visualDensity, titleAlignment, ); @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is ListTileThemeData && other.dense == dense && other.shape == shape && other.style == style && other.selectedColor == selectedColor && other.iconColor == iconColor && other.titleTextStyle == titleTextStyle && other.subtitleTextStyle == subtitleTextStyle && other.leadingAndTrailingTextStyle == leadingAndTrailingTextStyle && other.textColor == textColor && other.contentPadding == contentPadding && other.tileColor == tileColor && other.selectedTileColor == selectedTileColor && other.horizontalTitleGap == horizontalTitleGap && other.minVerticalPadding == minVerticalPadding && other.minLeadingWidth == minLeadingWidth && other.minTileHeight == minTileHeight && other.enableFeedback == enableFeedback && other.mouseCursor == mouseCursor && other.visualDensity == visualDensity && other.titleAlignment == titleAlignment; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<bool>('dense', dense, defaultValue: null)); properties.add(DiagnosticsProperty<ShapeBorder>('shape', shape, defaultValue: null)); properties.add(EnumProperty<ListTileStyle>('style', style, defaultValue: null)); properties.add(ColorProperty('selectedColor', selectedColor, defaultValue: null)); properties.add(ColorProperty('iconColor', iconColor, defaultValue: null)); properties.add(ColorProperty('textColor', textColor, defaultValue: null)); properties.add(DiagnosticsProperty<TextStyle>('titleTextStyle', titleTextStyle, defaultValue: null)); properties.add(DiagnosticsProperty<TextStyle>('subtitleTextStyle', subtitleTextStyle, defaultValue: null)); properties.add(DiagnosticsProperty<TextStyle>('leadingAndTrailingTextStyle', leadingAndTrailingTextStyle, defaultValue: null)); properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('contentPadding', contentPadding, defaultValue: null)); properties.add(ColorProperty('tileColor', tileColor, defaultValue: null)); properties.add(ColorProperty('selectedTileColor', selectedTileColor, defaultValue: null)); properties.add(DoubleProperty('horizontalTitleGap', horizontalTitleGap, defaultValue: null)); properties.add(DoubleProperty('minVerticalPadding', minVerticalPadding, defaultValue: null)); properties.add(DoubleProperty('minLeadingWidth', minLeadingWidth, defaultValue: null)); properties.add(DoubleProperty('minTileHeight', minTileHeight, defaultValue: null)); properties.add(DiagnosticsProperty<bool>('enableFeedback', enableFeedback, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<MouseCursor?>>('mouseCursor', mouseCursor, defaultValue: null)); properties.add(DiagnosticsProperty<VisualDensity>('visualDensity', visualDensity, defaultValue: null)); properties.add(DiagnosticsProperty<ListTileTitleAlignment>('titleAlignment', titleAlignment, defaultValue: null)); } } /// An inherited widget that defines color and style parameters for [ListTile]s /// in this widget's subtree. /// /// Values specified here are used for [ListTile] properties that are not given /// an explicit non-null value. /// /// The [Drawer] widget specifies a tile theme for its children which sets /// [style] to [ListTileStyle.drawer]. class ListTileTheme extends InheritedTheme { /// Creates a list tile theme that defines the color and style parameters for /// descendant [ListTile]s. /// /// Only the [data] parameter should be used. The other parameters are /// redundant (are now obsolete) and will be deprecated in a future update. const ListTileTheme({ super.key, ListTileThemeData? data, bool? dense, ShapeBorder? shape, ListTileStyle? style, Color? selectedColor, Color? iconColor, Color? textColor, EdgeInsetsGeometry? contentPadding, Color? tileColor, Color? selectedTileColor, bool? enableFeedback, MaterialStateProperty<MouseCursor?>? mouseCursor, double? horizontalTitleGap, double? minVerticalPadding, double? minLeadingWidth, required super.child, }) : assert( data == null || (shape ?? selectedColor ?? iconColor ?? textColor ?? contentPadding ?? tileColor ?? selectedTileColor ?? enableFeedback ?? mouseCursor ?? horizontalTitleGap ?? minVerticalPadding ?? minLeadingWidth) == null), _data = data, _dense = dense, _shape = shape, _style = style, _selectedColor = selectedColor, _iconColor = iconColor, _textColor = textColor, _contentPadding = contentPadding, _tileColor = tileColor, _selectedTileColor = selectedTileColor, _enableFeedback = enableFeedback, _mouseCursor = mouseCursor, _horizontalTitleGap = horizontalTitleGap, _minVerticalPadding = minVerticalPadding, _minLeadingWidth = minLeadingWidth; final ListTileThemeData? _data; final bool? _dense; final ShapeBorder? _shape; final ListTileStyle? _style; final Color? _selectedColor; final Color? _iconColor; final Color? _textColor; final EdgeInsetsGeometry? _contentPadding; final Color? _tileColor; final Color? _selectedTileColor; final double? _horizontalTitleGap; final double? _minVerticalPadding; final double? _minLeadingWidth; final bool? _enableFeedback; final MaterialStateProperty<MouseCursor?>? _mouseCursor; /// The configuration of this theme. ListTileThemeData get data { return _data ?? ListTileThemeData( dense: _dense, shape: _shape, style: _style, selectedColor: _selectedColor, iconColor: _iconColor, textColor: _textColor, contentPadding: _contentPadding, tileColor: _tileColor, selectedTileColor: _selectedTileColor, enableFeedback: _enableFeedback, mouseCursor: _mouseCursor, horizontalTitleGap: _horizontalTitleGap, minVerticalPadding: _minVerticalPadding, minLeadingWidth: _minLeadingWidth, ); } /// Overrides the default value of [ListTile.dense]. /// /// This property is obsolete: please use the [data] /// [ListTileThemeData.dense] property instead. bool? get dense => _data != null ? _data.dense : _dense; /// Overrides the default value of [ListTile.shape]. /// /// This property is obsolete: please use the [data] /// [ListTileThemeData.shape] property instead. ShapeBorder? get shape => _data != null ? _data.shape : _shape; /// Overrides the default value of [ListTile.style]. /// /// This property is obsolete: please use the [data] /// [ListTileThemeData.style] property instead. ListTileStyle? get style => _data != null ? _data.style : _style; /// Overrides the default value of [ListTile.selectedColor]. /// /// This property is obsolete: please use the [data] /// [ListTileThemeData.selectedColor] property instead. Color? get selectedColor => _data != null ? _data.selectedColor : _selectedColor; /// Overrides the default value of [ListTile.iconColor]. /// /// This property is obsolete: please use the [data] /// [ListTileThemeData.iconColor] property instead. Color? get iconColor => _data != null ? _data.iconColor : _iconColor; /// Overrides the default value of [ListTile.textColor]. /// /// This property is obsolete: please use the [data] /// [ListTileThemeData.textColor] property instead. Color? get textColor => _data != null ? _data.textColor : _textColor; /// Overrides the default value of [ListTile.contentPadding]. /// /// This property is obsolete: please use the [data] /// [ListTileThemeData.contentPadding] property instead. EdgeInsetsGeometry? get contentPadding => _data != null ? _data.contentPadding : _contentPadding; /// Overrides the default value of [ListTile.tileColor]. /// /// This property is obsolete: please use the [data] /// [ListTileThemeData.tileColor] property instead. Color? get tileColor => _data != null ? _data.tileColor : _tileColor; /// Overrides the default value of [ListTile.selectedTileColor]. /// /// This property is obsolete: please use the [data] /// [ListTileThemeData.selectedTileColor] property instead. Color? get selectedTileColor => _data != null ? _data.selectedTileColor : _selectedTileColor; /// Overrides the default value of [ListTile.horizontalTitleGap]. /// /// This property is obsolete: please use the [data] /// [ListTileThemeData.horizontalTitleGap] property instead. double? get horizontalTitleGap => _data != null ? _data.horizontalTitleGap : _horizontalTitleGap; /// Overrides the default value of [ListTile.minVerticalPadding]. /// /// This property is obsolete: please use the [data] /// [ListTileThemeData.minVerticalPadding] property instead. double? get minVerticalPadding => _data != null ? _data.minVerticalPadding : _minVerticalPadding; /// Overrides the default value of [ListTile.minLeadingWidth]. /// /// This property is obsolete: please use the [data] /// [ListTileThemeData.minLeadingWidth] property instead. double? get minLeadingWidth => _data != null ? _data.minLeadingWidth : _minLeadingWidth; /// Overrides the default value of [ListTile.enableFeedback]. /// /// This property is obsolete: please use the [data] /// [ListTileThemeData.enableFeedback] property instead. bool? get enableFeedback => _data != null ? _data.enableFeedback : _enableFeedback; /// The [data] property of the closest instance of this class that /// encloses the given context. /// /// If there is no enclosing [ListTileTheme] widget, then /// [ThemeData.listTileTheme] is used (see [Theme.of]). /// /// Typical usage is as follows: /// /// ```dart /// ListTileThemeData theme = ListTileTheme.of(context); /// ``` static ListTileThemeData of(BuildContext context) { final ListTileTheme? result = context.dependOnInheritedWidgetOfExactType<ListTileTheme>(); return result?.data ?? Theme.of(context).listTileTheme; } /// Creates a list tile theme that controls the color and style parameters for /// [ListTile]s, and merges in the current list tile theme, if any. static Widget merge({ Key? key, bool? dense, ShapeBorder? shape, ListTileStyle? style, Color? selectedColor, Color? iconColor, Color? textColor, TextStyle? titleTextStyle, TextStyle? subtitleTextStyle, TextStyle? leadingAndTrailingTextStyle, EdgeInsetsGeometry? contentPadding, Color? tileColor, Color? selectedTileColor, bool? enableFeedback, double? horizontalTitleGap, double? minVerticalPadding, double? minLeadingWidth, double? minTileHeight, ListTileTitleAlignment? titleAlignment, MaterialStateProperty<MouseCursor?>? mouseCursor, VisualDensity? visualDensity, required Widget child, }) { return Builder( builder: (BuildContext context) { final ListTileThemeData parent = ListTileTheme.of(context); return ListTileTheme( key: key, data: ListTileThemeData( dense: dense ?? parent.dense, shape: shape ?? parent.shape, style: style ?? parent.style, selectedColor: selectedColor ?? parent.selectedColor, iconColor: iconColor ?? parent.iconColor, textColor: textColor ?? parent.textColor, titleTextStyle: titleTextStyle ?? parent.titleTextStyle, subtitleTextStyle: subtitleTextStyle ?? parent.subtitleTextStyle, leadingAndTrailingTextStyle: leadingAndTrailingTextStyle ?? parent.leadingAndTrailingTextStyle, contentPadding: contentPadding ?? parent.contentPadding, tileColor: tileColor ?? parent.tileColor, selectedTileColor: selectedTileColor ?? parent.selectedTileColor, enableFeedback: enableFeedback ?? parent.enableFeedback, horizontalTitleGap: horizontalTitleGap ?? parent.horizontalTitleGap, minVerticalPadding: minVerticalPadding ?? parent.minVerticalPadding, minLeadingWidth: minLeadingWidth ?? parent.minLeadingWidth, minTileHeight: minTileHeight ?? parent.minTileHeight, titleAlignment: titleAlignment ?? parent.titleAlignment, mouseCursor: mouseCursor ?? parent.mouseCursor, visualDensity: visualDensity ?? parent.visualDensity, ), child: child, ); }, ); } @override Widget wrap(BuildContext context, Widget child) { return ListTileTheme( data: ListTileThemeData( dense: dense, shape: shape, style: style, selectedColor: selectedColor, iconColor: iconColor, textColor: textColor, contentPadding: contentPadding, tileColor: tileColor, selectedTileColor: selectedTileColor, enableFeedback: enableFeedback, horizontalTitleGap: horizontalTitleGap, minVerticalPadding: minVerticalPadding, minLeadingWidth: minLeadingWidth, ), child: child, ); } @override bool updateShouldNotify(ListTileTheme oldWidget) => data != oldWidget.data; }
flutter/packages/flutter/lib/src/material/list_tile_theme.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/list_tile_theme.dart", "repo_id": "flutter", "token_count": 7356 }
632
// 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 'package:flutter/widgets.dart'; import 'color_scheme.dart'; import 'colors.dart'; import 'drawer.dart'; import 'ink_well.dart'; import 'material.dart'; import 'material_localizations.dart'; import 'material_state.dart'; import 'navigation_bar.dart'; import 'navigation_drawer_theme.dart'; import 'text_theme.dart'; import 'theme.dart'; /// Material Design Navigation Drawer component. /// /// On top of [Drawer]s, Navigation drawers offer a persistent and convenient way to switch /// between primary destinations in an app. /// /// The style for the icons and text are not affected by parent /// [DefaultTextStyle]s or [IconTheme]s but rather controlled by parameters or /// the [NavigationDrawerThemeData]. /// /// The [children] are a list of widgets to be displayed in the drawer. These can be a /// mixture of any widgets, but there is special handling for [NavigationDrawerDestination]s. /// They are treated as a group and when one is selected, the [onDestinationSelected] /// is called with the index into the group that corresponds to the selected destination. /// /// {@tool dartpad} /// This example shows a [NavigationDrawer] used within a [Scaffold] /// widget. The [NavigationDrawer] has headline widget, divider widget and three /// [NavigationDrawerDestination] widgets. The initial [selectedIndex] is 0. /// The [onDestinationSelected] callback changes the selected item's index and displays /// a corresponding widget in the body of the [Scaffold]. /// /// ** See code in examples/api/lib/material/navigation_drawer/navigation_drawer.0.dart ** /// {@end-tool} /// /// See also: /// /// * [Scaffold.drawer], where one specifies a [Drawer] so that it can be /// shown. /// * [Scaffold.of], to obtain the current [ScaffoldState], which manages the /// display and animation of the drawer. /// * [ScaffoldState.openDrawer], which displays its [Drawer], if any. /// * <https://material.io/design/components/navigation-drawer.html> class NavigationDrawer extends StatelessWidget { /// Creates a Material Design Navigation Drawer component. const NavigationDrawer({ super.key, required this.children, this.backgroundColor, this.shadowColor, this.surfaceTintColor, this.elevation, this.indicatorColor, this.indicatorShape, this.onDestinationSelected, this.selectedIndex = 0, this.tilePadding = const EdgeInsets.symmetric(horizontal: 12.0), }); /// The background color of the [Material] that holds the [NavigationDrawer]'s /// contents. /// /// If this is null, then [NavigationDrawerThemeData.backgroundColor] is used. /// If that is also null, then it falls back to [ColorScheme.surfaceContainerLow]. final Color? backgroundColor; /// The color used for the drop shadow to indicate elevation. /// /// If null, [NavigationDrawerThemeData.shadowColor] is used. If that /// is also null, the default value is [Colors.transparent] which /// indicates that no drop shadow will be displayed. /// /// See [Material.shadowColor] for more details on drop shadows. final Color? shadowColor; /// The surface tint of the [Material] that holds the [NavigationDrawer]'s /// contents. /// /// 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 this is null, then [NavigationDrawerThemeData.surfaceTintColor] is used. /// If that is also null, the default value is [Colors.transparent]. final Color? surfaceTintColor; /// The elevation of the [NavigationDrawer] itself. /// /// If null, [NavigationDrawerThemeData.elevation] is used. If that /// is also null, it will be 1.0. final double? elevation; /// The color of the [indicatorShape] when this destination is selected. /// /// If this is null, [NavigationDrawerThemeData.indicatorColor] is used. /// If that is also null, defaults to [ColorScheme.secondaryContainer]. final Color? indicatorColor; /// The shape of the selected indicator. /// /// If this is null, [NavigationDrawerThemeData.indicatorShape] is used. /// If that is also null, defaults to [StadiumBorder]. final ShapeBorder? indicatorShape; /// Defines the appearance of the items within the navigation drawer. /// /// The list contains [NavigationDrawerDestination] widgets and/or customized /// widgets like headlines and dividers. final List<Widget> children; /// The index into destinations for the current selected /// [NavigationDrawerDestination] or null if no destination is selected. /// /// A valid [selectedIndex] satisfies 0 <= [selectedIndex] < number of [NavigationDrawerDestination]. /// For an invalid [selectedIndex] like `-1`, all destinations will appear unselected. final int? selectedIndex; /// Called when one of the [NavigationDrawerDestination] children is selected. /// /// This callback usually updates the int passed to [selectedIndex]. /// /// Upon updating [selectedIndex], the [NavigationDrawer] will be rebuilt. final ValueChanged<int>? onDestinationSelected; /// Defines the padding for [NavigationDrawerDestination] widgets (Drawer items). /// /// Defaults to `EdgeInsets.symmetric(horizontal: 12.0)`. final EdgeInsetsGeometry tilePadding; @override Widget build(BuildContext context) { final int totalNumberOfDestinations = children.whereType<NavigationDrawerDestination>().toList().length; int destinationIndex = 0; final List<Widget> wrappedChildren = <Widget>[]; Widget wrapChild(Widget child, int index) => _SelectableAnimatedBuilder( duration: const Duration(milliseconds: 500), isSelected: index == selectedIndex, builder: (BuildContext context, Animation<double> animation) { return _NavigationDrawerDestinationInfo( index: index, totalNumberOfDestinations: totalNumberOfDestinations, selectedAnimation: animation, indicatorColor: indicatorColor, indicatorShape: indicatorShape, tilePadding: tilePadding, onTap: () { if (onDestinationSelected != null) { onDestinationSelected!(index); } }, child: child, ); }); for (int i = 0; i < children.length; i++) { if (children[i] is! NavigationDrawerDestination) { wrappedChildren.add(children[i]); } else { wrappedChildren.add(wrapChild(children[i], destinationIndex)); destinationIndex += 1; } } final NavigationDrawerThemeData navigationDrawerTheme = NavigationDrawerTheme.of(context); return Drawer( backgroundColor: backgroundColor ?? navigationDrawerTheme.backgroundColor, shadowColor: shadowColor ?? navigationDrawerTheme.shadowColor, surfaceTintColor: surfaceTintColor ?? navigationDrawerTheme.surfaceTintColor, elevation: elevation ?? navigationDrawerTheme.elevation, child: SafeArea( bottom: false, child: ListView( children: wrappedChildren, ), ), ); } } /// A Material Design [NavigationDrawer] destination. /// /// Displays an icon with a label, for use in [NavigationDrawer.children]. class NavigationDrawerDestination extends StatelessWidget { /// Creates a navigation drawer destination. const NavigationDrawerDestination({ super.key, this.backgroundColor, required this.icon, this.selectedIcon, required this.label, this.enabled = true, }); /// Sets the color of the destination. /// /// If this is null, then [NavigationDrawerThemeData.backgroundColor]. final Color? backgroundColor; /// The [Widget] (usually an [Icon]) that's displayed for this /// [NavigationDestination]. /// /// The icon will use [NavigationDrawerThemeData.iconTheme]. If this is /// null, the default [IconThemeData] would use a size of 24.0 and /// [ColorScheme.onSurfaceVariant]. final Widget icon; /// The optional [Widget] (usually an [Icon]) that's displayed when this /// [NavigationDestination] is selected. /// /// If [selectedIcon] is non-null, the destination will fade from /// [icon] to [selectedIcon] when this destination goes from unselected to /// selected. /// /// The icon will use [NavigationDrawerThemeData.iconTheme] with /// [MaterialState.selected]. If this is null, the default [IconThemeData] /// would use a size of 24.0 and [ColorScheme.onSecondaryContainer]. final Widget? selectedIcon; /// The text label that appears on the right of the icon /// /// The accompanying [Text] widget will use /// [NavigationDrawerThemeData.labelTextStyle]. If this are null, the default /// text style would use [TextTheme.labelLarge] with [ColorScheme.onSurfaceVariant]. final Widget label; /// Indicates that this destination is selectable. /// /// Defaults to true. final bool enabled; @override Widget build(BuildContext context) { const Set<MaterialState> selectedState = <MaterialState>{ MaterialState.selected }; const Set<MaterialState> unselectedState = <MaterialState>{}; const Set<MaterialState> disabledState = <MaterialState>{ MaterialState.disabled }; final NavigationDrawerThemeData navigationDrawerTheme = NavigationDrawerTheme.of(context); final NavigationDrawerThemeData defaults = _NavigationDrawerDefaultsM3(context); final Animation<double> animation = _NavigationDrawerDestinationInfo.of(context).selectedAnimation; return _NavigationDestinationBuilder( buildIcon: (BuildContext context) { final Widget selectedIconWidget = IconTheme.merge( data: navigationDrawerTheme.iconTheme?.resolve(enabled ? selectedState : disabledState) ?? defaults.iconTheme!.resolve(enabled ? selectedState : disabledState)!, child: selectedIcon ?? icon, ); final Widget unselectedIconWidget = IconTheme.merge( data: navigationDrawerTheme.iconTheme?.resolve(enabled ? unselectedState : disabledState) ?? defaults.iconTheme!.resolve(enabled ? unselectedState : disabledState)!, child: icon, ); return _isForwardOrCompleted(animation) ? selectedIconWidget : unselectedIconWidget; }, buildLabel: (BuildContext context) { final TextStyle? effectiveSelectedLabelTextStyle = navigationDrawerTheme.labelTextStyle?.resolve(enabled ? selectedState : disabledState) ?? defaults.labelTextStyle!.resolve(enabled ? selectedState : disabledState); final TextStyle? effectiveUnselectedLabelTextStyle = navigationDrawerTheme.labelTextStyle?.resolve(enabled ? unselectedState : disabledState) ?? defaults.labelTextStyle!.resolve(enabled ? unselectedState : disabledState); return DefaultTextStyle( style: _isForwardOrCompleted(animation) ? effectiveSelectedLabelTextStyle! : effectiveUnselectedLabelTextStyle!, child: label, ); }, enabled: enabled, backgroundColor: backgroundColor, ); } } /// Widget that handles the semantics and layout of a navigation drawer /// destination. /// /// Prefer [NavigationDestination] over this widget, as it is a simpler /// (although less customizable) way to get navigation drawer destinations. /// /// The icon and label of this destination are built with [buildIcon] and /// [buildLabel]. They should build the unselected and selected icon and label /// according to [_NavigationDrawerDestinationInfo.selectedAnimation], where an /// animation value of 0 is unselected and 1 is selected. /// /// See [NavigationDestination] for an example. class _NavigationDestinationBuilder extends StatelessWidget { /// Builds a destination (icon + label) to use in a Material 3 [NavigationDrawer]. const _NavigationDestinationBuilder({ required this.buildIcon, required this.buildLabel, this.enabled = true, this.backgroundColor, }); /// Builds the icon for a destination in a [NavigationDrawer]. /// /// To animate between unselected and selected, build the icon based on /// [_NavigationDrawerDestinationInfo.selectedAnimation]. When the animation is 0, /// the destination is unselected, when the animation is 1, the destination is /// selected. /// /// The destination is considered selected as soon as the animation is /// increasing or completed, and it is considered unselected as soon as the /// animation is decreasing or dismissed. final WidgetBuilder buildIcon; /// Builds the label for a destination in a [NavigationDrawer]. /// /// To animate between unselected and selected, build the icon based on /// [_NavigationDrawerDestinationInfo.selectedAnimation]. When the animation is /// 0, the destination is unselected, when the animation is 1, the destination /// is selected. /// /// The destination is considered selected as soon as the animation is /// increasing or completed, and it is considered unselected as soon as the /// animation is decreasing or dismissed. final WidgetBuilder buildLabel; /// Indicates that this destination is selectable. /// /// Defaults to true. final bool enabled; /// Sets the color of navigation destination. /// /// If this is null, then [NavigationDrawerTheme.backgroundColor] is used. final Color? backgroundColor; @override Widget build(BuildContext context) { final _NavigationDrawerDestinationInfo info = _NavigationDrawerDestinationInfo.of(context); final NavigationDrawerThemeData navigationDrawerTheme = NavigationDrawerTheme.of(context); final NavigationDrawerThemeData defaults = _NavigationDrawerDefaultsM3(context); final Row destinationBody = Row( children: <Widget>[ const SizedBox(width: 16), buildIcon(context), const SizedBox(width: 12), buildLabel(context), ], ); return Container( padding: info.tilePadding, color: backgroundColor ?? navigationDrawerTheme.backgroundColor, child: _NavigationDestinationSemantics( child: SizedBox( height: navigationDrawerTheme.tileHeight ?? defaults.tileHeight, child: InkWell( highlightColor: Colors.transparent, onTap: enabled ? info.onTap : null, customBorder: info.indicatorShape ?? navigationDrawerTheme.indicatorShape ?? defaults.indicatorShape!, child: Stack( alignment: Alignment.center, children: <Widget>[ NavigationIndicator( animation: info.selectedAnimation, color: info.indicatorColor ?? navigationDrawerTheme.indicatorColor ?? defaults.indicatorColor!, shape: info.indicatorShape ?? navigationDrawerTheme.indicatorShape ?? defaults.indicatorShape!, width: (navigationDrawerTheme.indicatorSize ?? defaults.indicatorSize!).width, height: (navigationDrawerTheme.indicatorSize ?? defaults.indicatorSize!).height, ), destinationBody ], ), ), ), ), ); } } /// Semantics widget for a navigation drawer destination. /// /// Requires a [_NavigationDrawerDestinationInfo] parent (normally provided by the /// [NavigationDrawer] by default). /// /// Provides localized semantic labels to the destination, for example, it will /// read "Home, Tab 1 of 3". /// /// Used by [_NavigationDestinationBuilder]. class _NavigationDestinationSemantics extends StatelessWidget { /// Adds the appropriate semantics for navigation drawer destinations to the /// [child]. const _NavigationDestinationSemantics({ required this.child, }); /// The widget that should receive the destination semantics. final Widget child; @override Widget build(BuildContext context) { final MaterialLocalizations localizations = MaterialLocalizations.of(context); final _NavigationDrawerDestinationInfo destinationInfo = _NavigationDrawerDestinationInfo.of(context); // The AnimationStatusBuilder will make sure that the semantics update to // "selected" when the animation status changes. return _StatusTransitionWidgetBuilder( animation: destinationInfo.selectedAnimation, builder: (BuildContext context, Widget? child) { return Semantics( selected: _isForwardOrCompleted(destinationInfo.selectedAnimation), container: true, child: child, ); }, child: Stack( alignment: Alignment.center, children: <Widget>[ child, Semantics( label: localizations.tabLabel( tabIndex: destinationInfo.index + 1, tabCount: destinationInfo.totalNumberOfDestinations, ), ), ], ), ); } } /// Widget that listens to an animation, and rebuilds when the animation changes /// [AnimationStatus]. /// /// This can be more efficient than just using an [AnimatedBuilder] when you /// only need to rebuild when the [Animation.status] changes, since /// [AnimatedBuilder] rebuilds every time the animation ticks. class _StatusTransitionWidgetBuilder extends StatusTransitionWidget { /// Creates a widget that rebuilds when the given animation changes status. const _StatusTransitionWidgetBuilder({ required super.animation, required this.builder, this.child, }); /// Called every time the [animation] changes [AnimationStatus]. final TransitionBuilder builder; /// The child widget to pass to the [builder]. /// /// If a [builder] callback's return value contains a subtree that does not /// depend on the animation, it's more efficient to build that subtree once /// instead of rebuilding it on every animation status change. /// /// Using this pre-built child is entirely optional, but can improve /// performance in some cases and is therefore a good practice. /// /// See: [AnimatedBuilder.child] final Widget? child; @override Widget build(BuildContext context) => builder(context, child); } /// Inherited widget for passing data from the [NavigationDrawer] to the /// [NavigationDrawer.destinations] children widgets. /// /// Useful for building navigation destinations using: /// `_NavigationDrawerDestinationInfo.of(context)`. class _NavigationDrawerDestinationInfo extends InheritedWidget { /// Adds the information needed to build a navigation destination to the /// [child] and descendants. const _NavigationDrawerDestinationInfo({ required this.index, required this.totalNumberOfDestinations, required this.selectedAnimation, required this.indicatorColor, required this.indicatorShape, required this.onTap, required super.child, required this.tilePadding, }); /// Which destination index is this in the navigation drawer. /// /// For example: /// /// ```dart /// const NavigationDrawer( /// children: <Widget>[ /// Text('Headline'), // This doesn't have index. /// NavigationDrawerDestination( /// // This is destination index 0. /// icon: Icon(Icons.surfing), /// label: Text('Surfing'), /// ), /// NavigationDrawerDestination( /// // This is destination index 1. /// icon: Icon(Icons.support), /// label: Text('Support'), /// ), /// NavigationDrawerDestination( /// // This is destination index 2. /// icon: Icon(Icons.local_hospital), /// label: Text('Hospital'), /// ), /// ] /// ) /// ``` /// /// This is required for semantics, so that each destination can have a label /// "Tab 1 of 3", for example. final int index; /// How many total destinations are in this navigation drawer. /// /// This is required for semantics, so that each destination can have a label /// "Tab 1 of 4", for example. final int totalNumberOfDestinations; /// Indicates whether or not this destination is selected, from 0 (unselected) /// to 1 (selected). final Animation<double> selectedAnimation; /// The color of the indicator. /// /// This is used by destinations to override the indicator color. final Color? indicatorColor; /// The shape of the indicator. /// /// This is used by destinations to override the indicator shape. final ShapeBorder? indicatorShape; /// The callback that should be called when this destination is tapped. /// /// This is computed by calling [NavigationDrawer.onDestinationSelected] /// with [index] passed in. final VoidCallback onTap; /// Defines the padding for [NavigationDrawerDestination] widgets (Drawer items). /// /// Defaults to `EdgeInsets.symmetric(horizontal: 12.0)`. final EdgeInsetsGeometry tilePadding; /// Returns a non null [_NavigationDrawerDestinationInfo]. /// /// This will return an error if called with no [_NavigationDrawerDestinationInfo] /// ancestor. /// /// Used by widgets that are implementing a navigation destination info to /// get information like the selected animation and destination number. static _NavigationDrawerDestinationInfo of(BuildContext context) { final _NavigationDrawerDestinationInfo? result = context.dependOnInheritedWidgetOfExactType<_NavigationDrawerDestinationInfo>(); assert( result != null, 'Navigation destinations need a _NavigationDrawerDestinationInfo parent, ' 'which is usually provided by NavigationDrawer.', ); return result!; } @override bool updateShouldNotify(_NavigationDrawerDestinationInfo oldWidget) { return index != oldWidget.index || totalNumberOfDestinations != oldWidget.totalNumberOfDestinations || selectedAnimation != oldWidget.selectedAnimation || onTap != oldWidget.onTap; } } // Builder widget for widgets that need to be animated from 0 (unselected) to // 1.0 (selected). // // This widget creates and manages an [AnimationController] that it passes down // to the child through the [builder] function. // // When [isSelected] is `true`, the animation controller will animate from // 0 to 1 (for [duration] time). // // When [isSelected] is `false`, the animation controller will animate from // 1 to 0 (for [duration] time). // // If [isSelected] is updated while the widget is animating, the animation will // be reversed until it is either 0 or 1 again. // // Usage: // ```dart // _SelectableAnimatedBuilder( // isSelected: _isDrawerOpen, // builder: (context, animation) { // return AnimatedIcon( // icon: AnimatedIcons.menu_arrow, // progress: animation, // semanticLabel: 'Show menu', // ); // } // ) // ``` class _SelectableAnimatedBuilder extends StatefulWidget { /// Builds and maintains an [AnimationController] that will animate from 0 to /// 1 and back depending on when [isSelected] is true. const _SelectableAnimatedBuilder({ required this.isSelected, this.duration = const Duration(milliseconds: 200), required this.builder, }); /// When true, the widget will animate an animation controller from 0 to 1. /// /// The animation controller is passed to the child widget through [builder]. final bool isSelected; /// How long the animation controller should animate for when [isSelected] is /// updated. /// /// If the animation is currently running and [isSelected] is updated, only /// the [duration] left to finish the animation will be run. final Duration duration; /// Builds the child widget based on the current animation status. /// /// When [isSelected] is updated to true, this builder will be called and the /// animation will animate up to 1. When [isSelected] is updated to /// `false`, this will be called and the animation will animate down to 0. final Widget Function(BuildContext, Animation<double>) builder; /// @override _SelectableAnimatedBuilderState createState() => _SelectableAnimatedBuilderState(); } /// State that manages the [AnimationController] that is passed to /// [_SelectableAnimatedBuilder.builder]. class _SelectableAnimatedBuilderState extends State<_SelectableAnimatedBuilder> with SingleTickerProviderStateMixin { late AnimationController _controller; @override void initState() { super.initState(); _controller = AnimationController(vsync: this); _controller.duration = widget.duration; _controller.value = widget.isSelected ? 1.0 : 0.0; } @override void didUpdateWidget(_SelectableAnimatedBuilder oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.duration != widget.duration) { _controller.duration = widget.duration; } if (oldWidget.isSelected != widget.isSelected) { if (widget.isSelected) { _controller.forward(); } else { _controller.reverse(); } } } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return widget.builder( context, _controller, ); } } /// Returns `true` if this animation is ticking forward, or has completed, /// based on [status]. bool _isForwardOrCompleted(Animation<double> animation) { return animation.status == AnimationStatus.forward || animation.status == AnimationStatus.completed; } // BEGIN GENERATED TOKEN PROPERTIES - NavigationDrawer // Do not edit by hand. The code between the "BEGIN GENERATED" and // "END GENERATED" comments are generated from data in the Material // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. class _NavigationDrawerDefaultsM3 extends NavigationDrawerThemeData { _NavigationDrawerDefaultsM3(this.context) : super( elevation: 1.0, tileHeight: 56.0, indicatorShape: const StadiumBorder(), indicatorSize: const Size(336.0, 56.0), ); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; late final TextTheme _textTheme = Theme.of(context).textTheme; @override Color? get backgroundColor => _colors.surfaceContainerLow; @override Color? get surfaceTintColor => Colors.transparent; @override Color? get shadowColor => Colors.transparent; @override Color? get indicatorColor => _colors.secondaryContainer; @override MaterialStateProperty<IconThemeData?>? get iconTheme { return MaterialStateProperty.resolveWith((Set<MaterialState> states) { return IconThemeData( size: 24.0, color: states.contains(MaterialState.disabled) ? _colors.onSurfaceVariant.withOpacity(0.38) : states.contains(MaterialState.selected) ? _colors.onSecondaryContainer : _colors.onSurfaceVariant, ); }); } @override MaterialStateProperty<TextStyle?>? get labelTextStyle { return MaterialStateProperty.resolveWith((Set<MaterialState> states) { final TextStyle style = _textTheme.labelLarge!; return style.apply( color: states.contains(MaterialState.disabled) ? _colors.onSurfaceVariant.withOpacity(0.38) : states.contains(MaterialState.selected) ? _colors.onSecondaryContainer : _colors.onSurfaceVariant, ); }); } } // END GENERATED TOKEN PROPERTIES - NavigationDrawer
flutter/packages/flutter/lib/src/material/navigation_drawer.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/navigation_drawer.dart", "repo_id": "flutter", "token_count": 8785 }
633
// 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:ui' show lerpDouble; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'material_state.dart'; import 'theme.dart'; import 'theme_data.dart'; // Examples can assume: // late BuildContext context; /// Defines default property values for descendant [Radio] widgets. /// /// Descendant widgets obtain the current [RadioThemeData] object using /// `RadioTheme.of(context)`. Instances of [RadioThemeData] can be customized /// with [RadioThemeData.copyWith]. /// /// Typically a [RadioThemeData] is specified as part of the overall [Theme] /// with [ThemeData.radioTheme]. /// /// All [RadioThemeData] properties are `null` by default. When null, the /// [Radio] will use the values from [ThemeData] if they exist, otherwise it /// will provide its own defaults based on the overall [Theme]'s colorScheme. /// See the individual [Radio] properties for details. /// /// See also: /// /// * [ThemeData], which describes the overall theme information for the /// application. /// * [RadioTheme], which is used by descendants to obtain the /// [RadioThemeData]. @immutable class RadioThemeData with Diagnosticable { /// Creates a theme that can be used for [ThemeData.radioTheme]. const RadioThemeData({ this.mouseCursor, this.fillColor, this.overlayColor, this.splashRadius, this.materialTapTargetSize, this.visualDensity, }); /// {@macro flutter.material.radio.mouseCursor} /// /// If specified, overrides the default value of [Radio.mouseCursor]. The /// default value is [MaterialStateMouseCursor.clickable]. final MaterialStateProperty<MouseCursor?>? mouseCursor; /// {@macro flutter.material.radio.fillColor} /// /// If specified, overrides the default value of [Radio.fillColor]. final MaterialStateProperty<Color?>? fillColor; /// {@macro flutter.material.radio.overlayColor} /// /// If specified, overrides the default value of [Radio.overlayColor]. final MaterialStateProperty<Color?>? overlayColor; /// {@macro flutter.material.radio.splashRadius} /// /// If specified, overrides the default value of [Radio.splashRadius]. The /// default value is [kRadialReactionRadius]. final double? splashRadius; /// {@macro flutter.material.radio.materialTapTargetSize} /// /// If specified, overrides the default value of /// [Radio.materialTapTargetSize]. The default value is the value of /// [ThemeData.materialTapTargetSize]. final MaterialTapTargetSize? materialTapTargetSize; /// {@macro flutter.material.radio.visualDensity} /// /// If specified, overrides the default value of [Radio.visualDensity]. The /// default value is the value of [ThemeData.visualDensity]. final VisualDensity? visualDensity; /// Creates a copy of this object but with the given fields replaced with the /// new values. RadioThemeData copyWith({ MaterialStateProperty<MouseCursor?>? mouseCursor, MaterialStateProperty<Color?>? fillColor, MaterialStateProperty<Color?>? overlayColor, double? splashRadius, MaterialTapTargetSize? materialTapTargetSize, VisualDensity? visualDensity, }) { return RadioThemeData( mouseCursor: mouseCursor ?? this.mouseCursor, fillColor: fillColor ?? this.fillColor, overlayColor: overlayColor ?? this.overlayColor, splashRadius: splashRadius ?? this.splashRadius, materialTapTargetSize: materialTapTargetSize ?? this.materialTapTargetSize, visualDensity: visualDensity ?? this.visualDensity, ); } /// Linearly interpolate between two [RadioThemeData]s. /// /// {@macro dart.ui.shadow.lerp} static RadioThemeData lerp(RadioThemeData? a, RadioThemeData? b, double t) { if (identical(a, b) && a != null) { return a; } return RadioThemeData( mouseCursor: t < 0.5 ? a?.mouseCursor : b?.mouseCursor, fillColor: MaterialStateProperty.lerp<Color?>(a?.fillColor, b?.fillColor, t, Color.lerp), materialTapTargetSize: t < 0.5 ? a?.materialTapTargetSize : b?.materialTapTargetSize, overlayColor: MaterialStateProperty.lerp<Color?>(a?.overlayColor, b?.overlayColor, t, Color.lerp), splashRadius: lerpDouble(a?.splashRadius, b?.splashRadius, t), visualDensity: t < 0.5 ? a?.visualDensity : b?.visualDensity, ); } @override int get hashCode => Object.hash( mouseCursor, fillColor, overlayColor, splashRadius, materialTapTargetSize, visualDensity, ); @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is RadioThemeData && other.mouseCursor == mouseCursor && other.fillColor == fillColor && other.overlayColor == overlayColor && other.splashRadius == splashRadius && other.materialTapTargetSize == materialTapTargetSize && other.visualDensity == visualDensity; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<MaterialStateProperty<MouseCursor?>>('mouseCursor', mouseCursor, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<Color?>>('fillColor', fillColor, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialStateProperty<Color?>>('overlayColor', overlayColor, defaultValue: null)); properties.add(DoubleProperty('splashRadius', splashRadius, defaultValue: null)); properties.add(DiagnosticsProperty<MaterialTapTargetSize>('materialTapTargetSize', materialTapTargetSize, defaultValue: null)); properties.add(DiagnosticsProperty<VisualDensity>('visualDensity', visualDensity, defaultValue: null)); } } /// Applies a radio theme to descendant [Radio] widgets. /// /// Descendant widgets obtain the current theme's [RadioTheme] object using /// [RadioTheme.of]. When a widget uses [RadioTheme.of], it is automatically /// rebuilt if the theme later changes. /// /// A radio theme can be specified as part of the overall Material theme using /// [ThemeData.radioTheme]. /// /// See also: /// /// * [RadioThemeData], which describes the actual configuration of a radio /// theme. class RadioTheme extends InheritedWidget { /// Constructs a radio theme that configures all descendant [Radio] widgets. const RadioTheme({ super.key, required this.data, required super.child, }); /// The properties used for all descendant [Radio] widgets. final RadioThemeData data; /// Returns the configuration [data] from the closest [RadioTheme] ancestor. /// If there is no ancestor, it returns [ThemeData.radioTheme]. /// /// Typical usage is as follows: /// /// ```dart /// RadioThemeData theme = RadioTheme.of(context); /// ``` static RadioThemeData of(BuildContext context) { final RadioTheme? radioTheme = context.dependOnInheritedWidgetOfExactType<RadioTheme>(); return radioTheme?.data ?? Theme.of(context).radioTheme; } @override bool updateShouldNotify(RadioTheme oldWidget) => data != oldWidget.data; }
flutter/packages/flutter/lib/src/material/radio_theme.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/radio_theme.dart", "repo_id": "flutter", "token_count": 2294 }
634
// 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 'package:flutter/painting.dart'; // Based on https://material.io/design/environment/elevation.html // Currently, only the elevation values that are bound to one or more widgets are // defined here. /// Map of elevation offsets used by Material Design to [BoxShadow] definitions. /// /// The following elevations have defined shadows: 1, 2, 3, 4, 6, 8, 9, 12, 16, 24. /// /// Each entry has three shadows which must be combined to obtain the defined /// effect for that elevation. /// /// This is useful when simulating a shadow with a [BoxDecoration] or other /// class that uses a list of [BoxShadow] objects. /// /// See also: /// /// * [Material], which takes an arbitrary double for its elevation and generates /// a shadow dynamically. /// * <https://material.io/design/environment/elevation.html> const Map<int, List<BoxShadow>> kElevationToShadow = _elevationToShadow; // to hide the literal from the docs const Color _kKeyUmbraOpacity = Color(0x33000000); // alpha = 0.2 const Color _kKeyPenumbraOpacity = Color(0x24000000); // alpha = 0.14 const Color _kAmbientShadowOpacity = Color(0x1F000000); // alpha = 0.12 const Map<int, List<BoxShadow>> _elevationToShadow = <int, List<BoxShadow>>{ // The empty list depicts no elevation. 0: <BoxShadow>[], 1: <BoxShadow>[ BoxShadow(offset: Offset(0.0, 2.0), blurRadius: 1.0, spreadRadius: -1.0, color: _kKeyUmbraOpacity), BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 1.0, color: _kKeyPenumbraOpacity), BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 3.0, color: _kAmbientShadowOpacity), ], 2: <BoxShadow>[ BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 1.0, spreadRadius: -2.0, color: _kKeyUmbraOpacity), BoxShadow(offset: Offset(0.0, 2.0), blurRadius: 2.0, color: _kKeyPenumbraOpacity), BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 5.0, color: _kAmbientShadowOpacity), ], 3: <BoxShadow>[ BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 3.0, spreadRadius: -2.0, color: _kKeyUmbraOpacity), BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 4.0, color: _kKeyPenumbraOpacity), BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 8.0, color: _kAmbientShadowOpacity), ], 4: <BoxShadow>[ BoxShadow(offset: Offset(0.0, 2.0), blurRadius: 4.0, spreadRadius: -1.0, color: _kKeyUmbraOpacity), BoxShadow(offset: Offset(0.0, 4.0), blurRadius: 5.0, color: _kKeyPenumbraOpacity), BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 10.0, color: _kAmbientShadowOpacity), ], 6: <BoxShadow>[ BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 5.0, spreadRadius: -1.0, color: _kKeyUmbraOpacity), BoxShadow(offset: Offset(0.0, 6.0), blurRadius: 10.0, color: _kKeyPenumbraOpacity), BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 18.0, color: _kAmbientShadowOpacity), ], 8: <BoxShadow>[ BoxShadow(offset: Offset(0.0, 5.0), blurRadius: 5.0, spreadRadius: -3.0, color: _kKeyUmbraOpacity), BoxShadow(offset: Offset(0.0, 8.0), blurRadius: 10.0, spreadRadius: 1.0, color: _kKeyPenumbraOpacity), BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 14.0, spreadRadius: 2.0, color: _kAmbientShadowOpacity), ], 9: <BoxShadow>[ BoxShadow(offset: Offset(0.0, 5.0), blurRadius: 6.0, spreadRadius: -3.0, color: _kKeyUmbraOpacity), BoxShadow(offset: Offset(0.0, 9.0), blurRadius: 12.0, spreadRadius: 1.0, color: _kKeyPenumbraOpacity), BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 16.0, spreadRadius: 2.0, color: _kAmbientShadowOpacity), ], 12: <BoxShadow>[ BoxShadow(offset: Offset(0.0, 7.0), blurRadius: 8.0, spreadRadius: -4.0, color: _kKeyUmbraOpacity), BoxShadow(offset: Offset(0.0, 12.0), blurRadius: 17.0, spreadRadius: 2.0, color: _kKeyPenumbraOpacity), BoxShadow(offset: Offset(0.0, 5.0), blurRadius: 22.0, spreadRadius: 4.0, color: _kAmbientShadowOpacity), ], 16: <BoxShadow>[ BoxShadow(offset: Offset(0.0, 8.0), blurRadius: 10.0, spreadRadius: -5.0, color: _kKeyUmbraOpacity), BoxShadow(offset: Offset(0.0, 16.0), blurRadius: 24.0, spreadRadius: 2.0, color: _kKeyPenumbraOpacity), BoxShadow(offset: Offset(0.0, 6.0), blurRadius: 30.0, spreadRadius: 5.0, color: _kAmbientShadowOpacity), ], 24: <BoxShadow>[ BoxShadow(offset: Offset(0.0, 11.0), blurRadius: 15.0, spreadRadius: -7.0, color: _kKeyUmbraOpacity), BoxShadow(offset: Offset(0.0, 24.0), blurRadius: 38.0, spreadRadius: 3.0, color: _kKeyPenumbraOpacity), BoxShadow(offset: Offset(0.0, 9.0), blurRadius: 46.0, spreadRadius: 8.0, color: _kAmbientShadowOpacity), ], };
flutter/packages/flutter/lib/src/material/shadows.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/shadows.dart", "repo_id": "flutter", "token_count": 1860 }
635
// 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 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'button_style.dart'; import 'theme.dart'; // Examples can assume: // late BuildContext context; /// A [ButtonStyle] that overrides the default appearance of /// [TextButton]s when it's used with [TextButtonTheme] or with the /// overall [Theme]'s [ThemeData.textButtonTheme]. /// /// The [style]'s properties override [TextButton]'s default style, /// i.e. the [ButtonStyle] returned by [TextButton.defaultStyleOf]. Only /// the style's non-null property values or resolved non-null /// [MaterialStateProperty] values are used. /// /// See also: /// /// * [TextButtonTheme], the theme which is configured with this class. /// * [TextButton.defaultStyleOf], which returns the default [ButtonStyle] /// for text buttons. /// * [TextButton.styleFrom], which converts simple values into a /// [ButtonStyle] that's consistent with [TextButton]'s defaults. /// * [MaterialStateProperty.resolve], "resolve" a material state property /// to a simple value based on a set of [MaterialState]s. /// * [ThemeData.textButtonTheme], which can be used to override the default /// [ButtonStyle] for [TextButton]s below the overall [Theme]. @immutable class TextButtonThemeData with Diagnosticable { /// Creates a [TextButtonThemeData]. /// /// The [style] may be null. const TextButtonThemeData({ this.style }); /// Overrides for [TextButton]'s default style. /// /// Non-null properties or non-null resolved [MaterialStateProperty] /// values override the [ButtonStyle] returned by /// [TextButton.defaultStyleOf]. /// /// If [style] is null, then this theme doesn't override anything. final ButtonStyle? style; /// Linearly interpolate between two text button themes. static TextButtonThemeData? lerp(TextButtonThemeData? a, TextButtonThemeData? b, double t) { if (identical(a, b)) { return a; } return TextButtonThemeData( style: ButtonStyle.lerp(a?.style, b?.style, t), ); } @override int get hashCode => style.hashCode; @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is TextButtonThemeData && other.style == style; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<ButtonStyle>('style', style, defaultValue: null)); } } /// Overrides the default [ButtonStyle] of its [TextButton] descendants. /// /// See also: /// /// * [TextButtonThemeData], which is used to configure this theme. /// * [TextButton.defaultStyleOf], which returns the default [ButtonStyle] /// for text buttons. /// * [TextButton.styleFrom], which converts simple values into a /// [ButtonStyle] that's consistent with [TextButton]'s defaults. /// * [ThemeData.textButtonTheme], which can be used to override the default /// [ButtonStyle] for [TextButton]s below the overall [Theme]. class TextButtonTheme extends InheritedTheme { /// Create a [TextButtonTheme]. const TextButtonTheme({ super.key, required this.data, required super.child, }); /// The configuration of this theme. final TextButtonThemeData data; /// The closest instance of this class that encloses the given context. /// /// If there is no enclosing [TextButtonTheme] widget, then /// [ThemeData.textButtonTheme] is used. /// /// Typical usage is as follows: /// /// ```dart /// TextButtonThemeData theme = TextButtonTheme.of(context); /// ``` static TextButtonThemeData of(BuildContext context) { final TextButtonTheme? buttonTheme = context.dependOnInheritedWidgetOfExactType<TextButtonTheme>(); return buttonTheme?.data ?? Theme.of(context).textButtonTheme; } @override Widget wrap(BuildContext context, Widget child) { return TextButtonTheme(data: data, child: child); } @override bool updateShouldNotify(TextButtonTheme oldWidget) => data != oldWidget.data; }
flutter/packages/flutter/lib/src/material/text_button_theme.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/text_button_theme.dart", "repo_id": "flutter", "token_count": 1283 }
636
// 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 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; import 'feedback.dart'; import 'text_theme.dart'; import 'theme.dart'; import 'tooltip_theme.dart'; import 'tooltip_visibility.dart'; /// Signature for when a tooltip is triggered. typedef TooltipTriggeredCallback = void Function(); /// A special [MouseRegion] that when nested, only the first [_ExclusiveMouseRegion] /// to be hit in hit-testing order will be added to the BoxHitTestResult (i.e., /// child over parent, last sibling over first sibling). /// /// The [onEnter] method will be called when a mouse pointer enters this /// [MouseRegion], and there is no other [_ExclusiveMouseRegion]s obstructing /// this [_ExclusiveMouseRegion] from receiving the events. This includes the /// case where the mouse cursor stays within the paint bounds of an outer /// [_ExclusiveMouseRegion], but moves outside of the bounds of the inner /// [_ExclusiveMouseRegion] that was initially blocking the outer widget. /// /// Likewise, [onExit] is called when the a mouse pointer moves out of the paint /// bounds of this widget, or moves into another [_ExclusiveMouseRegion] that /// overlaps this widget in hit-testing order. /// /// This widget doesn't affect [MouseRegion]s that aren't [_ExclusiveMouseRegion]s, /// or other [HitTestTarget]s in the tree. class _ExclusiveMouseRegion extends MouseRegion { const _ExclusiveMouseRegion({ super.onEnter, super.onExit, super.child, }); @override _RenderExclusiveMouseRegion createRenderObject(BuildContext context) { return _RenderExclusiveMouseRegion( onEnter: onEnter, onExit: onExit, ); } } class _RenderExclusiveMouseRegion extends RenderMouseRegion { _RenderExclusiveMouseRegion({ super.onEnter, super.onExit, }); static bool isOutermostMouseRegion = true; static bool foundInnermostMouseRegion = false; @override bool hitTest(BoxHitTestResult result, {required Offset position}) { bool isHit = false; final bool outermost = isOutermostMouseRegion; isOutermostMouseRegion = false; if (size.contains(position)) { isHit = hitTestChildren(result, position: position) || hitTestSelf(position); if ((isHit || behavior == HitTestBehavior.translucent) && !foundInnermostMouseRegion) { foundInnermostMouseRegion = true; result.add(BoxHitTestEntry(this, position)); } } if (outermost) { // The outermost region resets the global states. isOutermostMouseRegion = true; foundInnermostMouseRegion = false; } return isHit; } } /// A Material Design tooltip. /// /// Tooltips provide text labels which help explain the function of a button or /// other user interface action. Wrap the button in a [Tooltip] widget and provide /// a message which will be shown when the widget is long pressed. /// /// Many widgets, such as [IconButton], [FloatingActionButton], and /// [PopupMenuButton] have a `tooltip` property that, when non-null, causes the /// widget to include a [Tooltip] in its build. /// /// Tooltips improve the accessibility of visual widgets by proving a textual /// representation of the widget, which, for example, can be vocalized by a /// screen reader. /// /// {@youtube 560 315 https://www.youtube.com/watch?v=EeEfD5fI-5Q} /// /// {@tool dartpad} /// This example show a basic [Tooltip] which has a [Text] as child. /// [message] contains your label to be shown by the tooltip when /// the child that Tooltip wraps is hovered over on web or desktop. On mobile, /// the tooltip is shown when the widget is long pressed. /// /// This tooltip will default to showing above the [Text] instead of below /// because its ambient [TooltipThemeData.preferBelow] is false. /// (See the use of [MaterialApp.theme].) /// Setting that piece of theme data is recommended to avoid having a finger or /// cursor hide the tooltip. For other ways to set that piece of theme data see: /// /// * [Theme.data], [ThemeData.tooltipTheme] /// * [TooltipTheme.data] /// /// or it can be set directly on each tooltip with [Tooltip.preferBelow]. /// /// ** See code in examples/api/lib/material/tooltip/tooltip.0.dart ** /// {@end-tool} /// /// {@tool dartpad} /// This example covers most of the attributes available in Tooltip. /// `decoration` has been used to give a gradient and borderRadius to Tooltip. /// `height` has been used to set a specific height of the Tooltip. /// `preferBelow` is true; the tooltip will prefer showing below [Tooltip]'s child widget. /// However, it may show the tooltip above if there's not enough space /// below the widget. /// `textStyle` has been used to set the font size of the 'message'. /// `showDuration` accepts a Duration to continue showing the message after the long /// press has been released or the mouse pointer exits the child widget. /// `waitDuration` accepts a Duration for which a mouse pointer has to hover over the child /// widget before the tooltip is shown. /// /// ** See code in examples/api/lib/material/tooltip/tooltip.1.dart ** /// {@end-tool} /// /// {@tool dartpad} /// This example shows a rich [Tooltip] that specifies the [richMessage] /// parameter instead of the [message] parameter (only one of these may be /// non-null. Any [InlineSpan] can be specified for the [richMessage] attribute, /// including [WidgetSpan]. /// /// ** See code in examples/api/lib/material/tooltip/tooltip.2.dart ** /// {@end-tool} /// /// {@tool dartpad} /// This example shows how [Tooltip] can be shown manually with [TooltipTriggerMode.manual] /// by calling the [TooltipState.ensureTooltipVisible] function. /// /// ** See code in examples/api/lib/material/tooltip/tooltip.3.dart ** /// {@end-tool} /// /// See also: /// /// * <https://material.io/design/components/tooltips.html> /// * [TooltipTheme] or [ThemeData.tooltipTheme] /// * [TooltipVisibility] class Tooltip extends StatefulWidget { /// Creates a tooltip. /// /// By default, tooltips should adhere to the /// [Material specification](https://material.io/design/components/tooltips.html#spec). /// If the optional constructor parameters are not defined, the values /// provided by [TooltipTheme.of] will be used if a [TooltipTheme] is present /// or specified in [ThemeData]. /// /// All parameters that are defined in the constructor will /// override the default values _and_ the values in [TooltipTheme.of]. /// /// Only one of [message] and [richMessage] may be non-null. const Tooltip({ super.key, this.message, this.richMessage, this.height, this.padding, this.margin, this.verticalOffset, this.preferBelow, this.excludeFromSemantics, this.decoration, this.textStyle, this.textAlign, this.waitDuration, this.showDuration, this.exitDuration, this.enableTapToDismiss = true, this.triggerMode, this.enableFeedback, this.onTriggered, this.child, }) : assert((message == null) != (richMessage == null), 'Either `message` or `richMessage` must be specified'), assert( richMessage == null || textStyle == null, 'If `richMessage` is specified, `textStyle` will have no effect. ' 'If you wish to provide a `textStyle` for a rich tooltip, add the ' '`textStyle` directly to the `richMessage` InlineSpan.', ); /// The text to display in the tooltip. /// /// Only one of [message] and [richMessage] may be non-null. final String? message; /// The rich text to display in the tooltip. /// /// Only one of [message] and [richMessage] may be non-null. final InlineSpan? richMessage; /// The height of the tooltip's [child]. /// /// If the [child] is null, then this is the tooltip's intrinsic height. final double? height; /// The amount of space by which to inset the tooltip's [child]. /// /// On mobile, defaults to 16.0 logical pixels horizontally and 4.0 vertically. /// On desktop, defaults to 8.0 logical pixels horizontally and 4.0 vertically. final EdgeInsetsGeometry? padding; /// The empty space that surrounds the tooltip. /// /// Defines the tooltip's outer [Container.margin]. By default, a /// long tooltip will span the width of its window. If long enough, /// a tooltip might also span the window's height. This property allows /// one to define how much space the tooltip must be inset from the edges /// of their display window. /// /// If this property is null, then [TooltipThemeData.margin] is used. /// If [TooltipThemeData.margin] is also null, the default margin is /// 0.0 logical pixels on all sides. final EdgeInsetsGeometry? margin; /// The vertical gap between the widget and the displayed tooltip. /// /// When [preferBelow] is set to true and tooltips have sufficient space to /// display themselves, this property defines how much vertical space /// tooltips will position themselves under their corresponding widgets. /// Otherwise, tooltips will position themselves above their corresponding /// widgets with the given offset. final double? verticalOffset; /// Whether the tooltip defaults to being displayed below the widget. /// /// If there is insufficient space to display the tooltip in /// the preferred direction, the tooltip will be displayed in the opposite /// direction. /// /// If this property is null, then [TooltipThemeData.preferBelow] is used. /// If that is also null, the default value is true. /// /// Applying [TooltipThemeData.preferBelow]: `false` for the entire app /// is recommended to avoid having a finger or cursor hide a tooltip. final bool? preferBelow; /// Whether the tooltip's [message] or [richMessage] should be excluded from /// the semantics tree. /// /// Defaults to false. A tooltip will add a [Semantics] label that is set to /// [Tooltip.message] if non-null, or the plain text value of /// [Tooltip.richMessage] otherwise. Set this property to true if the app is /// going to provide its own custom semantics label. final bool? excludeFromSemantics; /// The widget below this widget in the tree. /// /// {@macro flutter.widgets.ProxyWidget.child} final Widget? child; /// Specifies the tooltip's shape and background color. /// /// The tooltip shape defaults to a rounded rectangle with a border radius of /// 4.0. Tooltips will also default to an opacity of 90% and with the color /// [Colors.grey]\[700\] if [ThemeData.brightness] is [Brightness.dark], and /// [Colors.white] if it is [Brightness.light]. final Decoration? decoration; /// The style to use for the message of the tooltip. /// /// If null, the message's [TextStyle] will be determined based on /// [ThemeData]. If [ThemeData.brightness] is set to [Brightness.dark], /// [TextTheme.bodyMedium] of [ThemeData.textTheme] will be used with /// [Colors.white]. Otherwise, if [ThemeData.brightness] is set to /// [Brightness.light], [TextTheme.bodyMedium] of [ThemeData.textTheme] will be /// used with [Colors.black]. final TextStyle? textStyle; /// How the message of the tooltip is aligned horizontally. /// /// If this property is null, then [TooltipThemeData.textAlign] is used. /// If [TooltipThemeData.textAlign] is also null, the default value is /// [TextAlign.start]. final TextAlign? textAlign; /// The length of time that a pointer must hover over a tooltip's widget /// before the tooltip will be shown. /// /// Defaults to 0 milliseconds (tooltips are shown immediately upon hover). final Duration? waitDuration; /// The length of time that the tooltip will be shown after a long press is /// released (if triggerMode is [TooltipTriggerMode.longPress]) or a tap is /// released (if triggerMode is [TooltipTriggerMode.tap]). This property /// does not affect mouse pointer devices. /// /// Defaults to 1.5 seconds for long press and tap released /// /// See also: /// /// * [exitDuration], which allows configuring the time until a pointer /// disappears when hovering. final Duration? showDuration; /// The length of time that a pointer must have stopped hovering over a /// tooltip's widget before the tooltip will be hidden. /// /// Defaults to 100 milliseconds. /// /// See also: /// /// * [showDuration], which allows configuring the length of time that a /// tooltip will be visible after touch events are released. final Duration? exitDuration; /// Whether the tooltip can be dismissed by tap. /// /// The default value is true. final bool enableTapToDismiss; /// The [TooltipTriggerMode] that will show the tooltip. /// /// If this property is null, then [TooltipThemeData.triggerMode] is used. /// If [TooltipThemeData.triggerMode] is also null, the default mode is /// [TooltipTriggerMode.longPress]. /// /// This property does not affect mouse devices. Setting [triggerMode] to /// [TooltipTriggerMode.manual] will not prevent the tooltip from showing when /// the mouse cursor hovers over it. final TooltipTriggerMode? triggerMode; /// Whether the tooltip should provide acoustic and/or haptic feedback. /// /// For example, on Android a tap will produce a clicking sound and a /// long-press will produce a short vibration, when feedback is enabled. /// /// When null, the default value is true. /// /// See also: /// /// * [Feedback], for providing platform-specific feedback to certain actions. final bool? enableFeedback; /// Called when the Tooltip is triggered. /// /// The tooltip is triggered after a tap when [triggerMode] is [TooltipTriggerMode.tap] /// or after a long press when [triggerMode] is [TooltipTriggerMode.longPress]. final TooltipTriggeredCallback? onTriggered; static final List<TooltipState> _openedTooltips = <TooltipState>[]; /// Dismiss all of the tooltips that are currently shown on the screen, /// including those with mouse cursors currently hovering over them. /// /// This method returns true if it successfully dismisses the tooltips. It /// returns false if there is no tooltip shown on the screen. static bool dismissAllToolTips() { if (_openedTooltips.isNotEmpty) { // Avoid concurrent modification. final List<TooltipState> openedTooltips = _openedTooltips.toList(); for (final TooltipState state in openedTooltips) { assert(state.mounted); state._scheduleDismissTooltip(withDelay: Duration.zero); } return true; } return false; } @override State<Tooltip> createState() => TooltipState(); @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(StringProperty( 'message', message, showName: message == null, defaultValue: message == null ? null : kNoDefaultValue, )); properties.add(StringProperty( 'richMessage', richMessage?.toPlainText(), showName: richMessage == null, defaultValue: richMessage == null ? null : kNoDefaultValue, )); properties.add(DoubleProperty('height', height, defaultValue: null)); properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding, defaultValue: null)); properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('margin', margin, defaultValue: null)); properties.add(DoubleProperty('vertical offset', verticalOffset, defaultValue: null)); properties.add(FlagProperty('position', value: preferBelow, ifTrue: 'below', ifFalse: 'above', showName: true)); properties.add(FlagProperty('semantics', value: excludeFromSemantics, ifTrue: 'excluded', showName: true)); properties.add(DiagnosticsProperty<Duration>('wait duration', waitDuration, defaultValue: null)); properties.add(DiagnosticsProperty<Duration>('show duration', showDuration, defaultValue: null)); properties.add(DiagnosticsProperty<Duration>('exit duration', exitDuration, defaultValue: null)); properties.add(DiagnosticsProperty<TooltipTriggerMode>('triggerMode', triggerMode, defaultValue: null)); properties.add(FlagProperty('enableFeedback', value: enableFeedback, ifTrue: 'true', showName: true)); properties.add(DiagnosticsProperty<TextAlign>('textAlign', textAlign, defaultValue: null)); } } /// Contains the state for a [Tooltip]. /// /// This class can be used to programmatically show the Tooltip, see the /// [ensureTooltipVisible] method. class TooltipState extends State<Tooltip> with SingleTickerProviderStateMixin { static const double _defaultVerticalOffset = 24.0; static const bool _defaultPreferBelow = true; static const EdgeInsetsGeometry _defaultMargin = EdgeInsets.zero; static const Duration _fadeInDuration = Duration(milliseconds: 150); static const Duration _fadeOutDuration = Duration(milliseconds: 75); static const Duration _defaultShowDuration = Duration(milliseconds: 1500); static const Duration _defaultHoverExitDuration = Duration(milliseconds: 100); static const Duration _defaultWaitDuration = Duration.zero; static const bool _defaultExcludeFromSemantics = false; static const TooltipTriggerMode _defaultTriggerMode = TooltipTriggerMode.longPress; static const bool _defaultEnableFeedback = true; static const TextAlign _defaultTextAlign = TextAlign.start; final OverlayPortalController _overlayController = OverlayPortalController(); // From InheritedWidgets late bool _visible; late TooltipThemeData _tooltipTheme; Duration get _showDuration => widget.showDuration ?? _tooltipTheme.showDuration ?? _defaultShowDuration; Duration get _hoverExitDuration => widget.exitDuration ?? _tooltipTheme.exitDuration ?? _defaultHoverExitDuration; Duration get _waitDuration => widget.waitDuration ?? _tooltipTheme.waitDuration ?? _defaultWaitDuration; TooltipTriggerMode get _triggerMode => widget.triggerMode ?? _tooltipTheme.triggerMode ?? _defaultTriggerMode; bool get _enableFeedback => widget.enableFeedback ?? _tooltipTheme.enableFeedback ?? _defaultEnableFeedback; /// The plain text message for this tooltip. /// /// This value will either come from [widget.message] or [widget.richMessage]. String get _tooltipMessage => widget.message ?? widget.richMessage!.toPlainText(); Timer? _timer; AnimationController? _backingController; AnimationController get _controller { return _backingController ??= AnimationController( duration: _fadeInDuration, reverseDuration: _fadeOutDuration, vsync: this, )..addStatusListener(_handleStatusChanged); } LongPressGestureRecognizer? _longPressRecognizer; TapGestureRecognizer? _tapRecognizer; // The ids of mouse devices that are keeping the tooltip from being dismissed. // // Device ids are added to this set in _handleMouseEnter, and removed in // _handleMouseExit. The set is cleared in _handleTapToDismiss, typically when // a PointerDown event interacts with some other UI component. final Set<int> _activeHoveringPointerDevices = <int>{}; static bool _isTooltipVisible(AnimationStatus status) { return switch (status) { AnimationStatus.completed || AnimationStatus.forward || AnimationStatus.reverse => true, AnimationStatus.dismissed => false, }; } AnimationStatus _animationStatus = AnimationStatus.dismissed; void _handleStatusChanged(AnimationStatus status) { assert(mounted); switch ((_isTooltipVisible(_animationStatus), _isTooltipVisible(status))) { case (true, false): Tooltip._openedTooltips.remove(this); _overlayController.hide(); case (false, true): _overlayController.show(); Tooltip._openedTooltips.add(this); SemanticsService.tooltip(_tooltipMessage); case (true, true) || (false, false): break; } _animationStatus = status; } void _scheduleShowTooltip({ required Duration withDelay, Duration? showDuration }) { assert(mounted); void show() { assert(mounted); if (!_visible) { return; } _controller.forward(); _timer?.cancel(); _timer = showDuration == null ? null : Timer(showDuration, _controller.reverse); } assert( !(_timer?.isActive ?? false) || _controller.status != AnimationStatus.reverse, 'timer must not be active when the tooltip is fading out', ); switch (_controller.status) { case AnimationStatus.dismissed when withDelay.inMicroseconds > 0: _timer?.cancel(); _timer = Timer(withDelay, show); // If the tooltip is already fading in or fully visible, skip the // animation and show the tooltip immediately. case AnimationStatus.dismissed: case AnimationStatus.forward: case AnimationStatus.reverse: case AnimationStatus.completed: show(); } } void _scheduleDismissTooltip({ required Duration withDelay }) { assert(mounted); assert( !(_timer?.isActive ?? false) || _backingController?.status != AnimationStatus.reverse, 'timer must not be active when the tooltip is fading out', ); _timer?.cancel(); _timer = null; // Use _backingController instead of _controller to prevent the lazy getter // from instantiating an AnimationController unnecessarily. switch (_backingController?.status) { case null: case AnimationStatus.reverse: case AnimationStatus.dismissed: break; // Dismiss when the tooltip is fading in: if there's a dismiss delay we'll // allow the fade in animation to continue until the delay timer fires. case AnimationStatus.forward: case AnimationStatus.completed: if (withDelay.inMicroseconds > 0) { _timer = Timer(withDelay, _controller.reverse); } else { _controller.reverse(); } } } void _handlePointerDown(PointerDownEvent event) { assert(mounted); // PointerDeviceKinds that don't support hovering. const Set<PointerDeviceKind> triggerModeDeviceKinds = <PointerDeviceKind> { PointerDeviceKind.invertedStylus, PointerDeviceKind.stylus, PointerDeviceKind.touch, PointerDeviceKind.unknown, // MouseRegion only tracks PointerDeviceKind == mouse. PointerDeviceKind.trackpad, }; switch (_triggerMode) { case TooltipTriggerMode.longPress: final LongPressGestureRecognizer recognizer = _longPressRecognizer ??= LongPressGestureRecognizer( debugOwner: this, supportedDevices: triggerModeDeviceKinds, ); recognizer ..onLongPressCancel = _handleTapToDismiss ..onLongPress = _handleLongPress ..onLongPressUp = _handlePressUp ..addPointer(event); case TooltipTriggerMode.tap: final TapGestureRecognizer recognizer = _tapRecognizer ??= TapGestureRecognizer( debugOwner: this, supportedDevices: triggerModeDeviceKinds ); recognizer ..onTapCancel = _handleTapToDismiss ..onTap = _handleTap ..addPointer(event); case TooltipTriggerMode.manual: break; } } // For PointerDownEvents, this method will be called after _handlePointerDown. void _handleGlobalPointerEvent(PointerEvent event) { assert(mounted); if (_tapRecognizer?.primaryPointer == event.pointer || _longPressRecognizer?.primaryPointer == event.pointer) { // This is a pointer of interest specified by the trigger mode, since it's // picked up by the recognizer. // // The recognizer will later determine if this is indeed a "trigger" // gesture and dismiss the tooltip if that's not the case. However there's // still a chance that the PointerEvent was cancelled before the gesture // recognizer gets to emit a tap/longPress down, in which case the onCancel // callback (_handleTapToDismiss) will not be called. return; } if ((_timer == null && _controller.status == AnimationStatus.dismissed) || event is! PointerDownEvent) { return; } _handleTapToDismiss(); } // The primary pointer is not part of a "trigger" gesture so the tooltip // should be dismissed. void _handleTapToDismiss() { if (!widget.enableTapToDismiss) { return ; } _scheduleDismissTooltip(withDelay: Duration.zero); _activeHoveringPointerDevices.clear(); } void _handleTap() { if (!_visible) { return; } final bool tooltipCreated = _controller.status == AnimationStatus.dismissed; if (tooltipCreated && _enableFeedback) { assert(_triggerMode == TooltipTriggerMode.tap); Feedback.forTap(context); } widget.onTriggered?.call(); _scheduleShowTooltip( withDelay: Duration.zero, // _activeHoveringPointerDevices keep the tooltip visible. showDuration: _activeHoveringPointerDevices.isEmpty ? _showDuration : null, ); } // When a "trigger" gesture is recognized and the pointer down even is a part // of it. void _handleLongPress() { if (!_visible) { return; } final bool tooltipCreated = _visible && _controller.status == AnimationStatus.dismissed; if (tooltipCreated && _enableFeedback) { assert(_triggerMode == TooltipTriggerMode.longPress); Feedback.forLongPress(context); } widget.onTriggered?.call(); _scheduleShowTooltip(withDelay: Duration.zero); } void _handlePressUp() { if (_activeHoveringPointerDevices.isNotEmpty) { return; } _scheduleDismissTooltip(withDelay: _showDuration); } // # Current Hovering Behavior: // 1. Hovered tooltips don't show more than one at a time, for each mouse // device. For example, a chip with a delete icon typically shouldn't show // both the delete icon tooltip and the chip tooltip at the same time. // 2. Hovered tooltips are dismissed when: // i. [dismissAllToolTips] is called, even these tooltips are still hovered // ii. a unrecognized PointerDownEvent occurred within the application // (even these tooltips are still hovered), // iii. The last hovering device leaves the tooltip. void _handleMouseEnter(PointerEnterEvent event) { // _handleMouseEnter is only called when the mouse starts to hover over this // tooltip (including the actual tooltip it shows on the overlay), and this // tooltip is the first to be hit in the widget tree's hit testing order. // See also _ExclusiveMouseRegion for the exact behavior. _activeHoveringPointerDevices.add(event.device); // Dismiss other open tooltips unless they're kept visible by other mice. // The mouse tracker implementation always dispatches all `onExit` events // before dispatching any `onEnter` events, so `event.device` must have // already been removed from _activeHoveringPointerDevices of the tooltips // that are no longer being hovered over. final List<TooltipState> tooltipsToDismiss = Tooltip._openedTooltips .where((TooltipState tooltip) => tooltip._activeHoveringPointerDevices.isEmpty).toList(); for (final TooltipState tooltip in tooltipsToDismiss) { assert(tooltip.mounted); tooltip._scheduleDismissTooltip(withDelay: Duration.zero); } _scheduleShowTooltip(withDelay: tooltipsToDismiss.isNotEmpty ? Duration.zero : _waitDuration); } void _handleMouseExit(PointerExitEvent event) { if (_activeHoveringPointerDevices.isEmpty) { return; } _activeHoveringPointerDevices.remove(event.device); if (_activeHoveringPointerDevices.isEmpty) { _scheduleDismissTooltip(withDelay: _hoverExitDuration); } } /// Shows the tooltip if it is not already visible. /// /// After made visible by this method, The tooltip does not automatically /// dismiss after `waitDuration`, until the user dismisses/re-triggers it, or /// [Tooltip.dismissAllToolTips] is called. /// /// Returns `false` when the tooltip shouldn't be shown or when the tooltip /// was already visible. bool ensureTooltipVisible() { if (!_visible) { return false; } _timer?.cancel(); _timer = null; switch (_controller.status) { case AnimationStatus.dismissed: case AnimationStatus.reverse: _scheduleShowTooltip(withDelay: Duration.zero); return true; case AnimationStatus.forward: case AnimationStatus.completed: return false; } } @override void initState() { super.initState(); // Listen to global pointer events so that we can hide a tooltip immediately // if some other control is clicked on. Pointer events are dispatched to // global routes **after** other routes. GestureBinding.instance.pointerRouter.addGlobalRoute(_handleGlobalPointerEvent); } @override void didChangeDependencies() { super.didChangeDependencies(); _visible = TooltipVisibility.of(context); _tooltipTheme = TooltipTheme.of(context); } // https://material.io/components/tooltips#specs double _getDefaultTooltipHeight() { return switch (Theme.of(context).platform) { TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => 24.0, TargetPlatform.android || TargetPlatform.fuchsia || TargetPlatform.iOS => 32.0, }; } EdgeInsets _getDefaultPadding() { return switch (Theme.of(context).platform) { TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0), TargetPlatform.android || TargetPlatform.fuchsia || TargetPlatform.iOS => const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0), }; } static double _getDefaultFontSize(TargetPlatform platform) { return switch (platform) { TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => 12.0, TargetPlatform.android || TargetPlatform.fuchsia || TargetPlatform.iOS => 14.0, }; } Widget _buildTooltipOverlay(BuildContext context) { final OverlayState overlayState = Overlay.of(context, debugRequiredFor: widget); final RenderBox box = this.context.findRenderObject()! as RenderBox; final Offset target = box.localToGlobal( box.size.center(Offset.zero), ancestor: overlayState.context.findRenderObject(), ); final (TextStyle defaultTextStyle, BoxDecoration defaultDecoration) = switch (Theme.of(context)) { ThemeData(brightness: Brightness.dark, :final TextTheme textTheme, :final TargetPlatform platform) => ( textTheme.bodyMedium!.copyWith(color: Colors.black, fontSize: _getDefaultFontSize(platform)), BoxDecoration(color: Colors.white.withOpacity(0.9), borderRadius: const BorderRadius.all(Radius.circular(4))), ), ThemeData(brightness: Brightness.light, :final TextTheme textTheme, :final TargetPlatform platform) => ( textTheme.bodyMedium!.copyWith(color: Colors.white, fontSize: _getDefaultFontSize(platform)), BoxDecoration(color: Colors.grey[700]!.withOpacity(0.9), borderRadius: const BorderRadius.all(Radius.circular(4))), ), }; final TooltipThemeData tooltipTheme = _tooltipTheme; final _TooltipOverlay overlayChild = _TooltipOverlay( richMessage: widget.richMessage ?? TextSpan(text: widget.message), height: widget.height ?? tooltipTheme.height ?? _getDefaultTooltipHeight(), padding: widget.padding ?? tooltipTheme.padding ?? _getDefaultPadding(), margin: widget.margin ?? tooltipTheme.margin ?? _defaultMargin, onEnter: _handleMouseEnter, onExit: _handleMouseExit, decoration: widget.decoration ?? tooltipTheme.decoration ?? defaultDecoration, textStyle: widget.textStyle ?? tooltipTheme.textStyle ?? defaultTextStyle, textAlign: widget.textAlign ?? tooltipTheme.textAlign ?? _defaultTextAlign, animation: CurvedAnimation(parent: _controller, curve: Curves.fastOutSlowIn), target: target, verticalOffset: widget.verticalOffset ?? tooltipTheme.verticalOffset ?? _defaultVerticalOffset, preferBelow: widget.preferBelow ?? tooltipTheme.preferBelow ?? _defaultPreferBelow, ); return SelectionContainer.maybeOf(context) == null ? overlayChild : SelectionContainer.disabled(child: overlayChild); } @override void dispose() { GestureBinding.instance.pointerRouter.removeGlobalRoute(_handleGlobalPointerEvent); Tooltip._openedTooltips.remove(this); // _longPressRecognizer.dispose() and _tapRecognizer.dispose() may call // their registered onCancel callbacks if there's a gesture in progress. // Remove the onCancel callbacks to prevent the registered callbacks from // triggering unnecessary side effects (such as animations). _longPressRecognizer?.onLongPressCancel = null; _longPressRecognizer?.dispose(); _tapRecognizer?.onTapCancel = null; _tapRecognizer?.dispose(); _timer?.cancel(); _backingController?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { // If message is empty then no need to create a tooltip overlay to show // the empty black container so just return the wrapped child as is or // empty container if child is not specified. if (_tooltipMessage.isEmpty) { return widget.child ?? const SizedBox.shrink(); } assert(debugCheckHasOverlay(context)); final bool excludeFromSemantics = widget.excludeFromSemantics ?? _tooltipTheme.excludeFromSemantics ?? _defaultExcludeFromSemantics; Widget result = Semantics( tooltip: excludeFromSemantics ? null : _tooltipMessage, child: widget.child, ); // Only check for gestures if tooltip should be visible. if (_visible) { result = _ExclusiveMouseRegion( onEnter: _handleMouseEnter, onExit: _handleMouseExit, child: Listener( onPointerDown: _handlePointerDown, behavior: HitTestBehavior.opaque, child: result, ), ); } return OverlayPortal( controller: _overlayController, overlayChildBuilder: _buildTooltipOverlay, child: result, ); } } /// A delegate for computing the layout of a tooltip to be displayed above or /// below a target specified in the global coordinate system. class _TooltipPositionDelegate extends SingleChildLayoutDelegate { /// Creates a delegate for computing the layout of a tooltip. _TooltipPositionDelegate({ required this.target, required this.verticalOffset, required this.preferBelow, }); /// The offset of the target the tooltip is positioned near in the global /// coordinate system. final Offset target; /// The amount of vertical distance between the target and the displayed /// tooltip. final double verticalOffset; /// Whether the tooltip is displayed below its widget by default. /// /// If there is insufficient space to display the tooltip in the preferred /// direction, the tooltip will be displayed in the opposite direction. final bool preferBelow; @override BoxConstraints getConstraintsForChild(BoxConstraints constraints) => constraints.loosen(); @override Offset getPositionForChild(Size size, Size childSize) { return positionDependentBox( size: size, childSize: childSize, target: target, verticalOffset: verticalOffset, preferBelow: preferBelow, ); } @override bool shouldRelayout(_TooltipPositionDelegate oldDelegate) { return target != oldDelegate.target || verticalOffset != oldDelegate.verticalOffset || preferBelow != oldDelegate.preferBelow; } } class _TooltipOverlay extends StatelessWidget { const _TooltipOverlay({ required this.height, required this.richMessage, this.padding, this.margin, this.decoration, this.textStyle, this.textAlign, required this.animation, required this.target, required this.verticalOffset, required this.preferBelow, this.onEnter, this.onExit, }); final InlineSpan richMessage; final double height; final EdgeInsetsGeometry? padding; final EdgeInsetsGeometry? margin; final Decoration? decoration; final TextStyle? textStyle; final TextAlign? textAlign; final Animation<double> animation; final Offset target; final double verticalOffset; final bool preferBelow; final PointerEnterEventListener? onEnter; final PointerExitEventListener? onExit; @override Widget build(BuildContext context) { Widget result = FadeTransition( opacity: animation, child: ConstrainedBox( constraints: BoxConstraints(minHeight: height), child: DefaultTextStyle( style: Theme.of(context).textTheme.bodyMedium!, child: Semantics( container: true, child: Container( decoration: decoration, padding: padding, margin: margin, child: Center( widthFactor: 1.0, heightFactor: 1.0, child: Text.rich( richMessage, style: textStyle, textAlign: textAlign, ), ), ), ), ), ), ); if (onEnter != null || onExit != null) { result = _ExclusiveMouseRegion( onEnter: onEnter, onExit: onExit, child: result, ); } return Positioned.fill( bottom: MediaQuery.maybeViewInsetsOf(context)?.bottom ?? 0.0, child: CustomSingleChildLayout( delegate: _TooltipPositionDelegate( target: target, verticalOffset: verticalOffset, preferBelow: preferBelow, ), child: result, ), ); } }
flutter/packages/flutter/lib/src/material/tooltip.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/material/tooltip.dart", "repo_id": "flutter", "token_count": 12310 }
637
// 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 Shadow, lerpDouble; import 'package:flutter/foundation.dart'; import 'basic_types.dart'; import 'debug.dart'; /// A shadow cast by a box. /// /// [BoxShadow] can cast non-rectangular shadows if the box is non-rectangular /// (e.g., has a border radius or a circular shape). /// /// This class is similar to CSS box-shadow. /// /// See also: /// /// * [Canvas.drawShadow], which is a more efficient way to draw shadows. /// * [PhysicalModel], a widget for showing shadows. /// * [kElevationToShadow], for some predefined shadows used in Material /// Design. /// * [Shadow], which is the parent class that lacks [spreadRadius]. @immutable class BoxShadow extends ui.Shadow { /// Creates a box shadow. /// /// By default, the shadow is solid black with zero [offset], zero [blurRadius], /// zero [spreadRadius], and [BlurStyle.normal]. const BoxShadow({ super.color, super.offset, super.blurRadius, this.spreadRadius = 0.0, this.blurStyle = BlurStyle.normal, }); /// The amount the box should be inflated prior to applying the blur. final double spreadRadius; /// The [BlurStyle] to use for this shadow. /// /// Defaults to [BlurStyle.normal]. final BlurStyle blurStyle; /// Create the [Paint] object that corresponds to this shadow description. /// /// The [offset] and [spreadRadius] are not represented in the [Paint] object. /// To honor those as well, the shape should be inflated by [spreadRadius] pixels /// in every direction and then translated by [offset] before being filled using /// this [Paint]. @override Paint toPaint() { final Paint result = Paint() ..color = color ..maskFilter = MaskFilter.blur(blurStyle, blurSigma); assert(() { if (debugDisableShadows) { result.maskFilter = null; } return true; }()); return result; } /// Returns a new box shadow with its offset, blurRadius, and spreadRadius scaled by the given factor. @override BoxShadow scale(double factor) { return BoxShadow( color: color, offset: offset * factor, blurRadius: blurRadius * factor, spreadRadius: spreadRadius * factor, blurStyle: blurStyle, ); } /// Linearly interpolate between two box shadows. /// /// If either box shadow is null, this function linearly interpolates from /// a box shadow that matches the other box shadow in color but has a zero /// offset and a zero blurRadius. /// /// {@macro dart.ui.shadow.lerp} static BoxShadow? lerp(BoxShadow? a, BoxShadow? b, double t) { if (identical(a, b)) { return a; } if (a == null) { return b!.scale(t); } if (b == null) { return a.scale(1.0 - t); } return BoxShadow( color: Color.lerp(a.color, b.color, t)!, offset: Offset.lerp(a.offset, b.offset, t)!, blurRadius: ui.lerpDouble(a.blurRadius, b.blurRadius, t)!, spreadRadius: ui.lerpDouble(a.spreadRadius, b.spreadRadius, t)!, blurStyle: a.blurStyle == BlurStyle.normal ? b.blurStyle : a.blurStyle, ); } /// Linearly interpolate between two lists of box shadows. /// /// If the lists differ in length, excess items are lerped with null. /// /// {@macro dart.ui.shadow.lerp} static List<BoxShadow>? lerpList(List<BoxShadow>? a, List<BoxShadow>? b, double t) { if (identical(a, b)) { return a; } a ??= <BoxShadow>[]; b ??= <BoxShadow>[]; final int commonLength = math.min(a.length, b.length); return <BoxShadow>[ for (int i = 0; i < commonLength; i += 1) BoxShadow.lerp(a[i], b[i], t)!, for (int i = commonLength; i < a.length; i += 1) a[i].scale(1.0 - t), for (int i = commonLength; i < b.length; i += 1) b[i].scale(t), ]; } @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is BoxShadow && other.color == color && other.offset == offset && other.blurRadius == blurRadius && other.spreadRadius == spreadRadius && other.blurStyle == blurStyle; } @override int get hashCode => Object.hash(color, offset, blurRadius, spreadRadius, blurStyle); @override String toString() => 'BoxShadow($color, $offset, ${debugFormatDouble(blurRadius)}, ${debugFormatDouble(spreadRadius)}, $blurStyle)'; }
flutter/packages/flutter/lib/src/painting/box_shadow.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/painting/box_shadow.dart", "repo_id": "flutter", "token_count": 1685 }
638
// 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:collection'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'image_provider.dart'; /// A screen with a device-pixel ratio strictly less than this value is /// considered a low-resolution screen (typically entry-level to mid-range /// laptops, desktop screens up to QHD, low-end tablets such as Kindle Fire). const double _kLowDprLimit = 2.0; /// Fetches an image from an [AssetBundle], having determined the exact image to /// use based on the context. /// /// Given a main asset and a set of variants, AssetImage chooses the most /// appropriate asset for the current context, based on the device pixel ratio /// and size given in the configuration passed to [resolve]. /// /// To show a specific image from a bundle without any asset resolution, use an /// [AssetBundleImageProvider]. /// /// ## Naming assets for matching with different pixel densities /// /// Main assets are presumed to match a nominal pixel ratio of 1.0. To specify /// assets targeting different pixel ratios, place the variant assets in /// the application bundle under subdirectories named in the form "Nx", where /// N is the nominal device pixel ratio for that asset. /// /// For example, suppose an application wants to use an icon named /// "heart.png". This icon has representations at 1.0 (the main icon), as well /// as 2.0 and 4.0 pixel ratios (variants). The asset bundle should then /// contain the following assets: /// /// heart.png /// 2.0x/heart.png /// 4.0x/heart.png /// /// On a device with a 1.0 device pixel ratio, the image chosen would be /// heart.png; on a device with a 2.0 device pixel ratio, the image chosen /// would be 2.0x/heart.png; on a device with a 4.0 device pixel ratio, the /// image chosen would be 4.0x/heart.png. /// /// On a device with a device pixel ratio that does not exactly match an /// available asset the "best match" is chosen. Which asset is the best depends /// on the screen. Low-resolution screens (those with device pixel ratio /// strictly less than 2.0) use a different matching algorithm from the /// high-resolution screen. Because in low-resolution screens the physical /// pixels are visible to the user upscaling artifacts (e.g. blurred edges) are /// more pronounced. Therefore, a higher resolution asset is chosen, if /// available. For higher-resolution screens, where individual physical pixels /// are not visible to the user, the asset variant with the pixel ratio that's /// the closest to the screen's device pixel ratio is chosen. /// /// For example, for a screen with device pixel ratio 1.25 the image chosen /// would be 2.0x/heart.png, even though heart.png (i.e. 1.0) is closer. This /// is because the screen is considered low-resolution. For a screen with /// device pixel ratio of 2.25 the image chosen would also be 2.0x/heart.png. /// This is because the screen is considered to be a high-resolution screen, /// and therefore upscaling a 2.0x image to 2.25 won't result in visible /// upscaling artifacts. However, for a screen with device-pixel ratio 3.25 the /// image chosen would be 4.0x/heart.png because it's closer to 4.0 than it is /// to 2.0. /// /// Choosing a higher-resolution image than necessary may waste significantly /// more memory if the difference between the screen device pixel ratio and /// the device pixel ratio of the image is high. To reduce memory usage, /// consider providing more variants of the image. In the example above adding /// a 3.0x/heart.png variant would improve memory usage for screens with device /// pixel ratios between 3.0 and 3.5. /// /// [ImageConfiguration] can be used to customize the selection of the image /// variant by setting [ImageConfiguration.devicePixelRatio] to value different /// from the default. The default value is derived from /// [MediaQueryData.devicePixelRatio] by [createLocalImageConfiguration]. /// /// The directory level of the asset does not matter as long as the variants are /// at the equivalent level; that is, the following is also a valid bundle /// structure: /// /// icons/heart.png /// icons/1.5x/heart.png /// icons/2.0x/heart.png /// /// assets/icons/3.0x/heart.png would be a valid variant of /// assets/icons/heart.png. /// /// ## Fetching assets /// /// When fetching an image provided by the app itself, use the [assetName] /// argument to name the asset to choose. For instance, consider the structure /// above. First, the `pubspec.yaml` of the project should specify its assets in /// the `flutter` section: /// /// ```yaml /// flutter: /// assets: /// - icons/heart.png /// ``` /// /// Then, to fetch the image, use: /// ```dart /// const AssetImage('icons/heart.png') /// ``` /// /// {@tool snippet} /// /// The following shows the code required to write a widget that fully conforms /// to the [AssetImage] and [Widget] protocols. (It is essentially a /// bare-bones version of the [widgets.Image] widget made to work specifically for /// an [AssetImage].) /// /// ```dart /// class MyImage extends StatefulWidget { /// const MyImage({ /// super.key, /// required this.assetImage, /// }); /// /// final AssetImage assetImage; /// /// @override /// State<MyImage> createState() => _MyImageState(); /// } /// /// class _MyImageState extends State<MyImage> { /// ImageStream? _imageStream; /// ImageInfo? _imageInfo; /// /// @override /// void didChangeDependencies() { /// super.didChangeDependencies(); /// // We call _getImage here because createLocalImageConfiguration() needs to /// // be called again if the dependencies changed, in case the changes relate /// // to the DefaultAssetBundle, MediaQuery, etc, which that method uses. /// _getImage(); /// } /// /// @override /// void didUpdateWidget(MyImage oldWidget) { /// super.didUpdateWidget(oldWidget); /// if (widget.assetImage != oldWidget.assetImage) { /// _getImage(); /// } /// } /// /// void _getImage() { /// final ImageStream? oldImageStream = _imageStream; /// _imageStream = widget.assetImage.resolve(createLocalImageConfiguration(context)); /// if (_imageStream!.key != oldImageStream?.key) { /// // If the keys are the same, then we got the same image back, and so we don't /// // need to update the listeners. If the key changed, though, we must make sure /// // to switch our listeners to the new image stream. /// final ImageStreamListener listener = ImageStreamListener(_updateImage); /// oldImageStream?.removeListener(listener); /// _imageStream!.addListener(listener); /// } /// } /// /// void _updateImage(ImageInfo imageInfo, bool synchronousCall) { /// setState(() { /// // Trigger a build whenever the image changes. /// _imageInfo?.dispose(); /// _imageInfo = imageInfo; /// }); /// } /// /// @override /// void dispose() { /// _imageStream?.removeListener(ImageStreamListener(_updateImage)); /// _imageInfo?.dispose(); /// _imageInfo = null; /// super.dispose(); /// } /// /// @override /// Widget build(BuildContext context) { /// return RawImage( /// image: _imageInfo?.image, // this is a dart:ui Image object /// scale: _imageInfo?.scale ?? 1.0, /// ); /// } /// } /// ``` /// {@end-tool} /// /// ## Assets in packages /// /// To fetch an asset from a package, the [package] argument must be provided. /// For instance, suppose the structure above is inside a package called /// `my_icons`. Then to fetch the image, use: /// /// ```dart /// const AssetImage('icons/heart.png', package: 'my_icons') /// ``` /// /// Assets used by the package itself should also be fetched using the [package] /// argument as above. /// /// If the desired asset is specified in the `pubspec.yaml` of the package, it /// is bundled automatically with the app. In particular, assets used by the /// package itself must be specified in its `pubspec.yaml`. /// /// A package can also choose to have assets in its 'lib/' folder that are not /// specified in its `pubspec.yaml`. In this case for those images to be /// bundled, the app has to specify which ones to include. For instance a /// package named `fancy_backgrounds` could have: /// /// lib/backgrounds/background1.png /// lib/backgrounds/background2.png /// lib/backgrounds/background3.png /// /// To include, say the first image, the `pubspec.yaml` of the app should specify /// it in the `assets` section: /// /// ```yaml /// assets: /// - packages/fancy_backgrounds/backgrounds/background1.png /// ``` /// /// The `lib/` is implied, so it should not be included in the asset path. /// /// See also: /// /// * [Image.asset] for a shorthand of an [Image] widget backed by [AssetImage] /// when used without a scale. @immutable class AssetImage extends AssetBundleImageProvider { /// Creates an object that fetches an image from an asset bundle. /// /// The [assetName] argument should name the main asset from the set of images /// to choose from. The [package] argument must be non-null when fetching an /// asset that is included in package. See the documentation for the /// [AssetImage] class itself for details. const AssetImage( this.assetName, { this.bundle, this.package, }); /// The name of the main asset from the set of images to choose from. See the /// documentation for the [AssetImage] class itself for details. final String assetName; /// The name used to generate the key to obtain the asset. For local assets /// this is [assetName], and for assets from packages the [assetName] is /// prefixed 'packages/<package_name>/'. String get keyName => package == null ? assetName : 'packages/$package/$assetName'; /// The bundle from which the image will be obtained. /// /// If the provided [bundle] is null, the bundle provided in the /// [ImageConfiguration] passed to the [resolve] call will be used instead. If /// that is also null, the [rootBundle] is used. /// /// The image is obtained by calling [AssetBundle.load] on the given [bundle] /// using the key given by [keyName]. final AssetBundle? bundle; /// The name of the package from which the image is included. See the /// documentation for the [AssetImage] class itself for details. final String? package; // We assume the main asset is designed for a device pixel ratio of 1.0 static const double _naturalResolution = 1.0; @override Future<AssetBundleImageKey> obtainKey(ImageConfiguration configuration) { // This function tries to return a SynchronousFuture if possible. We do this // because otherwise showing an image would always take at least one frame, // which would be sad. (This code is called from inside build/layout/paint, // which all happens in one call frame; using native Futures would guarantee // that we resolve each future in a new call frame, and thus not in this // build/layout/paint sequence.) final AssetBundle chosenBundle = bundle ?? configuration.bundle ?? rootBundle; Completer<AssetBundleImageKey>? completer; Future<AssetBundleImageKey>? result; AssetManifest.loadFromAssetBundle(chosenBundle) .then((AssetManifest manifest) { final Iterable<AssetMetadata>? candidateVariants = manifest.getAssetVariants(keyName); final AssetMetadata chosenVariant = _chooseVariant( keyName, configuration, candidateVariants, ); final AssetBundleImageKey key = AssetBundleImageKey( bundle: chosenBundle, name: chosenVariant.key, scale: chosenVariant.targetDevicePixelRatio ?? _naturalResolution, ); if (completer != null) { // We already returned from this function, which means we are in the // asynchronous mode. Pass the value to the completer. The completer's // future is what we returned. completer.complete(key); } else { // We haven't yet returned, so we must have been called synchronously // just after loadStructuredData returned (which means it provided us // with a SynchronousFuture). Let's return a SynchronousFuture // ourselves. result = SynchronousFuture<AssetBundleImageKey>(key); } }) .onError((Object error, StackTrace stack) { // We had an error. (This guarantees we weren't called synchronously.) // Forward the error to the caller. assert(completer != null); assert(result == null); completer!.completeError(error, stack); }); if (result != null) { // The code above ran synchronously, and came up with an answer. // Return the SynchronousFuture that we created above. return result!; } // The code above hasn't yet run its "then" handler yet. Let's prepare a // completer for it to use when it does run. completer = Completer<AssetBundleImageKey>(); return completer.future; } AssetMetadata _chooseVariant(String mainAssetKey, ImageConfiguration config, Iterable<AssetMetadata>? candidateVariants) { if (candidateVariants == null || candidateVariants.isEmpty || config.devicePixelRatio == null) { return AssetMetadata(key: mainAssetKey, targetDevicePixelRatio: null, main: true); } final SplayTreeMap<double, AssetMetadata> candidatesByDevicePixelRatio = SplayTreeMap<double, AssetMetadata>(); for (final AssetMetadata candidate in candidateVariants) { candidatesByDevicePixelRatio[candidate.targetDevicePixelRatio ?? _naturalResolution] = candidate; } // TODO(ianh): implement support for config.locale, config.textDirection, // config.size, config.platform (then document this over in the Image.asset // docs) return _findBestVariant(candidatesByDevicePixelRatio, config.devicePixelRatio!); } // Returns the "best" asset variant amongst the available `candidates`. // // The best variant is chosen as follows: // - Choose a variant whose key matches `value` exactly, if available. // - If `value` is less than the lowest key, choose the variant with the // lowest key. // - If `value` is greater than the highest key, choose the variant with // the highest key. // - If the screen has low device pixel ratio, choose the variant with the // lowest key higher than `value`. // - If the screen has high device pixel ratio, choose the variant with the // key nearest to `value`. AssetMetadata _findBestVariant(SplayTreeMap<double, AssetMetadata> candidatesByDpr, double value) { if (candidatesByDpr.containsKey(value)) { return candidatesByDpr[value]!; } final double? lower = candidatesByDpr.lastKeyBefore(value); final double? upper = candidatesByDpr.firstKeyAfter(value); if (lower == null) { return candidatesByDpr[upper]!; } if (upper == null) { return candidatesByDpr[lower]!; } // On screens with low device-pixel ratios the artifacts from upscaling // images are more visible than on screens with a higher device-pixel // ratios because the physical pixels are larger. Choose the higher // resolution image in that case instead of the nearest one. if (value < _kLowDprLimit || value > (lower + upper) / 2) { return candidatesByDpr[upper]!; } else { return candidatesByDpr[lower]!; } } @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is AssetImage && other.keyName == keyName && other.bundle == bundle; } @override int get hashCode => Object.hash(keyName, bundle); @override String toString() => '${objectRuntimeType(this, 'AssetImage')}(bundle: $bundle, name: "$keyName")'; }
flutter/packages/flutter/lib/src/painting/image_resolution.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/painting/image_resolution.dart", "repo_id": "flutter", "token_count": 4924 }
639
// 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' show max, min; import 'package:flutter/foundation.dart'; /// A class that describes how textual contents should be scaled for better /// readability. /// /// The [scale] function computes the scaled font size given the original /// unscaled font size specified by app developers. /// /// The [==] operator defines the equality of 2 [TextScaler]s, which the /// framework uses to determine whether text widgets should rebuild when their /// [TextScaler] changes. Consider overriding the [==] operator if applicable /// to avoid unnecessary rebuilds. @immutable abstract class TextScaler { /// Creates a TextScaler. const TextScaler(); /// Creates a proportional [TextScaler] that scales the incoming font size by /// multiplying it with the given `textScaleFactor`. const factory TextScaler.linear(double textScaleFactor) = _LinearTextScaler; /// A [TextScaler] that doesn't scale the input font size. /// /// This is equivalent to `TextScaler.linear(1.0)`, the [TextScaler.scale] /// implementation always returns the input font size as-is. static const TextScaler noScaling = _LinearTextScaler(1.0); /// Computes the scaled font size (in logical pixels) with the given unscaled /// `fontSize` (in logical pixels). /// /// The input `fontSize` must be finite and non-negative. /// /// When given the same `fontSize` input, this method returns the same value. /// The output of a larger input `fontSize` is typically larger than that of a /// smaller input, but on unusual occasions they may produce the same output. /// For example, some platforms use single-precision floats to represent font /// sizes, as a result of truncation two different unscaled font sizes can be /// scaled to the same value. double scale(double fontSize); /// The estimated number of font pixels for each logical pixel. This property /// exists only for backward compatibility purposes, and will be removed in /// a future version of Flutter. /// /// The value of this property is only an estimate, so it may not reflect the /// exact text scaling strategy this [TextScaler] represents, especially when /// this [TextScaler] is not linear. Consider using [TextScaler.scale] instead. @Deprecated( 'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. ' 'This feature was deprecated after v3.12.0-2.0.pre.', ) double get textScaleFactor; /// Returns a new [TextScaler] that restricts the scaled font size to within /// the range `[minScaleFactor * fontSize, maxScaleFactor * fontSize]`. TextScaler clamp({ double minScaleFactor = 0, double maxScaleFactor = double.infinity }) { assert(maxScaleFactor >= minScaleFactor); assert(!maxScaleFactor.isNaN); assert(minScaleFactor.isFinite); assert(minScaleFactor >= 0); return minScaleFactor == maxScaleFactor ? TextScaler.linear(minScaleFactor) : _ClampedTextScaler(this, minScaleFactor, maxScaleFactor); } } final class _LinearTextScaler implements TextScaler { const _LinearTextScaler(this.textScaleFactor) : assert(textScaleFactor >= 0); @override final double textScaleFactor; @override double scale(double fontSize) { assert(fontSize >= 0); assert(fontSize.isFinite); return fontSize * textScaleFactor; } @override TextScaler clamp({ double minScaleFactor = 0, double maxScaleFactor = double.infinity }) { assert(maxScaleFactor >= minScaleFactor); assert(!maxScaleFactor.isNaN); assert(minScaleFactor.isFinite); assert(minScaleFactor >= 0); final double newScaleFactor = clampDouble(textScaleFactor, minScaleFactor, maxScaleFactor); return newScaleFactor == textScaleFactor ? this : _LinearTextScaler(newScaleFactor); } @override bool operator ==(Object other) { if (identical(this, other)) { return true; } return other is _LinearTextScaler && other.textScaleFactor == textScaleFactor; } @override int get hashCode => textScaleFactor.hashCode; @override String toString() => textScaleFactor == 1.0 ? 'no scaling' : 'linear (${textScaleFactor}x)'; } final class _ClampedTextScaler implements TextScaler { const _ClampedTextScaler(this.scaler, this.minScale, this.maxScale) : assert(maxScale > minScale); final TextScaler scaler; final double minScale; final double maxScale; @override double get textScaleFactor => clampDouble(scaler.textScaleFactor, minScale, maxScale); @override double scale(double fontSize) { assert(fontSize >= 0); assert(fontSize.isFinite); return minScale == maxScale ? minScale * fontSize : clampDouble(scaler.scale(fontSize), minScale * fontSize, maxScale * fontSize); } @override TextScaler clamp({ double minScaleFactor = 0, double maxScaleFactor = double.infinity }) { return minScaleFactor == maxScaleFactor ? _LinearTextScaler(minScaleFactor) : _ClampedTextScaler(scaler, max(minScaleFactor, minScale), min(maxScaleFactor, maxScale)); } @override bool operator ==(Object other) { if (identical(this, other)) { return true; } return other is _ClampedTextScaler && minScale == other.minScale && maxScale == other.maxScale && (minScale == maxScale || scaler == other.scaler); } @override int get hashCode => minScale == maxScale ? minScale.hashCode : Object.hash(scaler, minScale, maxScale); }
flutter/packages/flutter/lib/src/painting/text_scaler.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/painting/text_scaler.dart", "repo_id": "flutter", "token_count": 1681 }
640
// 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; import 'package:flutter/foundation.dart'; import 'object.dart'; import 'stack.dart'; // Describes which side the region data overflows on. enum _OverflowSide { left, top, bottom, right, } // Data used by the DebugOverflowIndicator to manage the regions and labels for // the indicators. class _OverflowRegionData { const _OverflowRegionData({ required this.rect, this.label = '', this.labelOffset = Offset.zero, this.rotation = 0.0, required this.side, }); final Rect rect; final String label; final Offset labelOffset; final double rotation; final _OverflowSide side; } /// An mixin indicator that is drawn when a [RenderObject] overflows its /// container. /// /// This is used by some RenderObjects that are containers to show where, and by /// how much, their children overflow their containers. These indicators are /// typically only shown in a debug build (where the call to /// [paintOverflowIndicator] is surrounded by an assert). /// /// This class will also print a debug message to the console when the container /// overflows. It will print on the first occurrence, and once after each time that /// [reassemble] is called. /// /// {@tool snippet} /// /// ```dart /// class MyRenderObject extends RenderAligningShiftedBox with DebugOverflowIndicatorMixin { /// MyRenderObject({ /// super.alignment = Alignment.center, /// required super.textDirection, /// super.child, /// }); /// /// late Rect _containerRect; /// late Rect _childRect; /// /// @override /// void performLayout() { /// // ... /// final BoxParentData childParentData = child!.parentData! as BoxParentData; /// _containerRect = Offset.zero & size; /// _childRect = childParentData.offset & child!.size; /// } /// /// @override /// void paint(PaintingContext context, Offset offset) { /// // Do normal painting here... /// // ... /// /// assert(() { /// paintOverflowIndicator(context, offset, _containerRect, _childRect); /// return true; /// }()); /// } /// } /// ``` /// {@end-tool} /// /// See also: /// /// * [RenderConstraintsTransformBox] and [RenderFlex] for examples of classes /// that use this indicator mixin. mixin DebugOverflowIndicatorMixin on RenderObject { static const Color _black = Color(0xBF000000); static const Color _yellow = Color(0xBFFFFF00); // The fraction of the container that the indicator covers. static const double _indicatorFraction = 0.1; static const double _indicatorFontSizePixels = 7.5; static const double _indicatorLabelPaddingPixels = 1.0; static const TextStyle _indicatorTextStyle = TextStyle( color: Color(0xFF900000), fontSize: _indicatorFontSizePixels, fontWeight: FontWeight.w800, ); static final Paint _indicatorPaint = Paint() ..shader = ui.Gradient.linear( Offset.zero, const Offset(10.0, 10.0), <Color>[_black, _yellow, _yellow, _black], <double>[0.25, 0.25, 0.75, 0.75], TileMode.repeated, ); static final Paint _labelBackgroundPaint = Paint()..color = const Color(0xFFFFFFFF); final List<TextPainter> _indicatorLabel = List<TextPainter>.generate( _OverflowSide.values.length, (int i) => TextPainter(textDirection: TextDirection.ltr), // This label is in English. growable: false, ); @override void dispose() { for (final TextPainter painter in _indicatorLabel) { painter.dispose(); } super.dispose(); } // Set to true to trigger a debug message in the console upon // the next paint call. Will be reset after each paint. bool _overflowReportNeeded = true; String _formatPixels(double value) { assert(value > 0.0); final String pixels; if (value > 10.0) { pixels = value.toStringAsFixed(0); } else if (value > 1.0) { pixels = value.toStringAsFixed(1); } else { pixels = value.toStringAsPrecision(3); } return pixels; } List<_OverflowRegionData> _calculateOverflowRegions(RelativeRect overflow, Rect containerRect) { final List<_OverflowRegionData> regions = <_OverflowRegionData>[]; if (overflow.left > 0.0) { final Rect markerRect = Rect.fromLTWH( 0.0, 0.0, containerRect.width * _indicatorFraction, containerRect.height, ); regions.add(_OverflowRegionData( rect: markerRect, label: 'LEFT OVERFLOWED BY ${_formatPixels(overflow.left)} PIXELS', labelOffset: markerRect.centerLeft + const Offset(_indicatorFontSizePixels + _indicatorLabelPaddingPixels, 0.0), rotation: math.pi / 2.0, side: _OverflowSide.left, )); } if (overflow.right > 0.0) { final Rect markerRect = Rect.fromLTWH( containerRect.width * (1.0 - _indicatorFraction), 0.0, containerRect.width * _indicatorFraction, containerRect.height, ); regions.add(_OverflowRegionData( rect: markerRect, label: 'RIGHT OVERFLOWED BY ${_formatPixels(overflow.right)} PIXELS', labelOffset: markerRect.centerRight - const Offset(_indicatorFontSizePixels + _indicatorLabelPaddingPixels, 0.0), rotation: -math.pi / 2.0, side: _OverflowSide.right, )); } if (overflow.top > 0.0) { final Rect markerRect = Rect.fromLTWH( 0.0, 0.0, containerRect.width, containerRect.height * _indicatorFraction, ); regions.add(_OverflowRegionData( rect: markerRect, label: 'TOP OVERFLOWED BY ${_formatPixels(overflow.top)} PIXELS', labelOffset: markerRect.topCenter + const Offset(0.0, _indicatorLabelPaddingPixels), side: _OverflowSide.top, )); } if (overflow.bottom > 0.0) { final Rect markerRect = Rect.fromLTWH( 0.0, containerRect.height * (1.0 - _indicatorFraction), containerRect.width, containerRect.height * _indicatorFraction, ); regions.add(_OverflowRegionData( rect: markerRect, label: 'BOTTOM OVERFLOWED BY ${_formatPixels(overflow.bottom)} PIXELS', labelOffset: markerRect.bottomCenter - const Offset(0.0, _indicatorFontSizePixels + _indicatorLabelPaddingPixels), side: _OverflowSide.bottom, )); } return regions; } void _reportOverflow(RelativeRect overflow, List<DiagnosticsNode>? overflowHints) { overflowHints ??= <DiagnosticsNode>[]; if (overflowHints.isEmpty) { overflowHints.add(ErrorDescription( 'The edge of the $runtimeType that is ' 'overflowing has been marked in the rendering with a yellow and black ' 'striped pattern. This is usually caused by the contents being too big ' 'for the $runtimeType.', )); overflowHints.add(ErrorHint( 'This is considered an error condition because it indicates that there ' 'is content that cannot be seen. If the content is legitimately bigger ' 'than the available space, consider clipping it with a ClipRect widget ' 'before putting it in the $runtimeType, or using a scrollable ' 'container, like a ListView.', )); } final List<String> overflows = <String>[ if (overflow.left > 0.0) '${_formatPixels(overflow.left)} pixels on the left', if (overflow.top > 0.0) '${_formatPixels(overflow.top)} pixels on the top', if (overflow.bottom > 0.0) '${_formatPixels(overflow.bottom)} pixels on the bottom', if (overflow.right > 0.0) '${_formatPixels(overflow.right)} pixels on the right', ]; String overflowText = ''; assert(overflows.isNotEmpty, "Somehow $runtimeType didn't actually overflow like it thought it did."); switch (overflows.length) { case 1: overflowText = overflows.first; case 2: overflowText = '${overflows.first} and ${overflows.last}'; default: overflows[overflows.length - 1] = 'and ${overflows[overflows.length - 1]}'; overflowText = overflows.join(', '); } // TODO(jacobr): add the overflows in pixels as structured data so they can // be visualized in debugging tools. FlutterError.reportError( FlutterErrorDetails( exception: FlutterError('A $runtimeType overflowed by $overflowText.'), library: 'rendering library', context: ErrorDescription('during layout'), informationCollector: () => <DiagnosticsNode>[ // debugCreator should only be set in DebugMode, but we want the // treeshaker to know that. if (kDebugMode && debugCreator != null) DiagnosticsDebugCreator(debugCreator!), ...overflowHints!, describeForError('The specific $runtimeType in question is'), // TODO(jacobr): this line is ascii art that it would be nice to // handle a little more generically in GUI debugging clients in the // future. DiagnosticsNode.message('◢◤' * (FlutterError.wrapWidth ~/ 2), allowWrap: false), ], ), ); } /// To be called when the overflow indicators should be painted. /// /// Typically only called if there is an overflow, and only from within a /// debug build. /// /// See example code in [DebugOverflowIndicatorMixin] documentation. void paintOverflowIndicator( PaintingContext context, Offset offset, Rect containerRect, Rect childRect, { List<DiagnosticsNode>? overflowHints, }) { final RelativeRect overflow = RelativeRect.fromRect(containerRect, childRect); if (overflow.left <= 0.0 && overflow.right <= 0.0 && overflow.top <= 0.0 && overflow.bottom <= 0.0) { return; } final List<_OverflowRegionData> overflowRegions = _calculateOverflowRegions(overflow, containerRect); for (final _OverflowRegionData region in overflowRegions) { context.canvas.drawRect(region.rect.shift(offset), _indicatorPaint); final TextSpan? textSpan = _indicatorLabel[region.side.index].text as TextSpan?; if (textSpan?.text != region.label) { _indicatorLabel[region.side.index].text = TextSpan( text: region.label, style: _indicatorTextStyle, ); _indicatorLabel[region.side.index].layout(); } final Offset labelOffset = region.labelOffset + offset; final Offset centerOffset = Offset(-_indicatorLabel[region.side.index].width / 2.0, 0.0); final Rect textBackgroundRect = centerOffset & _indicatorLabel[region.side.index].size; context.canvas.save(); context.canvas.translate(labelOffset.dx, labelOffset.dy); context.canvas.rotate(region.rotation); context.canvas.drawRect(textBackgroundRect, _labelBackgroundPaint); _indicatorLabel[region.side.index].paint(context.canvas, centerOffset); context.canvas.restore(); } if (_overflowReportNeeded) { _overflowReportNeeded = false; _reportOverflow(overflow, overflowHints); } } @override void reassemble() { super.reassemble(); // Users expect error messages to be shown again after hot reload. assert(() { _overflowReportNeeded = true; return true; }()); } }
flutter/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart", "repo_id": "flutter", "token_count": 4278 }
641
// 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:ui' as ui show Color, Gradient, Image, ImageFilter; import 'package:flutter/animation.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/semantics.dart'; import 'package:flutter/services.dart'; import 'box.dart'; import 'layer.dart'; import 'layout_helper.dart'; import 'object.dart'; export 'package:flutter/gestures.dart' show PointerCancelEvent, PointerDownEvent, PointerEvent, PointerMoveEvent, PointerUpEvent; /// A base class for render boxes that resemble their children. /// /// A proxy box has a single child and mimics all the properties of that /// child by calling through to the child for each function in the render box /// protocol. For example, a proxy box determines its size by asking its child /// to layout with the same constraints and then matching the size. /// /// A proxy box isn't useful on its own because you might as well just replace /// the proxy box with its child. However, RenderProxyBox is a useful base class /// for render objects that wish to mimic most, but not all, of the properties /// of their child. /// /// See also: /// /// * [RenderProxySliver], a base class for render slivers that resemble their /// children. class RenderProxyBox extends RenderBox with RenderObjectWithChildMixin<RenderBox>, RenderProxyBoxMixin<RenderBox> { /// Creates a proxy render box. /// /// Proxy render boxes are rarely created directly because they proxy /// the render box protocol to [child]. Instead, consider using one of the /// subclasses. RenderProxyBox([RenderBox? child]) { this.child = child; } } /// Implementation of [RenderProxyBox]. /// /// Use this mixin in situations where the proxying behavior /// of [RenderProxyBox] is desired but inheriting from [RenderProxyBox] is /// impractical (e.g. because you want to inherit from a different class). /// /// If a class already inherits from [RenderProxyBox] and also uses this mixin, /// you can safely delete the use of the mixin. @optionalTypeArgs mixin RenderProxyBoxMixin<T extends RenderBox> on RenderBox, RenderObjectWithChildMixin<T> { @override void setupParentData(RenderObject child) { // We don't actually use the offset argument in BoxParentData, so let's // avoid allocating it at all. if (child.parentData is! ParentData) { child.parentData = ParentData(); } } @override double computeMinIntrinsicWidth(double height) { return child?.getMinIntrinsicWidth(height) ?? 0.0; } @override double computeMaxIntrinsicWidth(double height) { return child?.getMaxIntrinsicWidth(height) ?? 0.0; } @override double computeMinIntrinsicHeight(double width) { return child?.getMinIntrinsicHeight(width) ?? 0.0; } @override double computeMaxIntrinsicHeight(double width) { return child?.getMaxIntrinsicHeight(width) ?? 0.0; } @override double? computeDistanceToActualBaseline(TextBaseline baseline) { return child?.getDistanceToActualBaseline(baseline) ?? super.computeDistanceToActualBaseline(baseline); } @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { return child?.getDryLayout(constraints) ?? computeSizeForNoChild(constraints); } @override void performLayout() { size = (child?..layout(constraints, parentUsesSize: true))?.size ?? computeSizeForNoChild(constraints); return; } /// Calculate the size the [RenderProxyBox] would have under the given /// [BoxConstraints] for the case where it does not have a child. Size computeSizeForNoChild(BoxConstraints constraints) { return constraints.smallest; } @override bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { return child?.hitTest(result, position: position) ?? false; } @override void applyPaintTransform(RenderObject child, Matrix4 transform) { } @override void paint(PaintingContext context, Offset offset) { final RenderBox? child = this.child; if (child == null) { return; } context.paintChild(child, offset); } } /// How to behave during hit tests. enum HitTestBehavior { /// Targets that defer to their children receive events within their bounds /// only if one of their children is hit by the hit test. deferToChild, /// Opaque targets can be hit by hit tests, causing them to both receive /// events within their bounds and prevent targets visually behind them from /// also receiving events. opaque, /// Translucent targets both receive events within their bounds and permit /// targets visually behind them to also receive events. translucent, } /// A RenderProxyBox subclass that allows you to customize the /// hit-testing behavior. abstract class RenderProxyBoxWithHitTestBehavior extends RenderProxyBox { /// Initializes member variables for subclasses. /// /// By default, the [behavior] is [HitTestBehavior.deferToChild]. RenderProxyBoxWithHitTestBehavior({ this.behavior = HitTestBehavior.deferToChild, RenderBox? child, }) : super(child); /// How to behave during hit testing when deciding how the hit test propagates /// to children and whether to consider targets behind this one. /// /// Defaults to [HitTestBehavior.deferToChild]. /// /// See [HitTestBehavior] for the allowed values and their meanings. HitTestBehavior behavior; @override bool hitTest(BoxHitTestResult result, { required Offset position }) { bool hitTarget = false; if (size.contains(position)) { hitTarget = hitTestChildren(result, position: position) || hitTestSelf(position); if (hitTarget || behavior == HitTestBehavior.translucent) { result.add(BoxHitTestEntry(this, position)); } } return hitTarget; } @override bool hitTestSelf(Offset position) => behavior == HitTestBehavior.opaque; @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(EnumProperty<HitTestBehavior>('behavior', behavior, defaultValue: null)); } } /// Imposes additional constraints on its child. /// /// A render constrained box proxies most functions in the render box protocol /// to its child, except that when laying out its child, it tightens the /// constraints provided by its parent by enforcing the [additionalConstraints] /// as well. /// /// For example, if you wanted [child] to have a minimum height of 50.0 logical /// pixels, you could use `const BoxConstraints(minHeight: 50.0)` as the /// [additionalConstraints]. class RenderConstrainedBox extends RenderProxyBox { /// Creates a render box that constrains its child. /// /// The [additionalConstraints] argument must be valid. RenderConstrainedBox({ RenderBox? child, required BoxConstraints additionalConstraints, }) : assert(additionalConstraints.debugAssertIsValid()), _additionalConstraints = additionalConstraints, super(child); /// Additional constraints to apply to [child] during layout. BoxConstraints get additionalConstraints => _additionalConstraints; BoxConstraints _additionalConstraints; set additionalConstraints(BoxConstraints value) { assert(value.debugAssertIsValid()); if (_additionalConstraints == value) { return; } _additionalConstraints = value; markNeedsLayout(); } @override double computeMinIntrinsicWidth(double height) { if (_additionalConstraints.hasBoundedWidth && _additionalConstraints.hasTightWidth) { return _additionalConstraints.minWidth; } final double width = super.computeMinIntrinsicWidth(height); assert(width.isFinite); if (!_additionalConstraints.hasInfiniteWidth) { return _additionalConstraints.constrainWidth(width); } return width; } @override double computeMaxIntrinsicWidth(double height) { if (_additionalConstraints.hasBoundedWidth && _additionalConstraints.hasTightWidth) { return _additionalConstraints.minWidth; } final double width = super.computeMaxIntrinsicWidth(height); assert(width.isFinite); if (!_additionalConstraints.hasInfiniteWidth) { return _additionalConstraints.constrainWidth(width); } return width; } @override double computeMinIntrinsicHeight(double width) { if (_additionalConstraints.hasBoundedHeight && _additionalConstraints.hasTightHeight) { return _additionalConstraints.minHeight; } final double height = super.computeMinIntrinsicHeight(width); assert(height.isFinite); if (!_additionalConstraints.hasInfiniteHeight) { return _additionalConstraints.constrainHeight(height); } return height; } @override double computeMaxIntrinsicHeight(double width) { if (_additionalConstraints.hasBoundedHeight && _additionalConstraints.hasTightHeight) { return _additionalConstraints.minHeight; } final double height = super.computeMaxIntrinsicHeight(width); assert(height.isFinite); if (!_additionalConstraints.hasInfiniteHeight) { return _additionalConstraints.constrainHeight(height); } return height; } @override void performLayout() { final BoxConstraints constraints = this.constraints; if (child != null) { child!.layout(_additionalConstraints.enforce(constraints), parentUsesSize: true); size = child!.size; } else { size = _additionalConstraints.enforce(constraints).constrain(Size.zero); } } @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { if (child != null) { return child!.getDryLayout(_additionalConstraints.enforce(constraints)); } else { return _additionalConstraints.enforce(constraints).constrain(Size.zero); } } @override void debugPaintSize(PaintingContext context, Offset offset) { super.debugPaintSize(context, offset); assert(() { final Paint paint; if (child == null || child!.size.isEmpty) { paint = Paint() ..color = const Color(0x90909090); context.canvas.drawRect(offset & size, paint); } return true; }()); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<BoxConstraints>('additionalConstraints', additionalConstraints)); } } /// Constrains the child's [BoxConstraints.maxWidth] and /// [BoxConstraints.maxHeight] if they're otherwise unconstrained. /// /// This has the effect of giving the child a natural dimension in unbounded /// environments. For example, by providing a [maxHeight] to a widget that /// normally tries to be as big as possible, the widget will normally size /// itself to fit its parent, but when placed in a vertical list, it will take /// on the given height. /// /// This is useful when composing widgets that normally try to match their /// parents' size, so that they behave reasonably in lists (which are /// unbounded). class RenderLimitedBox extends RenderProxyBox { /// Creates a render box that imposes a maximum width or maximum height on its /// child if the child is otherwise unconstrained. /// /// The [maxWidth] and [maxHeight] arguments not be null and must be /// non-negative. RenderLimitedBox({ RenderBox? child, double maxWidth = double.infinity, double maxHeight = double.infinity, }) : assert(maxWidth >= 0.0), assert(maxHeight >= 0.0), _maxWidth = maxWidth, _maxHeight = maxHeight, super(child); /// The value to use for maxWidth if the incoming maxWidth constraint is infinite. double get maxWidth => _maxWidth; double _maxWidth; set maxWidth(double value) { assert(value >= 0.0); if (_maxWidth == value) { return; } _maxWidth = value; markNeedsLayout(); } /// The value to use for maxHeight if the incoming maxHeight constraint is infinite. double get maxHeight => _maxHeight; double _maxHeight; set maxHeight(double value) { assert(value >= 0.0); if (_maxHeight == value) { return; } _maxHeight = value; markNeedsLayout(); } BoxConstraints _limitConstraints(BoxConstraints constraints) { return BoxConstraints( minWidth: constraints.minWidth, maxWidth: constraints.hasBoundedWidth ? constraints.maxWidth : constraints.constrainWidth(maxWidth), minHeight: constraints.minHeight, maxHeight: constraints.hasBoundedHeight ? constraints.maxHeight : constraints.constrainHeight(maxHeight), ); } Size _computeSize({required BoxConstraints constraints, required ChildLayouter layoutChild }) { if (child != null) { final Size childSize = layoutChild(child!, _limitConstraints(constraints)); return constraints.constrain(childSize); } return _limitConstraints(constraints).constrain(Size.zero); } @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { return _computeSize( constraints: constraints, layoutChild: ChildLayoutHelper.dryLayoutChild, ); } @override void performLayout() { size = _computeSize( constraints: constraints, layoutChild: ChildLayoutHelper.layoutChild, ); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DoubleProperty('maxWidth', maxWidth, defaultValue: double.infinity)); properties.add(DoubleProperty('maxHeight', maxHeight, defaultValue: double.infinity)); } } /// Attempts to size the child to a specific aspect ratio. /// /// The render object first tries the largest width permitted by the layout /// constraints. The height of the render object is determined by applying the /// given aspect ratio to the width, expressed as a ratio of width to height. /// /// For example, a 16:9 width:height aspect ratio would have a value of /// 16.0/9.0. If the maximum width is infinite, the initial width is determined /// by applying the aspect ratio to the maximum height. /// /// Now consider a second example, this time with an aspect ratio of 2.0 and /// layout constraints that require the width to be between 0.0 and 100.0 and /// the height to be between 0.0 and 100.0. We'll select a width of 100.0 (the /// biggest allowed) and a height of 50.0 (to match the aspect ratio). /// /// In that same situation, if the aspect ratio is 0.5, we'll also select a /// width of 100.0 (still the biggest allowed) and we'll attempt to use a height /// of 200.0. Unfortunately, that violates the constraints because the child can /// be at most 100.0 pixels tall. The render object will then take that value /// and apply the aspect ratio again to obtain a width of 50.0. That width is /// permitted by the constraints and the child receives a width of 50.0 and a /// height of 100.0. If the width were not permitted, the render object would /// continue iterating through the constraints. If the render object does not /// find a feasible size after consulting each constraint, the render object /// will eventually select a size for the child that meets the layout /// constraints but fails to meet the aspect ratio constraints. class RenderAspectRatio extends RenderProxyBox { /// Creates as render object with a specific aspect ratio. /// /// The [aspectRatio] argument must be a finite, positive value. RenderAspectRatio({ RenderBox? child, required double aspectRatio, }) : assert(aspectRatio > 0.0), assert(aspectRatio.isFinite), _aspectRatio = aspectRatio, super(child); /// The aspect ratio to attempt to use. /// /// The aspect ratio is expressed as a ratio of width to height. For example, /// a 16:9 width:height aspect ratio would have a value of 16.0/9.0. double get aspectRatio => _aspectRatio; double _aspectRatio; set aspectRatio(double value) { assert(value > 0.0); assert(value.isFinite); if (_aspectRatio == value) { return; } _aspectRatio = value; markNeedsLayout(); } @override double computeMinIntrinsicWidth(double height) { if (height.isFinite) { return height * _aspectRatio; } return child?.getMinIntrinsicWidth(height) ?? 0.0; } @override double computeMaxIntrinsicWidth(double height) { if (height.isFinite) { return height * _aspectRatio; } return child?.getMaxIntrinsicWidth(height) ?? 0.0; } @override double computeMinIntrinsicHeight(double width) { if (width.isFinite) { return width / _aspectRatio; } return child?.getMinIntrinsicHeight(width) ?? 0.0; } @override double computeMaxIntrinsicHeight(double width) { if (width.isFinite) { return width / _aspectRatio; } return child?.getMaxIntrinsicHeight(width) ?? 0.0; } Size _applyAspectRatio(BoxConstraints constraints) { assert(constraints.debugAssertIsValid()); assert(() { if (!constraints.hasBoundedWidth && !constraints.hasBoundedHeight) { throw FlutterError( '$runtimeType has unbounded constraints.\n' 'This $runtimeType was given an aspect ratio of $aspectRatio but was given ' 'both unbounded width and unbounded height constraints. Because both ' "constraints were unbounded, this render object doesn't know how much " 'size to consume.', ); } return true; }()); if (constraints.isTight) { return constraints.smallest; } double width = constraints.maxWidth; double height; // We default to picking the height based on the width, but if the width // would be infinite, that's not sensible so we try to infer the height // from the width. if (width.isFinite) { height = width / _aspectRatio; } else { height = constraints.maxHeight; width = height * _aspectRatio; } // Similar to RenderImage, we iteratively attempt to fit within the given // constraints while maintaining the given aspect ratio. The order of // applying the constraints is also biased towards inferring the height // from the width. if (width > constraints.maxWidth) { width = constraints.maxWidth; height = width / _aspectRatio; } if (height > constraints.maxHeight) { height = constraints.maxHeight; width = height * _aspectRatio; } if (width < constraints.minWidth) { width = constraints.minWidth; height = width / _aspectRatio; } if (height < constraints.minHeight) { height = constraints.minHeight; width = height * _aspectRatio; } return constraints.constrain(Size(width, height)); } @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { return _applyAspectRatio(constraints); } @override void performLayout() { size = computeDryLayout(constraints); if (child != null) { child!.layout(BoxConstraints.tight(size)); } } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DoubleProperty('aspectRatio', aspectRatio)); } } /// Sizes its child to the child's maximum intrinsic width. /// /// This class is useful, for example, when unlimited width is available and /// you would like a child that would otherwise attempt to expand infinitely to /// instead size itself to a more reasonable width. /// /// The constraints that this object passes to its child will adhere to the /// parent's constraints, so if the constraints are not large enough to satisfy /// the child's maximum intrinsic width, then the child will get less width /// than it otherwise would. Likewise, if the minimum width constraint is /// larger than the child's maximum intrinsic width, the child will be given /// more width than it otherwise would. /// /// If [stepWidth] is non-null, the child's width will be snapped to a multiple /// of the [stepWidth]. Similarly, if [stepHeight] is non-null, the child's /// height will be snapped to a multiple of the [stepHeight]. /// /// This class is relatively expensive, because it adds a speculative layout /// pass before the final layout phase. Avoid using it where possible. In the /// worst case, this render object can result in a layout that is O(N²) in the /// depth of the tree. /// /// See also: /// /// * [Align], a widget that aligns its child within itself. This can be used /// to loosen the constraints passed to the [RenderIntrinsicWidth], /// allowing the [RenderIntrinsicWidth]'s child to be smaller than that of /// its parent. /// * [Row], which when used with [CrossAxisAlignment.stretch] can be used /// to loosen just the width constraints that are passed to the /// [RenderIntrinsicWidth], allowing the [RenderIntrinsicWidth]'s child's /// width to be smaller than that of its parent. class RenderIntrinsicWidth extends RenderProxyBox { /// Creates a render object that sizes itself to its child's intrinsic width. /// /// If [stepWidth] is non-null it must be > 0.0. Similarly If [stepHeight] is /// non-null it must be > 0.0. RenderIntrinsicWidth({ double? stepWidth, double? stepHeight, RenderBox? child, }) : assert(stepWidth == null || stepWidth > 0.0), assert(stepHeight == null || stepHeight > 0.0), _stepWidth = stepWidth, _stepHeight = stepHeight, super(child); /// If non-null, force the child's width to be a multiple of this value. /// /// This value must be null or > 0.0. double? get stepWidth => _stepWidth; double? _stepWidth; set stepWidth(double? value) { assert(value == null || value > 0.0); if (value == _stepWidth) { return; } _stepWidth = value; markNeedsLayout(); } /// If non-null, force the child's height to be a multiple of this value. /// /// This value must be null or > 0.0. double? get stepHeight => _stepHeight; double? _stepHeight; set stepHeight(double? value) { assert(value == null || value > 0.0); if (value == _stepHeight) { return; } _stepHeight = value; markNeedsLayout(); } static double _applyStep(double input, double? step) { assert(input.isFinite); if (step == null) { return input; } return (input / step).ceil() * step; } @override double computeMinIntrinsicWidth(double height) { return computeMaxIntrinsicWidth(height); } @override double computeMaxIntrinsicWidth(double height) { if (child == null) { return 0.0; } final double width = child!.getMaxIntrinsicWidth(height); return _applyStep(width, _stepWidth); } @override double computeMinIntrinsicHeight(double width) { if (child == null) { return 0.0; } if (!width.isFinite) { width = computeMaxIntrinsicWidth(double.infinity); } assert(width.isFinite); final double height = child!.getMinIntrinsicHeight(width); return _applyStep(height, _stepHeight); } @override double computeMaxIntrinsicHeight(double width) { if (child == null) { return 0.0; } if (!width.isFinite) { width = computeMaxIntrinsicWidth(double.infinity); } assert(width.isFinite); final double height = child!.getMaxIntrinsicHeight(width); return _applyStep(height, _stepHeight); } Size _computeSize({required ChildLayouter layoutChild, required BoxConstraints constraints}) { if (child != null) { if (!constraints.hasTightWidth) { final double width = child!.getMaxIntrinsicWidth(constraints.maxHeight); assert(width.isFinite); constraints = constraints.tighten(width: _applyStep(width, _stepWidth)); } if (_stepHeight != null) { final double height = child!.getMaxIntrinsicHeight(constraints.maxWidth); assert(height.isFinite); constraints = constraints.tighten(height: _applyStep(height, _stepHeight)); } return layoutChild(child!, constraints); } else { return constraints.smallest; } } @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { return _computeSize( layoutChild: ChildLayoutHelper.dryLayoutChild, constraints: constraints, ); } @override void performLayout() { size = _computeSize( layoutChild: ChildLayoutHelper.layoutChild, constraints: constraints, ); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DoubleProperty('stepWidth', stepWidth)); properties.add(DoubleProperty('stepHeight', stepHeight)); } } /// Sizes its child to the child's intrinsic height. /// /// This class is useful, for example, when unlimited height is available and /// you would like a child that would otherwise attempt to expand infinitely to /// instead size itself to a more reasonable height. /// /// The constraints that this object passes to its child will adhere to the /// parent's constraints, so if the constraints are not large enough to satisfy /// the child's maximum intrinsic height, then the child will get less height /// than it otherwise would. Likewise, if the minimum height constraint is /// larger than the child's maximum intrinsic height, the child will be given /// more height than it otherwise would. /// /// This class is relatively expensive, because it adds a speculative layout /// pass before the final layout phase. Avoid using it where possible. In the /// worst case, this render object can result in a layout that is O(N²) in the /// depth of the tree. /// /// See also: /// /// * [Align], a widget that aligns its child within itself. This can be used /// to loosen the constraints passed to the [RenderIntrinsicHeight], /// allowing the [RenderIntrinsicHeight]'s child to be smaller than that of /// its parent. /// * [Column], which when used with [CrossAxisAlignment.stretch] can be used /// to loosen just the height constraints that are passed to the /// [RenderIntrinsicHeight], allowing the [RenderIntrinsicHeight]'s child's /// height to be smaller than that of its parent. class RenderIntrinsicHeight extends RenderProxyBox { /// Creates a render object that sizes itself to its child's intrinsic height. RenderIntrinsicHeight({ RenderBox? child, }) : super(child); @override double computeMinIntrinsicWidth(double height) { if (child == null) { return 0.0; } if (!height.isFinite) { height = child!.getMaxIntrinsicHeight(double.infinity); } assert(height.isFinite); return child!.getMinIntrinsicWidth(height); } @override double computeMaxIntrinsicWidth(double height) { if (child == null) { return 0.0; } if (!height.isFinite) { height = child!.getMaxIntrinsicHeight(double.infinity); } assert(height.isFinite); return child!.getMaxIntrinsicWidth(height); } @override double computeMinIntrinsicHeight(double width) { return computeMaxIntrinsicHeight(width); } Size _computeSize({required ChildLayouter layoutChild, required BoxConstraints constraints}) { if (child != null) { if (!constraints.hasTightHeight) { final double height = child!.getMaxIntrinsicHeight(constraints.maxWidth); assert(height.isFinite); constraints = constraints.tighten(height: height); } return layoutChild(child!, constraints); } else { return constraints.smallest; } } @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { return _computeSize( layoutChild: ChildLayoutHelper.dryLayoutChild, constraints: constraints, ); } @override void performLayout() { size = _computeSize( layoutChild: ChildLayoutHelper.layoutChild, constraints: constraints, ); } } /// Excludes the child from baseline computations in the parent. class RenderIgnoreBaseline extends RenderProxyBox { /// Create a render object that causes the parent to ignore the child for baseline computations. RenderIgnoreBaseline({ RenderBox? child, }) : super(child); @override double? computeDistanceToActualBaseline(TextBaseline baseline) { return null; } } /// 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. class RenderOpacity extends RenderProxyBox { /// Creates a partially transparent render object. /// /// The [opacity] argument must be between 0.0 and 1.0, inclusive. RenderOpacity({ double opacity = 1.0, bool alwaysIncludeSemantics = false, RenderBox? child, }) : assert(opacity >= 0.0 && opacity <= 1.0), _opacity = opacity, _alwaysIncludeSemantics = alwaysIncludeSemantics, _alpha = ui.Color.getAlphaFromOpacity(opacity), super(child); @override bool get alwaysNeedsCompositing => child != null && _alpha > 0; @override bool get isRepaintBoundary => alwaysNeedsCompositing; int _alpha; /// 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). /// /// 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. double get opacity => _opacity; double _opacity; set opacity(double value) { assert(value >= 0.0 && value <= 1.0); if (_opacity == value) { return; } final bool didNeedCompositing = alwaysNeedsCompositing; final bool wasVisible = _alpha != 0; _opacity = value; _alpha = ui.Color.getAlphaFromOpacity(_opacity); if (didNeedCompositing != alwaysNeedsCompositing) { markNeedsCompositingBitsUpdate(); } markNeedsCompositedLayerUpdate(); if (wasVisible != (_alpha != 0) && !alwaysIncludeSemantics) { markNeedsSemanticsUpdate(); } } /// Whether child semantics are included regardless of the opacity. /// /// If false, semantics are excluded when [opacity] is 0.0. /// /// Defaults to false. bool get alwaysIncludeSemantics => _alwaysIncludeSemantics; bool _alwaysIncludeSemantics; set alwaysIncludeSemantics(bool value) { if (value == _alwaysIncludeSemantics) { return; } _alwaysIncludeSemantics = value; markNeedsSemanticsUpdate(); } @override bool paintsChild(RenderBox child) { assert(child.parent == this); return _alpha > 0; } @override OffsetLayer updateCompositedLayer({required covariant OpacityLayer? oldLayer}) { final OpacityLayer layer = oldLayer ?? OpacityLayer(); layer.alpha = _alpha; return layer; } @override void paint(PaintingContext context, Offset offset) { if (child == null || _alpha == 0) { return; } super.paint(context, offset); } @override void visitChildrenForSemantics(RenderObjectVisitor visitor) { if (child != null && (_alpha != 0 || alwaysIncludeSemantics)) { visitor(child!); } } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DoubleProperty('opacity', opacity)); properties.add(FlagProperty('alwaysIncludeSemantics', value: alwaysIncludeSemantics, ifTrue: 'alwaysIncludeSemantics')); } } /// Implementation of [RenderAnimatedOpacity] and [RenderSliverAnimatedOpacity]. /// /// This mixin allows the logic of animating opacity to be used with different /// layout models, e.g. the way that [RenderAnimatedOpacity] uses it for [RenderBox] /// and [RenderSliverAnimatedOpacity] uses it for [RenderSliver]. mixin RenderAnimatedOpacityMixin<T extends RenderObject> on RenderObjectWithChildMixin<T> { int? _alpha; @override bool get isRepaintBoundary => child != null && _currentlyIsRepaintBoundary!; bool? _currentlyIsRepaintBoundary; @override OffsetLayer updateCompositedLayer({required covariant OpacityLayer? oldLayer}) { final OpacityLayer updatedLayer = oldLayer ?? OpacityLayer(); updatedLayer.alpha = _alpha; return updatedLayer; } /// The animation that drives this render object's opacity. /// /// An opacity of 1.0 is fully opaque. An opacity of 0.0 is fully transparent /// (i.e., invisible). /// /// To change the opacity of a child in a static manner, not animated, /// consider [RenderOpacity] instead. /// /// This getter cannot be read until the value has been set. It should be set /// by the constructor of the class in which this mixin is included. Animation<double> get opacity => _opacity!; Animation<double>? _opacity; set opacity(Animation<double> value) { if (_opacity == value) { return; } if (attached && _opacity != null) { opacity.removeListener(_updateOpacity); } _opacity = value; if (attached) { opacity.addListener(_updateOpacity); } _updateOpacity(); } /// Whether child semantics are included regardless of the opacity. /// /// If false, semantics are excluded when [opacity] is 0.0. /// /// Defaults to false. /// /// This getter cannot be read until the value has been set. It should be set /// by the constructor of the class in which this mixin is included. bool get alwaysIncludeSemantics => _alwaysIncludeSemantics!; bool? _alwaysIncludeSemantics; set alwaysIncludeSemantics(bool value) { if (value == _alwaysIncludeSemantics) { return; } _alwaysIncludeSemantics = value; markNeedsSemanticsUpdate(); } @override void attach(PipelineOwner owner) { super.attach(owner); opacity.addListener(_updateOpacity); _updateOpacity(); // in case it changed while we weren't listening } @override void detach() { opacity.removeListener(_updateOpacity); super.detach(); } void _updateOpacity() { final int? oldAlpha = _alpha; _alpha = ui.Color.getAlphaFromOpacity(opacity.value); if (oldAlpha != _alpha) { final bool? wasRepaintBoundary = _currentlyIsRepaintBoundary; _currentlyIsRepaintBoundary = _alpha! > 0; if (child != null && wasRepaintBoundary != _currentlyIsRepaintBoundary) { markNeedsCompositingBitsUpdate(); } markNeedsCompositedLayerUpdate(); if (oldAlpha == 0 || _alpha == 0) { markNeedsSemanticsUpdate(); } } } @override bool paintsChild(RenderObject child) { assert(child.parent == this); return opacity.value > 0; } @override void paint(PaintingContext context, Offset offset) { if (_alpha == 0) { return; } super.paint(context, offset); } @override void visitChildrenForSemantics(RenderObjectVisitor visitor) { if (child != null && (_alpha != 0 || alwaysIncludeSemantics)) { visitor(child!); } } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<Animation<double>>('opacity', opacity)); properties.add(FlagProperty('alwaysIncludeSemantics', value: alwaysIncludeSemantics, ifTrue: 'alwaysIncludeSemantics')); } } /// Makes its child partially transparent, driven from an [Animation]. /// /// This is a variant of [RenderOpacity] that uses an [Animation<double>] rather /// than a [double] to control the opacity. class RenderAnimatedOpacity extends RenderProxyBox with RenderAnimatedOpacityMixin<RenderBox> { /// Creates a partially transparent render object. RenderAnimatedOpacity({ required Animation<double> opacity, bool alwaysIncludeSemantics = false, RenderBox? child, }) : super(child) { this.opacity = opacity; this.alwaysIncludeSemantics = alwaysIncludeSemantics; } } /// Signature for a function that creates a [Shader] for a given [Rect]. /// /// Used by [RenderShaderMask] and the [ShaderMask] widget. typedef ShaderCallback = Shader Function(Rect bounds); /// Applies a mask generated by a [Shader] to its child. /// /// For example, [RenderShaderMask] can be used to gradually fade out the edge /// of a child by using a [ui.Gradient.linear] mask. class RenderShaderMask extends RenderProxyBox { /// Creates a render object that applies a mask generated by a [Shader] to its child. RenderShaderMask({ RenderBox? child, required ShaderCallback shaderCallback, BlendMode blendMode = BlendMode.modulate, }) : _shaderCallback = shaderCallback, _blendMode = blendMode, super(child); @override ShaderMaskLayer? get layer => super.layer as ShaderMaskLayer?; /// Called to creates the [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. /// /// The rectangle will always be at the origin when called by /// [RenderShaderMask]. // TODO(abarth): Use the delegate pattern here to avoid generating spurious // repaints when the ShaderCallback changes identity. ShaderCallback get shaderCallback => _shaderCallback; ShaderCallback _shaderCallback; set shaderCallback(ShaderCallback value) { if (_shaderCallback == value) { return; } _shaderCallback = value; markNeedsPaint(); } /// 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. BlendMode get blendMode => _blendMode; BlendMode _blendMode; set blendMode(BlendMode value) { if (_blendMode == value) { return; } _blendMode = value; markNeedsPaint(); } @override bool get alwaysNeedsCompositing => child != null; @override void paint(PaintingContext context, Offset offset) { if (child != null) { assert(needsCompositing); layer ??= ShaderMaskLayer(); layer! ..shader = _shaderCallback(Offset.zero & size) ..maskRect = offset & size ..blendMode = _blendMode; context.pushLayer(layer!, super.paint, offset); assert(() { layer!.debugCreator = debugCreator; return true; }()); } else { layer = null; } } } /// Applies a filter to the existing painted content and then paints [child]. /// /// This effect is relatively expensive, especially if the filter is non-local, /// such as a blur. class RenderBackdropFilter extends RenderProxyBox { /// Creates a backdrop filter. // /// The [blendMode] argument defaults to [BlendMode.srcOver]. RenderBackdropFilter({ RenderBox? child, required ui.ImageFilter filter, BlendMode blendMode = BlendMode.srcOver }) : _filter = filter, _blendMode = blendMode, super(child); @override BackdropFilterLayer? get layer => super.layer as BackdropFilterLayer?; /// The image filter to apply to the existing painted content before painting /// the child. /// /// For example, consider using [ui.ImageFilter.blur] to create a backdrop /// blur effect. ui.ImageFilter get filter => _filter; ui.ImageFilter _filter; set filter(ui.ImageFilter value) { if (_filter == value) { return; } _filter = value; markNeedsPaint(); } /// The blend mode to use to apply the filtered background content onto the background /// surface. /// /// {@macro flutter.widgets.BackdropFilter.blendMode} BlendMode get blendMode => _blendMode; BlendMode _blendMode; set blendMode(BlendMode value) { if (_blendMode == value) { return; } _blendMode = value; markNeedsPaint(); } @override bool get alwaysNeedsCompositing => child != null; @override void paint(PaintingContext context, Offset offset) { if (child != null) { assert(needsCompositing); layer ??= BackdropFilterLayer(); layer!.filter = _filter; layer!.blendMode = _blendMode; context.pushLayer(layer!, super.paint, offset); assert(() { layer!.debugCreator = debugCreator; return true; }()); } else { layer = null; } } } /// An interface for providing custom clips. /// /// This class is used by a number of clip widgets (e.g., [ClipRect] and /// [ClipPath]). /// /// The [getClip] method is called whenever the custom clip needs to be updated. /// /// The [shouldReclip] method is called when a new instance of the class /// is provided, to check if the new instance actually represents different /// information. /// /// The most efficient way to update the clip provided by this class is to /// supply a `reclip` argument to the constructor of the [CustomClipper]. The /// custom object will listen to this animation and update the clip whenever the /// animation ticks, avoiding both the build and layout phases of the pipeline. /// /// See also: /// /// * [ClipRect], which can be customized with a [CustomClipper<Rect>]. /// * [ClipRRect], which can be customized with a [CustomClipper<RRect>]. /// * [ClipOval], which can be customized with a [CustomClipper<Rect>]. /// * [ClipPath], which can be customized with a [CustomClipper<Path>]. /// * [ShapeBorderClipper], for specifying a clip path using a [ShapeBorder]. abstract class CustomClipper<T> extends Listenable { /// Creates a custom clipper. /// /// The clipper will update its clip whenever [reclip] notifies its listeners. const CustomClipper({ Listenable? reclip }) : _reclip = reclip; final Listenable? _reclip; /// Register a closure to be notified when it is time to reclip. /// /// The [CustomClipper] implementation merely forwards to the same method on /// the [Listenable] provided to the constructor in the `reclip` argument, if /// it was not null. @override void addListener(VoidCallback listener) => _reclip?.addListener(listener); /// Remove a previously registered closure from the list of closures that the /// object notifies when it is time to reclip. /// /// The [CustomClipper] implementation merely forwards to the same method on /// the [Listenable] provided to the constructor in the `reclip` argument, if /// it was not null. @override void removeListener(VoidCallback listener) => _reclip?.removeListener(listener); /// Returns a description of the clip given that the render object being /// clipped is of the given size. T getClip(Size size); /// Returns an approximation of the clip returned by [getClip], as /// an axis-aligned Rect. This is used by the semantics layer to /// determine whether widgets should be excluded. /// /// By default, this returns a rectangle that is the same size as /// the RenderObject. If getClip returns a shape that is roughly the /// same size as the RenderObject (e.g. it's a rounded rectangle /// with very small arcs in the corners), then this may be adequate. Rect getApproximateClipRect(Size size) => Offset.zero & size; /// Called whenever a new instance of the custom clipper delegate class is /// provided to the clip object, or any time that a new clip object is created /// with a new instance of the custom clipper delegate class (which amounts to /// the same thing, because the latter is implemented in terms of the former). /// /// If the new instance represents different information than the old /// instance, then the method should return true, otherwise it should return /// false. /// /// If the method returns false, then the [getClip] call might be optimized /// away. /// /// It's possible that the [getClip] method will get called even if /// [shouldReclip] returns false or if the [shouldReclip] method is never /// called at all (e.g. if the box changes size). bool shouldReclip(covariant CustomClipper<T> oldClipper); @override String toString() => objectRuntimeType(this, 'CustomClipper'); } /// A [CustomClipper] that clips to the outer path of a [ShapeBorder]. class ShapeBorderClipper extends CustomClipper<Path> { /// Creates a [ShapeBorder] clipper. /// /// The [textDirection] argument must be provided non-null if [shape] /// has a text direction dependency (for example if it is expressed in terms /// of "start" and "end" instead of "left" and "right"). It may be null if /// the border will not need the text direction to paint itself. const ShapeBorderClipper({ required this.shape, this.textDirection, }); /// The shape border whose outer path this clipper clips to. final ShapeBorder shape; /// The text direction to use for getting the outer path for [shape]. /// /// [ShapeBorder]s can depend on the text direction (e.g having a "dent" /// towards the start of the shape). final TextDirection? textDirection; /// Returns the outer path of [shape] as the clip. @override Path getClip(Size size) { return shape.getOuterPath(Offset.zero & size, textDirection: textDirection); } @override bool shouldReclip(CustomClipper<Path> oldClipper) { if (oldClipper.runtimeType != ShapeBorderClipper) { return true; } final ShapeBorderClipper typedOldClipper = oldClipper as ShapeBorderClipper; return typedOldClipper.shape != shape || typedOldClipper.textDirection != textDirection; } } abstract class _RenderCustomClip<T> extends RenderProxyBox { _RenderCustomClip({ RenderBox? child, CustomClipper<T>? clipper, Clip clipBehavior = Clip.antiAlias, }) : _clipper = clipper, _clipBehavior = clipBehavior, super(child); /// If non-null, determines which clip to use on the child. CustomClipper<T>? get clipper => _clipper; CustomClipper<T>? _clipper; set clipper(CustomClipper<T>? newClipper) { if (_clipper == newClipper) { return; } final CustomClipper<T>? oldClipper = _clipper; _clipper = newClipper; assert(newClipper != null || oldClipper != null); if (newClipper == null || oldClipper == null || newClipper.runtimeType != oldClipper.runtimeType || newClipper.shouldReclip(oldClipper)) { _markNeedsClip(); } if (attached) { oldClipper?.removeListener(_markNeedsClip); newClipper?.addListener(_markNeedsClip); } } @override void attach(PipelineOwner owner) { super.attach(owner); _clipper?.addListener(_markNeedsClip); } @override void detach() { _clipper?.removeListener(_markNeedsClip); super.detach(); } void _markNeedsClip() { _clip = null; markNeedsPaint(); markNeedsSemanticsUpdate(); } T get _defaultClip; T? _clip; Clip get clipBehavior => _clipBehavior; set clipBehavior(Clip value) { if (value != _clipBehavior) { _clipBehavior = value; markNeedsPaint(); } } Clip _clipBehavior; @override void performLayout() { final Size? oldSize = hasSize ? size : null; super.performLayout(); if (oldSize != size) { _clip = null; } } void _updateClip() { _clip ??= _clipper?.getClip(size) ?? _defaultClip; } @override Rect? describeApproximatePaintClip(RenderObject child) { switch (clipBehavior) { case Clip.none: return null; case Clip.hardEdge: case Clip.antiAlias: case Clip.antiAliasWithSaveLayer: return _clipper?.getApproximateClipRect(size) ?? Offset.zero & size; } } Paint? _debugPaint; TextPainter? _debugText; @override void debugPaintSize(PaintingContext context, Offset offset) { assert(() { _debugPaint ??= Paint() ..shader = ui.Gradient.linear( Offset.zero, const Offset(10.0, 10.0), <Color>[const Color(0x00000000), const Color(0xFFFF00FF), const Color(0xFFFF00FF), const Color(0x00000000)], <double>[0.25, 0.25, 0.75, 0.75], TileMode.repeated, ) ..strokeWidth = 2.0 ..style = PaintingStyle.stroke; _debugText ??= TextPainter( text: const TextSpan( text: '✂', style: TextStyle( color: Color(0xFFFF00FF), fontSize: 14.0, ), ), textDirection: TextDirection.rtl, // doesn't matter, it's one character ) ..layout(); return true; }()); } @override void dispose() { _debugText?.dispose(); _debugText = null; super.dispose(); } } /// Clips its child using a rectangle. /// /// By default, [RenderClipRect] prevents its child from painting outside its /// bounds, but the size and location of the clip rect can be customized using a /// custom [clipper]. class RenderClipRect extends _RenderCustomClip<Rect> { /// Creates a rectangular clip. /// /// If [clipper] is null, the clip will match the layout size and position of /// the child. /// /// If [clipBehavior] is [Clip.none], no clipping will be applied. RenderClipRect({ super.child, super.clipper, super.clipBehavior, }); @override Rect get _defaultClip => Offset.zero & size; @override bool hitTest(BoxHitTestResult result, { required Offset position }) { if (_clipper != null) { _updateClip(); assert(_clip != null); if (!_clip!.contains(position)) { return false; } } return super.hitTest(result, position: position); } @override void paint(PaintingContext context, Offset offset) { if (child != null) { if (clipBehavior != Clip.none) { _updateClip(); layer = context.pushClipRect( needsCompositing, offset, _clip!, super.paint, clipBehavior: clipBehavior, oldLayer: layer as ClipRectLayer?, ); } else { context.paintChild(child!, offset); layer = null; } } else { layer = null; } } @override void debugPaintSize(PaintingContext context, Offset offset) { assert(() { if (child != null) { super.debugPaintSize(context, offset); if (clipBehavior != Clip.none) { context.canvas.drawRect(_clip!.shift(offset), _debugPaint!); _debugText!.paint(context.canvas, offset + Offset(_clip!.width / 8.0, -_debugText!.text!.style!.fontSize! * 1.1)); } } return true; }()); } } /// Clips its child using a rounded rectangle. /// /// By default, [RenderClipRRect] 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]. class RenderClipRRect extends _RenderCustomClip<RRect> { /// 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. /// /// If [clipBehavior] is [Clip.none], no clipping will be applied. RenderClipRRect({ super.child, BorderRadiusGeometry borderRadius = BorderRadius.zero, super.clipper, super.clipBehavior, TextDirection? textDirection, }) : _borderRadius = borderRadius, _textDirection = textDirection; /// 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. BorderRadiusGeometry get borderRadius => _borderRadius; BorderRadiusGeometry _borderRadius; set borderRadius(BorderRadiusGeometry value) { if (_borderRadius == value) { return; } _borderRadius = value; _markNeedsClip(); } /// The text direction with which to resolve [borderRadius]. TextDirection? get textDirection => _textDirection; TextDirection? _textDirection; set textDirection(TextDirection? value) { if (_textDirection == value) { return; } _textDirection = value; _markNeedsClip(); } @override RRect get _defaultClip => _borderRadius.resolve(textDirection).toRRect(Offset.zero & size); @override bool hitTest(BoxHitTestResult result, { required Offset position }) { if (_clipper != null) { _updateClip(); assert(_clip != null); if (!_clip!.contains(position)) { return false; } } return super.hitTest(result, position: position); } @override void paint(PaintingContext context, Offset offset) { if (child != null) { if (clipBehavior != Clip.none) { _updateClip(); layer = context.pushClipRRect( needsCompositing, offset, _clip!.outerRect, _clip!, super.paint, clipBehavior: clipBehavior, oldLayer: layer as ClipRRectLayer?, ); } else { context.paintChild(child!, offset); layer = null; } } else { layer = null; } } @override void debugPaintSize(PaintingContext context, Offset offset) { assert(() { if (child != null) { super.debugPaintSize(context, offset); if (clipBehavior != Clip.none) { context.canvas.drawRRect(_clip!.shift(offset), _debugPaint!); _debugText!.paint(context.canvas, offset + Offset(_clip!.tlRadiusX, -_debugText!.text!.style!.fontSize! * 1.1)); } } return true; }()); } } /// Clips its child using an oval. /// /// 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]. class RenderClipOval extends _RenderCustomClip<Rect> { /// Creates an oval-shaped clip. /// /// If [clipper] is null, the oval will be inscribed into the layout size and /// position of the child. /// /// If [clipBehavior] is [Clip.none], no clipping will be applied. RenderClipOval({ super.child, super.clipper, super.clipBehavior, }); Rect? _cachedRect; late Path _cachedPath; Path _getClipPath(Rect rect) { if (rect != _cachedRect) { _cachedRect = rect; _cachedPath = Path()..addOval(_cachedRect!); } return _cachedPath; } @override Rect get _defaultClip => Offset.zero & size; @override bool hitTest(BoxHitTestResult result, { required Offset position }) { _updateClip(); assert(_clip != null); final Offset center = _clip!.center; // convert the position to an offset from the center of the unit circle final Offset offset = Offset( (position.dx - center.dx) / _clip!.width, (position.dy - center.dy) / _clip!.height, ); // check if the point is outside the unit circle if (offset.distanceSquared > 0.25) { // x^2 + y^2 > r^2 return false; } return super.hitTest(result, position: position); } @override void paint(PaintingContext context, Offset offset) { if (child != null) { if (clipBehavior != Clip.none) { _updateClip(); layer = context.pushClipPath( needsCompositing, offset, _clip!, _getClipPath(_clip!), super.paint, clipBehavior: clipBehavior, oldLayer: layer as ClipPathLayer?, ); } else { context.paintChild(child!, offset); layer = null; } } else { layer = null; } } @override void debugPaintSize(PaintingContext context, Offset offset) { assert(() { if (child != null) { super.debugPaintSize(context, offset); if (clipBehavior != Clip.none) { context.canvas.drawPath(_getClipPath(_clip!).shift(offset), _debugPaint!); _debugText!.paint(context.canvas, offset + Offset((_clip!.width - _debugText!.width) / 2.0, -_debugText!.text!.style!.fontSize! * 1.1)); } } return true; }()); } } /// Clips its child using a path. /// /// Takes a delegate whose primary method returns a path that should /// be used to prevent the child from painting outside the path. /// /// Clipping to a path is expensive. Certain shapes have more /// optimized render objects: /// /// * To clip to a rectangle, consider [RenderClipRect]. /// * To clip to an oval or circle, consider [RenderClipOval]. /// * To clip to a rounded rectangle, consider [RenderClipRRect]. class RenderClipPath extends _RenderCustomClip<Path> { /// 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 [RenderClipRect], which can achieve the same effect more /// efficiently. /// /// If [clipBehavior] is [Clip.none], no clipping will be applied. RenderClipPath({ super.child, super.clipper, super.clipBehavior, }); @override Path get _defaultClip => Path()..addRect(Offset.zero & size); @override bool hitTest(BoxHitTestResult result, { required Offset position }) { if (_clipper != null) { _updateClip(); assert(_clip != null); if (!_clip!.contains(position)) { return false; } } return super.hitTest(result, position: position); } @override void paint(PaintingContext context, Offset offset) { if (child != null) { if (clipBehavior != Clip.none) { _updateClip(); layer = context.pushClipPath( needsCompositing, offset, Offset.zero & size, _clip!, super.paint, clipBehavior: clipBehavior, oldLayer: layer as ClipPathLayer?, ); } else { context.paintChild(child!, offset); layer = null; } } else { layer = null; } } @override void debugPaintSize(PaintingContext context, Offset offset) { assert(() { if (child != null) { super.debugPaintSize(context, offset); if (clipBehavior != Clip.none) { context.canvas.drawPath(_clip!.shift(offset), _debugPaint!); _debugText!.paint(context.canvas, offset); } } return true; }()); } } /// A physical model layer casts a shadow based on its [elevation]. /// /// The concrete implementations [RenderPhysicalModel] and [RenderPhysicalShape] /// determine the actual shape of the physical model. abstract class _RenderPhysicalModelBase<T> extends _RenderCustomClip<T> { /// The [elevation] parameter must be non-negative. _RenderPhysicalModelBase({ required super.child, required double elevation, required Color color, required Color shadowColor, super.clipBehavior = Clip.none, super.clipper, }) : assert(elevation >= 0.0), _elevation = elevation, _color = color, _shadowColor = shadowColor; /// The z-coordinate relative to the parent at which to place this material. /// /// The value is non-negative. /// /// If [debugDisableShadows] is set, this value is ignored and no shadow is /// drawn (an outline is rendered instead). double get elevation => _elevation; double _elevation; set elevation(double value) { assert(value >= 0.0); if (elevation == value) { return; } final bool didNeedCompositing = alwaysNeedsCompositing; _elevation = value; if (didNeedCompositing != alwaysNeedsCompositing) { markNeedsCompositingBitsUpdate(); } markNeedsPaint(); } /// The shadow color. Color get shadowColor => _shadowColor; Color _shadowColor; set shadowColor(Color value) { if (shadowColor == value) { return; } _shadowColor = value; markNeedsPaint(); } /// The background color. Color get color => _color; Color _color; set color(Color value) { if (color == value) { return; } _color = value; markNeedsPaint(); } @override void describeSemanticsConfiguration(SemanticsConfiguration config) { super.describeSemanticsConfiguration(config); config.elevation = elevation; } @override void debugFillProperties(DiagnosticPropertiesBuilder description) { super.debugFillProperties(description); description.add(DoubleProperty('elevation', elevation)); description.add(ColorProperty('color', color)); description.add(ColorProperty('shadowColor', color)); } } /// Creates a physical model layer that clips its child to a rounded /// rectangle. /// /// A physical model layer casts a shadow based on its [elevation]. class RenderPhysicalModel extends _RenderPhysicalModelBase<RRect> { /// Creates a rounded-rectangular clip. /// /// The [color] is required. /// /// The [elevation] parameter must be non-negative. RenderPhysicalModel({ super.child, BoxShape shape = BoxShape.rectangle, super.clipBehavior, BorderRadius? borderRadius, super.elevation = 0.0, required super.color, super.shadowColor = const Color(0xFF000000), }) : assert(elevation >= 0.0), _shape = shape, _borderRadius = borderRadius; /// The shape of the layer. /// /// Defaults to [BoxShape.rectangle]. The [borderRadius] affects the corners /// of the rectangle. BoxShape get shape => _shape; BoxShape _shape; set shape(BoxShape value) { if (shape == value) { return; } _shape = value; _markNeedsClip(); } /// The border radius of the rounded corners. /// /// Values are clamped so that horizontal and vertical radii sums do not /// exceed width/height. /// /// This property is ignored if the [shape] is not [BoxShape.rectangle]. /// /// The value null is treated like [BorderRadius.zero]. BorderRadius? get borderRadius => _borderRadius; BorderRadius? _borderRadius; set borderRadius(BorderRadius? value) { if (borderRadius == value) { return; } _borderRadius = value; _markNeedsClip(); } @override RRect get _defaultClip { assert(hasSize); final Rect rect = Offset.zero & size; return switch (_shape) { BoxShape.rectangle => (borderRadius ?? BorderRadius.zero).toRRect(rect), BoxShape.circle => RRect.fromRectXY(rect, rect.width / 2, rect.height / 2), }; } @override bool hitTest(BoxHitTestResult result, { required Offset position }) { if (_clipper != null) { _updateClip(); assert(_clip != null); if (!_clip!.contains(position)) { return false; } } return super.hitTest(result, position: position); } @override void paint(PaintingContext context, Offset offset) { if (child == null) { layer = null; return; } _updateClip(); final RRect offsetRRect = _clip!.shift(offset); final Path offsetRRectAsPath = Path()..addRRect(offsetRRect); bool paintShadows = true; assert(() { if (debugDisableShadows) { if (elevation > 0.0) { context.canvas.drawRRect( offsetRRect, Paint() ..color = shadowColor ..style = PaintingStyle.stroke ..strokeWidth = elevation * 2.0, ); } paintShadows = false; } return true; }()); final Canvas canvas = context.canvas; if (elevation != 0.0 && paintShadows) { canvas.drawShadow( offsetRRectAsPath, shadowColor, elevation, color.alpha != 0xFF, ); } final bool usesSaveLayer = clipBehavior == Clip.antiAliasWithSaveLayer; if (!usesSaveLayer) { canvas.drawRRect( offsetRRect, Paint()..color = color ); } layer = context.pushClipRRect( needsCompositing, offset, Offset.zero & size, _clip!, (PaintingContext context, Offset offset) { if (usesSaveLayer) { // If we want to avoid the bleeding edge artifact // (https://github.com/flutter/flutter/issues/18057#issue-328003931) // using saveLayer, we have to call drawPaint instead of drawPath as // anti-aliased drawPath will always have such artifacts. context.canvas.drawPaint( Paint()..color = color); } super.paint(context, offset); }, oldLayer: layer as ClipRRectLayer?, clipBehavior: clipBehavior, ); assert(() { layer?.debugCreator = debugCreator; return true; }()); } @override void debugFillProperties(DiagnosticPropertiesBuilder description) { super.debugFillProperties(description); description.add(DiagnosticsProperty<BoxShape>('shape', shape)); description.add(DiagnosticsProperty<BorderRadius>('borderRadius', borderRadius)); } } /// Creates a physical shape layer that clips its child to a [Path]. /// /// A physical shape layer casts a shadow based on its [elevation]. /// /// See also: /// /// * [RenderPhysicalModel], which is optimized for rounded rectangles and /// circles. class RenderPhysicalShape extends _RenderPhysicalModelBase<Path> { /// Creates an arbitrary shape clip. /// /// The [color] and [clipper] parameters are required. /// /// The [elevation] parameter must be non-negative. RenderPhysicalShape({ super.child, required CustomClipper<Path> super.clipper, super.clipBehavior, super.elevation = 0.0, required super.color, super.shadowColor = const Color(0xFF000000), }) : assert(elevation >= 0.0); @override Path get _defaultClip => Path()..addRect(Offset.zero & size); @override bool hitTest(BoxHitTestResult result, { required Offset position }) { if (_clipper != null) { _updateClip(); assert(_clip != null); if (!_clip!.contains(position)) { return false; } } return super.hitTest(result, position: position); } @override void paint(PaintingContext context, Offset offset) { if (child == null) { layer = null; return; } _updateClip(); final Path offsetPath = _clip!.shift(offset); bool paintShadows = true; assert(() { if (debugDisableShadows) { if (elevation > 0.0) { context.canvas.drawPath( offsetPath, Paint() ..color = shadowColor ..style = PaintingStyle.stroke ..strokeWidth = elevation * 2.0, ); } paintShadows = false; } return true; }()); final Canvas canvas = context.canvas; if (elevation != 0.0 && paintShadows) { canvas.drawShadow( offsetPath, shadowColor, elevation, color.alpha != 0xFF, ); } final bool usesSaveLayer = clipBehavior == Clip.antiAliasWithSaveLayer; if (!usesSaveLayer) { canvas.drawPath( offsetPath, Paint()..color = color ); } layer = context.pushClipPath( needsCompositing, offset, Offset.zero & size, _clip!, (PaintingContext context, Offset offset) { if (usesSaveLayer) { // If we want to avoid the bleeding edge artifact // (https://github.com/flutter/flutter/issues/18057#issue-328003931) // using saveLayer, we have to call drawPaint instead of drawPath as // anti-aliased drawPath will always have such artifacts. context.canvas.drawPaint( Paint()..color = color); } super.paint(context, offset); }, oldLayer: layer as ClipPathLayer?, clipBehavior: clipBehavior, ); assert(() { layer?.debugCreator = debugCreator; return true; }()); } @override void debugFillProperties(DiagnosticPropertiesBuilder description) { super.debugFillProperties(description); description.add(DiagnosticsProperty<CustomClipper<Path>>('clipper', clipper)); } } /// Where to paint a box decoration. enum DecorationPosition { /// Paint the box decoration behind the children. background, /// Paint the box decoration in front of the children. foreground, } /// Paints a [Decoration] either before or after its child paints. class RenderDecoratedBox extends RenderProxyBox { /// Creates a decorated box. /// /// The [decoration], [position], and [configuration] arguments must not be /// null. By default the decoration paints behind the child. /// /// The [ImageConfiguration] will be passed to the decoration (with the size /// filled in) to let it resolve images. RenderDecoratedBox({ required Decoration decoration, DecorationPosition position = DecorationPosition.background, ImageConfiguration configuration = ImageConfiguration.empty, RenderBox? child, }) : _decoration = decoration, _position = position, _configuration = configuration, super(child); BoxPainter? _painter; /// What decoration to paint. /// /// Commonly a [BoxDecoration]. Decoration get decoration => _decoration; Decoration _decoration; set decoration(Decoration value) { if (value == _decoration) { return; } _painter?.dispose(); _painter = null; _decoration = value; markNeedsPaint(); } /// Whether to paint the box decoration behind or in front of the child. DecorationPosition get position => _position; DecorationPosition _position; set position(DecorationPosition value) { if (value == _position) { return; } _position = value; markNeedsPaint(); } /// The settings to pass to the decoration when painting, so that it can /// resolve images appropriately. See [ImageProvider.resolve] and /// [BoxPainter.paint]. /// /// The [ImageConfiguration.textDirection] field is also used by /// direction-sensitive [Decoration]s for painting and hit-testing. ImageConfiguration get configuration => _configuration; ImageConfiguration _configuration; set configuration(ImageConfiguration value) { if (value == _configuration) { return; } _configuration = value; markNeedsPaint(); } @override void detach() { _painter?.dispose(); _painter = null; super.detach(); // Since we're disposing of our painter, we won't receive change // notifications. We mark ourselves as needing paint so that we will // resubscribe to change notifications. If we didn't do this, then, for // example, animated GIFs would stop animating when a DecoratedBox gets // moved around the tree due to GlobalKey reparenting. markNeedsPaint(); } @override void dispose() { _painter?.dispose(); super.dispose(); } @override bool hitTestSelf(Offset position) { return _decoration.hitTest(size, position, textDirection: configuration.textDirection); } @override void paint(PaintingContext context, Offset offset) { _painter ??= _decoration.createBoxPainter(markNeedsPaint); final ImageConfiguration filledConfiguration = configuration.copyWith(size: size); if (position == DecorationPosition.background) { int? debugSaveCount; assert(() { debugSaveCount = context.canvas.getSaveCount(); return true; }()); _painter!.paint(context.canvas, offset, filledConfiguration); assert(() { if (debugSaveCount != context.canvas.getSaveCount()) { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('${_decoration.runtimeType} painter had mismatching save and restore calls.'), ErrorDescription( 'Before painting the decoration, the canvas save count was $debugSaveCount. ' 'After painting it, the canvas save count was ${context.canvas.getSaveCount()}. ' 'Every call to save() or saveLayer() must be matched by a call to restore().', ), DiagnosticsProperty<Decoration>('The decoration was', decoration, style: DiagnosticsTreeStyle.errorProperty), DiagnosticsProperty<BoxPainter>('The painter was', _painter, style: DiagnosticsTreeStyle.errorProperty), ]); } return true; }()); if (decoration.isComplex) { context.setIsComplexHint(); } } super.paint(context, offset); if (position == DecorationPosition.foreground) { _painter!.paint(context.canvas, offset, filledConfiguration); if (decoration.isComplex) { context.setIsComplexHint(); } } } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(_decoration.toDiagnosticsNode(name: 'decoration')); properties.add(DiagnosticsProperty<ImageConfiguration>('configuration', configuration)); } } /// Applies a transformation before painting its child. class RenderTransform extends RenderProxyBox { /// Creates a render object that transforms its child. RenderTransform({ required Matrix4 transform, Offset? origin, AlignmentGeometry? alignment, TextDirection? textDirection, this.transformHitTests = true, FilterQuality? filterQuality, RenderBox? child, }) : super(child) { this.transform = transform; this.alignment = alignment; this.textDirection = textDirection; this.filterQuality = filterQuality; this.origin = origin; } /// The origin of the coordinate system (relative to the upper left corner of /// this render object) in which to apply the matrix. /// /// Setting an origin is equivalent to conjugating the transform matrix by a /// translation. This property is provided just for convenience. Offset? get origin => _origin; Offset? _origin; set origin(Offset? value) { if (_origin == value) { return; } _origin = value; markNeedsPaint(); markNeedsSemanticsUpdate(); } /// The alignment of the origin, relative to the size of the box. /// /// This is equivalent to setting an origin based on the size of the box. /// If it is specified at the same time as an offset, both are applied. /// /// An [AlignmentDirectional.centerStart] value is the same as an [Alignment] /// whose [Alignment.x] value is `-1.0` if [textDirection] is /// [TextDirection.ltr], and `1.0` if [textDirection] is [TextDirection.rtl]. /// Similarly [AlignmentDirectional.centerEnd] is the same as an [Alignment] /// whose [Alignment.x] value is `1.0` if [textDirection] is /// [TextDirection.ltr], and `-1.0` if [textDirection] is [TextDirection.rtl]. AlignmentGeometry? get alignment => _alignment; AlignmentGeometry? _alignment; set alignment(AlignmentGeometry? value) { if (_alignment == value) { return; } _alignment = value; markNeedsPaint(); markNeedsSemanticsUpdate(); } /// The text direction with which to resolve [alignment]. /// /// This may be changed to null, but only after [alignment] has been changed /// to a value that does not depend on the direction. TextDirection? get textDirection => _textDirection; TextDirection? _textDirection; set textDirection(TextDirection? value) { if (_textDirection == value) { return; } _textDirection = value; markNeedsPaint(); markNeedsSemanticsUpdate(); } @override bool get alwaysNeedsCompositing => child != null && _filterQuality != null; /// When set to true, hit tests are performed based on the position of the /// child as it is painted. When set to false, hit tests are performed /// ignoring the transformation. /// /// [applyPaintTransform], and therefore [localToGlobal] and [globalToLocal], /// always honor the transformation, regardless of the value of this property. bool transformHitTests; Matrix4? _transform; /// The matrix to transform the child by during painting. The provided value /// is copied on assignment. /// /// There is no getter for [transform], because [Matrix4] is mutable, and /// mutations outside of the control of the render object could not reliably /// be reflected in the rendering. set transform(Matrix4 value) { // ignore: avoid_setters_without_getters if (_transform == value) { return; } _transform = Matrix4.copy(value); markNeedsPaint(); markNeedsSemanticsUpdate(); } /// The filter quality with which to apply the transform as a bitmap operation. /// /// {@macro flutter.widgets.Transform.optional.FilterQuality} FilterQuality? get filterQuality => _filterQuality; FilterQuality? _filterQuality; set filterQuality(FilterQuality? value) { if (_filterQuality == value) { return; } final bool didNeedCompositing = alwaysNeedsCompositing; _filterQuality = value; if (didNeedCompositing != alwaysNeedsCompositing) { markNeedsCompositingBitsUpdate(); } markNeedsPaint(); } /// Sets the transform to the identity matrix. void setIdentity() { _transform!.setIdentity(); markNeedsPaint(); markNeedsSemanticsUpdate(); } /// Concatenates a rotation about the x axis into the transform. void rotateX(double radians) { _transform!.rotateX(radians); markNeedsPaint(); markNeedsSemanticsUpdate(); } /// Concatenates a rotation about the y axis into the transform. void rotateY(double radians) { _transform!.rotateY(radians); markNeedsPaint(); markNeedsSemanticsUpdate(); } /// Concatenates a rotation about the z axis into the transform. void rotateZ(double radians) { _transform!.rotateZ(radians); markNeedsPaint(); markNeedsSemanticsUpdate(); } /// Concatenates a translation by (x, y, z) into the transform. void translate(double x, [ double y = 0.0, double z = 0.0 ]) { _transform!.translate(x, y, z); markNeedsPaint(); markNeedsSemanticsUpdate(); } /// Concatenates a scale into the transform. void scale(double x, [ double? y, double? z ]) { _transform!.scale(x, y, z); markNeedsPaint(); markNeedsSemanticsUpdate(); } Matrix4? get _effectiveTransform { final Alignment? resolvedAlignment = alignment?.resolve(textDirection); if (_origin == null && resolvedAlignment == null) { return _transform; } final Matrix4 result = Matrix4.identity(); if (_origin != null) { result.translate(_origin!.dx, _origin!.dy); } Offset? translation; if (resolvedAlignment != null) { translation = resolvedAlignment.alongSize(size); result.translate(translation.dx, translation.dy); } result.multiply(_transform!); if (resolvedAlignment != null) { result.translate(-translation!.dx, -translation.dy); } if (_origin != null) { result.translate(-_origin!.dx, -_origin!.dy); } return result; } @override bool hitTest(BoxHitTestResult result, { required Offset position }) { // RenderTransform objects don't check if they are // themselves hit, because it's confusing to think about // how the untransformed size and the child's transformed // position interact. return hitTestChildren(result, position: position); } @override bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { assert(!transformHitTests || _effectiveTransform != null); return result.addWithPaintTransform( transform: transformHitTests ? _effectiveTransform : null, position: position, hitTest: (BoxHitTestResult result, Offset position) { return super.hitTestChildren(result, position: position); }, ); } @override void paint(PaintingContext context, Offset offset) { if (child != null) { final Matrix4 transform = _effectiveTransform!; if (filterQuality == null) { final Offset? childOffset = MatrixUtils.getAsTranslation(transform); if (childOffset == null) { // if the matrix is singular the children would be compressed to a line or // single point, instead short-circuit and paint nothing. final double det = transform.determinant(); if (det == 0 || !det.isFinite) { layer = null; return; } layer = context.pushTransform( needsCompositing, offset, transform, super.paint, oldLayer: layer is TransformLayer ? layer as TransformLayer? : null, ); } else { super.paint(context, offset + childOffset); layer = null; } } else { final Matrix4 effectiveTransform = Matrix4.translationValues(offset.dx, offset.dy, 0.0) ..multiply(transform)..translate(-offset.dx, -offset.dy); final ui.ImageFilter filter = ui.ImageFilter.matrix( effectiveTransform.storage, filterQuality: filterQuality!, ); if (layer is ImageFilterLayer) { final ImageFilterLayer filterLayer = layer! as ImageFilterLayer; filterLayer.imageFilter = filter; } else { layer = ImageFilterLayer(imageFilter: filter); } context.pushLayer(layer!, super.paint, offset); assert(() { layer!.debugCreator = debugCreator; return true; }()); } } } @override void applyPaintTransform(RenderBox child, Matrix4 transform) { transform.multiply(_effectiveTransform!); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(TransformProperty('transform matrix', _transform)); properties.add(DiagnosticsProperty<Offset>('origin', origin)); properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment)); properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null)); properties.add(DiagnosticsProperty<bool>('transformHitTests', transformHitTests)); } } /// Scales and positions its child within itself according to [fit]. class RenderFittedBox extends RenderProxyBox { /// Scales and positions its child within itself. RenderFittedBox({ BoxFit fit = BoxFit.contain, AlignmentGeometry alignment = Alignment.center, TextDirection? textDirection, RenderBox? child, Clip clipBehavior = Clip.none, }) : _fit = fit, _alignment = alignment, _textDirection = textDirection, _clipBehavior = clipBehavior, super(child); Alignment? _resolvedAlignment; void _resolve() { if (_resolvedAlignment != null) { return; } _resolvedAlignment = alignment.resolve(textDirection); } void _markNeedResolution() { _resolvedAlignment = null; markNeedsPaint(); } bool _fitAffectsLayout(BoxFit fit) { switch (fit) { case BoxFit.scaleDown: return true; case BoxFit.contain: case BoxFit.cover: case BoxFit.fill: case BoxFit.fitHeight: case BoxFit.fitWidth: case BoxFit.none: return false; } } /// How to inscribe the child into the space allocated during layout. BoxFit get fit => _fit; BoxFit _fit; set fit(BoxFit value) { if (_fit == value) { return; } final BoxFit lastFit = _fit; _fit = value; if (_fitAffectsLayout(lastFit) || _fitAffectsLayout(value)) { markNeedsLayout(); } else { _clearPaintData(); markNeedsPaint(); } } /// How to align the child within its parent's bounds. /// /// An alignment of (0.0, 0.0) aligns the child to the top-left corner of its /// parent's bounds. An alignment of (1.0, 0.5) aligns the child to the middle /// of the right edge of its parent's bounds. /// /// If this is set to an [AlignmentDirectional] object, then /// [textDirection] must not be null. AlignmentGeometry get alignment => _alignment; AlignmentGeometry _alignment; set alignment(AlignmentGeometry value) { if (_alignment == value) { return; } _alignment = value; _clearPaintData(); _markNeedResolution(); } /// The text direction with which to resolve [alignment]. /// /// This may be changed to null, but only after [alignment] has been changed /// to a value that does not depend on the direction. TextDirection? get textDirection => _textDirection; TextDirection? _textDirection; set textDirection(TextDirection? value) { if (_textDirection == value) { return; } _textDirection = value; _clearPaintData(); _markNeedResolution(); } // TODO(ianh): The intrinsic dimensions of this box are wrong. @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { if (child != null) { final Size childSize = child!.getDryLayout(const BoxConstraints()); // During [RenderObject.debugCheckingIntrinsics] a child that doesn't // support dry layout may provide us with an invalid size that triggers // assertions if we try to work with it. Instead of throwing, we bail // out early in that case. bool invalidChildSize = false; assert(() { if (RenderObject.debugCheckingIntrinsics && childSize.width * childSize.height == 0.0) { invalidChildSize = true; } return true; }()); if (invalidChildSize) { assert(debugCannotComputeDryLayout( reason: 'Child provided invalid size of $childSize.', )); return Size.zero; } switch (fit) { case BoxFit.scaleDown: final BoxConstraints sizeConstraints = constraints.loosen(); final Size unconstrainedSize = sizeConstraints.constrainSizeAndAttemptToPreserveAspectRatio(childSize); return constraints.constrain(unconstrainedSize); case BoxFit.contain: case BoxFit.cover: case BoxFit.fill: case BoxFit.fitHeight: case BoxFit.fitWidth: case BoxFit.none: return constraints.constrainSizeAndAttemptToPreserveAspectRatio(childSize); } } else { return constraints.smallest; } } @override void performLayout() { if (child != null) { child!.layout(const BoxConstraints(), parentUsesSize: true); switch (fit) { case BoxFit.scaleDown: final BoxConstraints sizeConstraints = constraints.loosen(); final Size unconstrainedSize = sizeConstraints.constrainSizeAndAttemptToPreserveAspectRatio(child!.size); size = constraints.constrain(unconstrainedSize); case BoxFit.contain: case BoxFit.cover: case BoxFit.fill: case BoxFit.fitHeight: case BoxFit.fitWidth: case BoxFit.none: size = constraints.constrainSizeAndAttemptToPreserveAspectRatio(child!.size); } _clearPaintData(); } else { size = constraints.smallest; } } bool? _hasVisualOverflow; Matrix4? _transform; /// {@macro flutter.material.Material.clipBehavior} /// /// Defaults to [Clip.none]. Clip get clipBehavior => _clipBehavior; Clip _clipBehavior = Clip.none; set clipBehavior(Clip value) { if (value != _clipBehavior) { _clipBehavior = value; markNeedsPaint(); markNeedsSemanticsUpdate(); } } void _clearPaintData() { _hasVisualOverflow = null; _transform = null; } void _updatePaintData() { if (_transform != null) { return; } if (child == null) { _hasVisualOverflow = false; _transform = Matrix4.identity(); } else { _resolve(); final Size childSize = child!.size; final FittedSizes sizes = applyBoxFit(_fit, childSize, size); final double scaleX = sizes.destination.width / sizes.source.width; final double scaleY = sizes.destination.height / sizes.source.height; final Rect sourceRect = _resolvedAlignment!.inscribe(sizes.source, Offset.zero & childSize); final Rect destinationRect = _resolvedAlignment!.inscribe(sizes.destination, Offset.zero & size); _hasVisualOverflow = sourceRect.width < childSize.width || sourceRect.height < childSize.height; assert(scaleX.isFinite && scaleY.isFinite); _transform = Matrix4.translationValues(destinationRect.left, destinationRect.top, 0.0) ..scale(scaleX, scaleY, 1.0) ..translate(-sourceRect.left, -sourceRect.top); assert(_transform!.storage.every((double value) => value.isFinite)); } } TransformLayer? _paintChildWithTransform(PaintingContext context, Offset offset) { final Offset? childOffset = MatrixUtils.getAsTranslation(_transform!); if (childOffset == null) { return context.pushTransform( needsCompositing, offset, _transform!, super.paint, oldLayer: layer is TransformLayer ? layer! as TransformLayer : null, ); } else { super.paint(context, offset + childOffset); } return null; } @override void paint(PaintingContext context, Offset offset) { if (child == null || size.isEmpty || child!.size.isEmpty) { return; } _updatePaintData(); assert(child != null); if (_hasVisualOverflow! && clipBehavior != Clip.none) { layer = context.pushClipRect( needsCompositing, offset, Offset.zero & size, _paintChildWithTransform, oldLayer: layer is ClipRectLayer ? layer! as ClipRectLayer : null, clipBehavior: clipBehavior, ); } else { layer = _paintChildWithTransform(context, offset); } } @override bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { if (size.isEmpty || (child?.size.isEmpty ?? false)) { return false; } _updatePaintData(); return result.addWithPaintTransform( transform: _transform, position: position, hitTest: (BoxHitTestResult result, Offset position) { return super.hitTestChildren(result, position: position); }, ); } @override bool paintsChild(RenderBox child) { assert(child.parent == this); return !size.isEmpty && !child.size.isEmpty; } @override void applyPaintTransform(RenderBox child, Matrix4 transform) { if (!paintsChild(child)) { transform.setZero(); } else { _updatePaintData(); transform.multiply(_transform!); } } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(EnumProperty<BoxFit>('fit', fit)); properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment)); properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null)); } } /// Applies a translation transformation before painting its child. /// /// The translation is expressed as an [Offset] scaled to the child's size. For /// example, an [Offset] with a `dx` of 0.25 will result in a horizontal /// translation of one quarter the width of the child. /// /// Hit tests will only be detected inside the bounds of the /// [RenderFractionalTranslation], even if the contents are offset such that /// they overflow. class RenderFractionalTranslation extends RenderProxyBox { /// Creates a render object that translates its child's painting. RenderFractionalTranslation({ required Offset translation, this.transformHitTests = true, RenderBox? child, }) : _translation = translation, super(child); /// The translation to apply to the child, scaled to the child's size. /// /// For example, an [Offset] with a `dx` of 0.25 will result in a horizontal /// translation of one quarter the width of the child. Offset get translation => _translation; Offset _translation; set translation(Offset value) { if (_translation == value) { return; } _translation = value; markNeedsPaint(); markNeedsSemanticsUpdate(); } @override bool hitTest(BoxHitTestResult result, { required Offset position }) { // RenderFractionalTranslation objects don't check if they are // themselves hit, because it's confusing to think about // how the untransformed size and the child's transformed // position interact. return hitTestChildren(result, position: position); } /// When set to true, hit tests are performed based on the position of the /// child as it is painted. When set to false, hit tests are performed /// ignoring the transformation. /// /// applyPaintTransform(), and therefore localToGlobal() and globalToLocal(), /// always honor the transformation, regardless of the value of this property. bool transformHitTests; @override bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { assert(!debugNeedsLayout); return result.addWithPaintOffset( offset: transformHitTests ? Offset(translation.dx * size.width, translation.dy * size.height) : null, position: position, hitTest: (BoxHitTestResult result, Offset position) { return super.hitTestChildren(result, position: position); }, ); } @override void paint(PaintingContext context, Offset offset) { assert(!debugNeedsLayout); if (child != null) { super.paint(context, Offset( offset.dx + translation.dx * size.width, offset.dy + translation.dy * size.height, )); } } @override void applyPaintTransform(RenderBox child, Matrix4 transform) { transform.translate( translation.dx * size.width, translation.dy * size.height, ); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<Offset>('translation', translation)); properties.add(DiagnosticsProperty<bool>('transformHitTests', transformHitTests)); } } /// Signature for listening to [PointerDownEvent] events. /// /// Used by [Listener] and [RenderPointerListener]. typedef PointerDownEventListener = void Function(PointerDownEvent event); /// Signature for listening to [PointerMoveEvent] events. /// /// Used by [Listener] and [RenderPointerListener]. typedef PointerMoveEventListener = void Function(PointerMoveEvent event); /// Signature for listening to [PointerUpEvent] events. /// /// Used by [Listener] and [RenderPointerListener]. typedef PointerUpEventListener = void Function(PointerUpEvent event); /// Signature for listening to [PointerCancelEvent] events. /// /// Used by [Listener] and [RenderPointerListener]. typedef PointerCancelEventListener = void Function(PointerCancelEvent event); /// Signature for listening to [PointerPanZoomStartEvent] events. /// /// Used by [Listener] and [RenderPointerListener]. typedef PointerPanZoomStartEventListener = void Function(PointerPanZoomStartEvent event); /// Signature for listening to [PointerPanZoomUpdateEvent] events. /// /// Used by [Listener] and [RenderPointerListener]. typedef PointerPanZoomUpdateEventListener = void Function(PointerPanZoomUpdateEvent event); /// Signature for listening to [PointerPanZoomEndEvent] events. /// /// Used by [Listener] and [RenderPointerListener]. typedef PointerPanZoomEndEventListener = void Function(PointerPanZoomEndEvent event); /// Signature for listening to [PointerSignalEvent] events. /// /// Used by [Listener] and [RenderPointerListener]. typedef PointerSignalEventListener = void Function(PointerSignalEvent event); /// Calls callbacks in response to common pointer events. /// /// It responds to events that can construct gestures, such as when the /// pointer is pointer is pressed and moved, and then released or canceled. /// /// It does not respond to events that are exclusive to mouse, such as when the /// mouse enters and exits a region without pressing any buttons. For /// these events, use [RenderMouseRegion]. /// /// If it has a child, defers to the child for sizing behavior. /// /// If it does not have a child, grows to fit the parent-provided constraints. class RenderPointerListener extends RenderProxyBoxWithHitTestBehavior { /// Creates a render object that forwards pointer events to callbacks. /// /// The [behavior] argument defaults to [HitTestBehavior.deferToChild]. RenderPointerListener({ this.onPointerDown, this.onPointerMove, this.onPointerUp, this.onPointerHover, this.onPointerCancel, this.onPointerPanZoomStart, this.onPointerPanZoomUpdate, this.onPointerPanZoomEnd, this.onPointerSignal, super.behavior, super.child, }); /// Called when a pointer comes into contact with the screen (for touch /// pointers), or has its button pressed (for mouse pointers) at this widget's /// location. PointerDownEventListener? onPointerDown; /// Called when a pointer that triggered an [onPointerDown] changes position. PointerMoveEventListener? onPointerMove; /// Called when a pointer that triggered an [onPointerDown] is no longer in /// contact with the screen. PointerUpEventListener? onPointerUp; /// Called when a pointer that has not an [onPointerDown] changes position. PointerHoverEventListener? onPointerHover; /// Called when the input from a pointer that triggered an [onPointerDown] is /// no longer directed towards this receiver. PointerCancelEventListener? onPointerCancel; /// Called when a pan/zoom begins such as from a trackpad gesture. PointerPanZoomStartEventListener? onPointerPanZoomStart; /// Called when a pan/zoom is updated. PointerPanZoomUpdateEventListener? onPointerPanZoomUpdate; /// Called when a pan/zoom finishes. PointerPanZoomEndEventListener? onPointerPanZoomEnd; /// Called when a pointer signal occurs over this object. PointerSignalEventListener? onPointerSignal; @override Size computeSizeForNoChild(BoxConstraints constraints) { return constraints.biggest; } @override void handleEvent(PointerEvent event, HitTestEntry entry) { assert(debugHandleEvent(event, entry)); if (event is PointerDownEvent) { return onPointerDown?.call(event); } if (event is PointerMoveEvent) { return onPointerMove?.call(event); } if (event is PointerUpEvent) { return onPointerUp?.call(event); } if (event is PointerHoverEvent) { return onPointerHover?.call(event); } if (event is PointerCancelEvent) { return onPointerCancel?.call(event); } if (event is PointerPanZoomStartEvent) { return onPointerPanZoomStart?.call(event); } if (event is PointerPanZoomUpdateEvent) { return onPointerPanZoomUpdate?.call(event); } if (event is PointerPanZoomEndEvent) { return onPointerPanZoomEnd?.call(event); } if (event is PointerSignalEvent) { return onPointerSignal?.call(event); } } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(FlagsSummary<Function?>( 'listeners', <String, Function?>{ 'down': onPointerDown, 'move': onPointerMove, 'up': onPointerUp, 'hover': onPointerHover, 'cancel': onPointerCancel, 'panZoomStart': onPointerPanZoomStart, 'panZoomUpdate': onPointerPanZoomUpdate, 'panZoomEnd': onPointerPanZoomEnd, 'signal': onPointerSignal, }, ifEmpty: '<none>', )); } } /// Calls callbacks in response to pointer events that are exclusive to mice. /// /// It responds to events that are related to hovering, i.e. when the mouse /// enters, exits (with or without pressing buttons), or moves over a region /// without pressing buttons. /// /// It does not respond to common events that construct gestures, such as when /// the pointer is pressed, moved, then released or canceled. For these events, /// use [RenderPointerListener]. /// /// If it has a child, it defers to the child for sizing behavior. /// /// If it does not have a child, it grows to fit the parent-provided constraints. /// /// See also: /// /// * [MouseRegion], a widget that listens to hover events using /// [RenderMouseRegion]. class RenderMouseRegion extends RenderProxyBoxWithHitTestBehavior implements MouseTrackerAnnotation { /// Creates a render object that forwards pointer events to callbacks. /// /// All parameters are optional. By default this method creates an opaque /// mouse region with no callbacks and cursor being [MouseCursor.defer]. RenderMouseRegion({ this.onEnter, this.onHover, this.onExit, MouseCursor cursor = MouseCursor.defer, bool validForMouseTracker = true, bool opaque = true, super.child, HitTestBehavior? hitTestBehavior = HitTestBehavior.opaque, }) : _cursor = cursor, _validForMouseTracker = validForMouseTracker, _opaque = opaque, super(behavior: hitTestBehavior ?? HitTestBehavior.opaque); @override bool hitTest(BoxHitTestResult result, { required Offset position }) { return super.hitTest(result, position: position) && _opaque; } @override void handleEvent(PointerEvent event, HitTestEntry entry) { assert(debugHandleEvent(event, entry)); if (onHover != null && event is PointerHoverEvent) { return onHover!(event); } } /// Whether this object should prevent [RenderMouseRegion]s visually behind it /// from detecting the pointer, thus affecting how their [onHover], [onEnter], /// and [onExit] behave. /// /// If [opaque] is true, this object will absorb the mouse pointer and /// prevent this object's siblings (or any other objects that are not /// ancestors or descendants of this object) from detecting the mouse /// pointer even when the pointer is within their areas. /// /// If [opaque] is false, this object will not affect how [RenderMouseRegion]s /// behind it behave, which will detect the mouse pointer as long as the /// pointer is within their areas. /// /// This defaults to true. bool get opaque => _opaque; bool _opaque; set opaque(bool value) { if (_opaque != value) { _opaque = value; // Trigger [MouseTracker]'s device update to recalculate mouse states. markNeedsPaint(); } } /// How to behave during hit testing. /// /// This defaults to [HitTestBehavior.opaque] if null. HitTestBehavior? get hitTestBehavior => behavior; set hitTestBehavior(HitTestBehavior? value) { final HitTestBehavior newValue = value ?? HitTestBehavior.opaque; if (behavior != newValue) { behavior = newValue; // Trigger [MouseTracker]'s device update to recalculate mouse states. markNeedsPaint(); } } @override PointerEnterEventListener? onEnter; /// Triggered when a pointer has moved onto or within the region without /// buttons pressed. /// /// This callback is not triggered by the movement of the object. PointerHoverEventListener? onHover; @override PointerExitEventListener? onExit; @override MouseCursor get cursor => _cursor; MouseCursor _cursor; set cursor(MouseCursor value) { if (_cursor != value) { _cursor = value; // A repaint is needed in order to trigger a device update of // [MouseTracker] so that this new value can be found. markNeedsPaint(); } } @override bool get validForMouseTracker => _validForMouseTracker; bool _validForMouseTracker; @override void attach(PipelineOwner owner) { super.attach(owner); _validForMouseTracker = true; } @override void detach() { // It's possible that the renderObject be detached during mouse events // dispatching, set the [MouseTrackerAnnotation.validForMouseTracker] false to prevent // the callbacks from being called. _validForMouseTracker = false; super.detach(); } @override Size computeSizeForNoChild(BoxConstraints constraints) { return constraints.biggest; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(FlagsSummary<Function?>( 'listeners', <String, Function?>{ 'enter': onEnter, 'hover': onHover, 'exit': onExit, }, ifEmpty: '<none>', )); properties.add(DiagnosticsProperty<MouseCursor>('cursor', cursor, defaultValue: MouseCursor.defer)); properties.add(DiagnosticsProperty<bool>('opaque', opaque, defaultValue: true)); properties.add(FlagProperty('validForMouseTracker', value: validForMouseTracker, defaultValue: true, ifFalse: 'invalid for MouseTracker')); } } /// Creates a separate display list for its child. /// /// This render object creates a separate display list for its child, which /// can improve performance if the subtree repaints at different times than /// the surrounding parts of the tree. Specifically, when the child does not /// repaint but its parent does, we can re-use the display list we recorded /// previously. Similarly, when the child repaints but the surround tree does /// not, we can re-record its display list without re-recording the display list /// for the surround tree. /// /// In some cases, it is necessary to place _two_ (or more) repaint boundaries /// to get a useful effect. Consider, for example, an e-mail application that /// shows an unread count and a list of e-mails. Whenever a new e-mail comes in, /// the list would update, but so would the unread count. If only one of these /// two parts of the application was behind a repaint boundary, the entire /// application would repaint each time. On the other hand, if both were behind /// a repaint boundary, a new e-mail would only change those two parts of the /// application and the rest of the application would not repaint. /// /// To tell if a particular RenderRepaintBoundary is useful, run your /// application in debug mode, interacting with it in typical ways, and then /// call [debugDumpRenderTree]. Each RenderRepaintBoundary will include the /// ratio of cases where the repaint boundary was useful vs the cases where it /// was not. These counts can also be inspected programmatically using /// [debugAsymmetricPaintCount] and [debugSymmetricPaintCount] respectively. class RenderRepaintBoundary extends RenderProxyBox { /// Creates a repaint boundary around [child]. RenderRepaintBoundary({ RenderBox? child }) : super(child); @override bool get isRepaintBoundary => true; /// Capture an image of the current state of this render object and its /// children. /// /// The returned [ui.Image] has uncompressed raw RGBA bytes in the dimensions /// of the render object, multiplied by the [pixelRatio]. /// /// To use [toImage], the render object must have gone through the paint phase /// (i.e. [debugNeedsPaint] must be false). /// /// The [pixelRatio] describes the scale between the logical pixels and the /// size of the output image. It is independent of the /// [dart:ui.FlutterView.devicePixelRatio] for the device, so specifying 1.0 /// (the default) will give you a 1:1 mapping between logical pixels and the /// output pixels in the image. /// /// {@tool snippet} /// /// The following is an example of how to go from a `GlobalKey` on a /// `RepaintBoundary` to a PNG: /// /// ```dart /// class PngHome extends StatefulWidget { /// const PngHome({super.key}); /// /// @override /// State<PngHome> createState() => _PngHomeState(); /// } /// /// class _PngHomeState extends State<PngHome> { /// GlobalKey globalKey = GlobalKey(); /// /// Future<void> _capturePng() async { /// final RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject()! as RenderRepaintBoundary; /// final ui.Image image = await boundary.toImage(); /// final ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png); /// final Uint8List pngBytes = byteData!.buffer.asUint8List(); /// print(pngBytes); /// } /// /// @override /// Widget build(BuildContext context) { /// return RepaintBoundary( /// key: globalKey, /// child: Center( /// child: TextButton( /// onPressed: _capturePng, /// child: const Text('Hello World', textDirection: TextDirection.ltr), /// ), /// ), /// ); /// } /// } /// ``` /// {@end-tool} /// /// See also: /// /// * [OffsetLayer.toImage] for a similar API at the layer level. /// * [dart:ui.Scene.toImage] for more information about the image returned. Future<ui.Image> toImage({ double pixelRatio = 1.0 }) { assert(!debugNeedsPaint); final OffsetLayer offsetLayer = layer! as OffsetLayer; return offsetLayer.toImage(Offset.zero & size, pixelRatio: pixelRatio); } /// Capture an image of the current state of this render object and its /// children synchronously. /// /// The returned [ui.Image] has uncompressed raw RGBA bytes in the dimensions /// of the render object, multiplied by the [pixelRatio]. /// /// To use [toImageSync], the render object must have gone through the paint phase /// (i.e. [debugNeedsPaint] must be false). /// /// The [pixelRatio] describes the scale between the logical pixels and the /// size of the output image. It is independent of the /// [dart:ui.FlutterView.devicePixelRatio] for the device, so specifying 1.0 /// (the default) will give you a 1:1 mapping between logical pixels and the /// output pixels in the image. /// /// This API functions like [toImage], except that rasterization begins eagerly /// on the raster thread and the image is returned before this is completed. /// /// {@tool snippet} /// /// The following is an example of how to go from a `GlobalKey` on a /// `RepaintBoundary` to an image handle: /// /// ```dart /// class ImageCaptureHome extends StatefulWidget { /// const ImageCaptureHome({super.key}); /// /// @override /// State<ImageCaptureHome> createState() => _ImageCaptureHomeState(); /// } /// /// class _ImageCaptureHomeState extends State<ImageCaptureHome> { /// GlobalKey globalKey = GlobalKey(); /// /// void _captureImage() { /// final RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject()! as RenderRepaintBoundary; /// final ui.Image image = boundary.toImageSync(); /// print('Image dimensions: ${image.width}x${image.height}'); /// } /// /// @override /// Widget build(BuildContext context) { /// return RepaintBoundary( /// key: globalKey, /// child: Center( /// child: TextButton( /// onPressed: _captureImage, /// child: const Text('Hello World', textDirection: TextDirection.ltr), /// ), /// ), /// ); /// } /// } /// ``` /// {@end-tool} /// /// See also: /// /// * [OffsetLayer.toImageSync] for a similar API at the layer level. /// * [dart:ui.Scene.toImageSync] for more information about the image returned. ui.Image toImageSync({ double pixelRatio = 1.0 }) { assert(!debugNeedsPaint); final OffsetLayer offsetLayer = layer! as OffsetLayer; return offsetLayer.toImageSync(Offset.zero & size, pixelRatio: pixelRatio); } /// The number of times that this render object repainted at the same time as /// its parent. Repaint boundaries are only useful when the parent and child /// paint at different times. When both paint at the same time, the repaint /// boundary is redundant, and may be actually making performance worse. /// /// Only valid when asserts are enabled. In release builds, always returns /// zero. /// /// Can be reset using [debugResetMetrics]. See [debugAsymmetricPaintCount] /// for the corresponding count of times where only the parent or only the /// child painted. int get debugSymmetricPaintCount => _debugSymmetricPaintCount; int _debugSymmetricPaintCount = 0; /// The number of times that either this render object repainted without the /// parent being painted, or the parent repainted without this object being /// painted. When a repaint boundary is used at a seam in the render tree /// where the parent tends to repaint at entirely different times than the /// child, it can improve performance by reducing the number of paint /// operations that have to be recorded each frame. /// /// Only valid when asserts are enabled. In release builds, always returns /// zero. /// /// Can be reset using [debugResetMetrics]. See [debugSymmetricPaintCount] for /// the corresponding count of times where both the parent and the child /// painted together. int get debugAsymmetricPaintCount => _debugAsymmetricPaintCount; int _debugAsymmetricPaintCount = 0; /// Resets the [debugSymmetricPaintCount] and [debugAsymmetricPaintCount] /// counts to zero. /// /// Only valid when asserts are enabled. Does nothing in release builds. void debugResetMetrics() { assert(() { _debugSymmetricPaintCount = 0; _debugAsymmetricPaintCount = 0; return true; }()); } @override void debugRegisterRepaintBoundaryPaint({ bool includedParent = true, bool includedChild = false }) { assert(() { if (includedParent && includedChild) { _debugSymmetricPaintCount += 1; } else { _debugAsymmetricPaintCount += 1; } return true; }()); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); bool inReleaseMode = true; assert(() { inReleaseMode = false; if (debugSymmetricPaintCount + debugAsymmetricPaintCount == 0) { properties.add(MessageProperty('usefulness ratio', 'no metrics collected yet (never painted)')); } else { final double fraction = debugAsymmetricPaintCount / (debugSymmetricPaintCount + debugAsymmetricPaintCount); final String diagnosis; if (debugSymmetricPaintCount + debugAsymmetricPaintCount < 5) { diagnosis = 'insufficient data to draw conclusion (less than five repaints)'; } else if (fraction > 0.9) { diagnosis = 'this is an outstandingly useful repaint boundary and should definitely be kept'; } else if (fraction > 0.5) { diagnosis = 'this is a useful repaint boundary and should be kept'; } else if (fraction > 0.30) { diagnosis = 'this repaint boundary is probably useful, but maybe it would be more useful in tandem with adding more repaint boundaries elsewhere'; } else if (fraction > 0.1) { diagnosis = 'this repaint boundary does sometimes show value, though currently not that often'; } else if (debugAsymmetricPaintCount == 0) { diagnosis = 'this repaint boundary is astoundingly ineffectual and should be removed'; } else { diagnosis = 'this repaint boundary is not very effective and should probably be removed'; } properties.add(PercentProperty('metrics', fraction, unit: 'useful', tooltip: '$debugSymmetricPaintCount bad vs $debugAsymmetricPaintCount good')); properties.add(MessageProperty('diagnosis', diagnosis)); } return true; }()); if (inReleaseMode) { properties.add(DiagnosticsNode.message('(run in debug mode to collect repaint boundary statistics)')); } } } /// A render object that is invisible during hit testing. /// /// When [ignoring] is true, this render object (and its subtree) is invisible /// to hit testing. It still consumes space during layout and paints its child /// as usual. It just cannot be the target of located events, because its render /// object returns false from [hitTest]. /// /// ## Semantics /// /// Using this class may also affect how the semantics subtree underneath is /// collected. /// /// {@macro flutter.widgets.IgnorePointer.semantics} /// /// {@macro flutter.widgets.IgnorePointer.ignoringSemantics} /// /// See also: /// /// * [RenderAbsorbPointer], which takes the pointer events but prevents any /// nodes in the subtree from seeing them. class RenderIgnorePointer extends RenderProxyBox { /// Creates a render object that is invisible to hit testing. RenderIgnorePointer({ RenderBox? child, bool ignoring = true, @Deprecated( 'Use ExcludeSemantics or create a custom ignore pointer widget instead. ' 'This feature was deprecated after v3.8.0-12.0.pre.' ) bool? ignoringSemantics, }) : _ignoring = ignoring, _ignoringSemantics = ignoringSemantics, super(child); /// Whether this render object is ignored during hit testing. /// /// Regardless of whether this render object is ignored during hit testing, it /// will still consume space during layout and be visible during painting. /// /// {@macro flutter.widgets.IgnorePointer.semantics} bool get ignoring => _ignoring; bool _ignoring; set ignoring(bool value) { if (value == _ignoring) { return; } _ignoring = value; if (ignoringSemantics == null) { markNeedsSemanticsUpdate(); } } /// Whether the semantics of this render object is ignored when compiling the semantics tree. /// /// {@macro flutter.widgets.IgnorePointer.ignoringSemantics} /// /// See [SemanticsNode] for additional information about the semantics tree. @Deprecated( 'Use ExcludeSemantics or create a custom ignore pointer widget instead. ' 'This feature was deprecated after v3.8.0-12.0.pre.' ) bool? get ignoringSemantics => _ignoringSemantics; bool? _ignoringSemantics; set ignoringSemantics(bool? value) { if (value == _ignoringSemantics) { return; } _ignoringSemantics = value; markNeedsSemanticsUpdate(); } @override bool hitTest(BoxHitTestResult result, { required Offset position }) { return !ignoring && super.hitTest(result, position: position); } @override void visitChildrenForSemantics(RenderObjectVisitor visitor) { if (_ignoringSemantics ?? false) { return; } super.visitChildrenForSemantics(visitor); } @override void describeSemanticsConfiguration(SemanticsConfiguration config) { super.describeSemanticsConfiguration(config); // Do not block user interactions if _ignoringSemantics is false; otherwise, // delegate to _ignoring config.isBlockingUserActions = _ignoring && (_ignoringSemantics ?? true); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<bool>('ignoring', _ignoring)); properties.add( DiagnosticsProperty<bool>( 'ignoringSemantics', _ignoringSemantics, description: _ignoringSemantics == null ? null : 'implicitly $_ignoringSemantics', ), ); } } /// Lays the child out as if it was in the tree, but without painting anything, /// without making the child available for hit testing, and without taking any /// room in the parent. class RenderOffstage extends RenderProxyBox { /// Creates an offstage render object. RenderOffstage({ bool offstage = true, RenderBox? child, }) : _offstage = offstage, super(child); /// Whether the child is hidden from the rest of the tree. /// /// If true, the child is laid out as if it was in the tree, but without /// painting anything, without making the child available for hit testing, and /// without taking any room in the parent. /// /// If false, the child is included in the tree as normal. bool get offstage => _offstage; bool _offstage; set offstage(bool value) { if (value == _offstage) { return; } _offstage = value; markNeedsLayoutForSizedByParentChange(); } @override double computeMinIntrinsicWidth(double height) { if (offstage) { return 0.0; } return super.computeMinIntrinsicWidth(height); } @override double computeMaxIntrinsicWidth(double height) { if (offstage) { return 0.0; } return super.computeMaxIntrinsicWidth(height); } @override double computeMinIntrinsicHeight(double width) { if (offstage) { return 0.0; } return super.computeMinIntrinsicHeight(width); } @override double computeMaxIntrinsicHeight(double width) { if (offstage) { return 0.0; } return super.computeMaxIntrinsicHeight(width); } @override double? computeDistanceToActualBaseline(TextBaseline baseline) { if (offstage) { return null; } return super.computeDistanceToActualBaseline(baseline); } @override bool get sizedByParent => offstage; @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { if (offstage) { return constraints.smallest; } return super.computeDryLayout(constraints); } @override void performResize() { assert(offstage); super.performResize(); } @override void performLayout() { if (offstage) { child?.layout(constraints); } else { super.performLayout(); } } @override bool hitTest(BoxHitTestResult result, { required Offset position }) { return !offstage && super.hitTest(result, position: position); } @override bool paintsChild(RenderBox child) { assert(child.parent == this); return !offstage; } @override void paint(PaintingContext context, Offset offset) { if (offstage) { return; } super.paint(context, offset); } @override void visitChildrenForSemantics(RenderObjectVisitor visitor) { if (offstage) { return; } super.visitChildrenForSemantics(visitor); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<bool>('offstage', offstage)); } @override List<DiagnosticsNode> debugDescribeChildren() { if (child == null) { return <DiagnosticsNode>[]; } return <DiagnosticsNode>[ child!.toDiagnosticsNode( name: 'child', style: offstage ? DiagnosticsTreeStyle.offstage : DiagnosticsTreeStyle.sparse, ), ]; } } /// A render object that absorbs pointers during hit testing. /// /// When [absorbing] is true, this render object prevents its subtree from /// receiving pointer events by terminating hit testing at itself. It still /// consumes space during layout and paints its child as usual. It just prevents /// its children from being the target of located events, because its render /// object returns true from [hitTest]. /// /// ## Semantics /// /// Using this class may also affect how the semantics subtree underneath is /// collected. /// /// {@macro flutter.widgets.AbsorbPointer.semantics} /// /// {@macro flutter.widgets.AbsorbPointer.ignoringSemantics} /// /// See also: /// /// * [RenderIgnorePointer], which has the opposite effect: removing the /// subtree from considering entirely for the purposes of hit testing. class RenderAbsorbPointer extends RenderProxyBox { /// Creates a render object that absorbs pointers during hit testing. RenderAbsorbPointer({ RenderBox? child, bool absorbing = true, @Deprecated( 'Use ExcludeSemantics or create a custom absorb pointer widget instead. ' 'This feature was deprecated after v3.8.0-12.0.pre.' ) bool? ignoringSemantics, }) : _absorbing = absorbing, _ignoringSemantics = ignoringSemantics, super(child); /// Whether this render object absorbs pointers during hit testing. /// /// Regardless of whether this render object absorbs pointers during hit /// testing, it will still consume space during layout and be visible during /// painting. /// /// {@macro flutter.widgets.AbsorbPointer.semantics} bool get absorbing => _absorbing; bool _absorbing; set absorbing(bool value) { if (_absorbing == value) { return; } _absorbing = value; if (ignoringSemantics == null) { markNeedsSemanticsUpdate(); } } /// Whether the semantics of this render object is ignored when compiling the /// semantics tree. /// /// {@macro flutter.widgets.AbsorbPointer.ignoringSemantics} /// /// See [SemanticsNode] for additional information about the semantics tree. @Deprecated( 'Use ExcludeSemantics or create a custom absorb pointer widget instead. ' 'This feature was deprecated after v3.8.0-12.0.pre.' ) bool? get ignoringSemantics => _ignoringSemantics; bool? _ignoringSemantics; set ignoringSemantics(bool? value) { if (value == _ignoringSemantics) { return; } _ignoringSemantics = value; markNeedsSemanticsUpdate(); } @override bool hitTest(BoxHitTestResult result, { required Offset position }) { return absorbing ? size.contains(position) : super.hitTest(result, position: position); } @override void visitChildrenForSemantics(RenderObjectVisitor visitor) { if (_ignoringSemantics ?? false) { return; } super.visitChildrenForSemantics(visitor); } @override void describeSemanticsConfiguration(SemanticsConfiguration config) { super.describeSemanticsConfiguration(config); // Do not block user interactions if _ignoringSemantics is false; otherwise, // delegate to absorbing config.isBlockingUserActions = absorbing && (_ignoringSemantics ?? true); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<bool>('absorbing', absorbing)); properties.add( DiagnosticsProperty<bool>( 'ignoringSemantics', ignoringSemantics, description: ignoringSemantics == null ? null : 'implicitly $ignoringSemantics', ), ); } } /// Holds opaque meta data in the render tree. /// /// Useful for decorating the render tree with information that will be consumed /// later. For example, you could store information in the render tree that will /// be used when the user interacts with the render tree but has no visual /// impact prior to the interaction. class RenderMetaData extends RenderProxyBoxWithHitTestBehavior { /// Creates a render object that hold opaque meta data. /// /// The [behavior] argument defaults to [HitTestBehavior.deferToChild]. RenderMetaData({ this.metaData, super.behavior, super.child, }); /// Opaque meta data ignored by the render tree. dynamic metaData; @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<dynamic>('metaData', metaData)); } } /// Listens for the specified gestures from the semantics server (e.g. /// an accessibility tool). class RenderSemanticsGestureHandler extends RenderProxyBoxWithHitTestBehavior { /// Creates a render object that listens for specific semantic gestures. RenderSemanticsGestureHandler({ super.child, GestureTapCallback? onTap, GestureLongPressCallback? onLongPress, GestureDragUpdateCallback? onHorizontalDragUpdate, GestureDragUpdateCallback? onVerticalDragUpdate, this.scrollFactor = 0.8, super.behavior, }) : _onTap = onTap, _onLongPress = onLongPress, _onHorizontalDragUpdate = onHorizontalDragUpdate, _onVerticalDragUpdate = onVerticalDragUpdate; /// If non-null, the set of actions to allow. Other actions will be omitted, /// even if their callback is provided. /// /// For example, if [onTap] is non-null but [validActions] does not contain /// [SemanticsAction.tap], then the semantic description of this node will /// not claim to support taps. /// /// This is normally used to filter the actions made available by /// [onHorizontalDragUpdate] and [onVerticalDragUpdate]. Normally, these make /// both the right and left, or up and down, actions available. For example, /// if [onHorizontalDragUpdate] is set but [validActions] only contains /// [SemanticsAction.scrollLeft], then the [SemanticsAction.scrollRight] /// action will be omitted. Set<SemanticsAction>? get validActions => _validActions; Set<SemanticsAction>? _validActions; set validActions(Set<SemanticsAction>? value) { if (setEquals<SemanticsAction>(value, _validActions)) { return; } _validActions = value; markNeedsSemanticsUpdate(); } /// Called when the user taps on the render object. GestureTapCallback? get onTap => _onTap; GestureTapCallback? _onTap; set onTap(GestureTapCallback? value) { if (_onTap == value) { return; } final bool hadHandler = _onTap != null; _onTap = value; if ((value != null) != hadHandler) { markNeedsSemanticsUpdate(); } } /// Called when the user presses on the render object for a long period of time. GestureLongPressCallback? get onLongPress => _onLongPress; GestureLongPressCallback? _onLongPress; set onLongPress(GestureLongPressCallback? value) { if (_onLongPress == value) { return; } final bool hadHandler = _onLongPress != null; _onLongPress = value; if ((value != null) != hadHandler) { markNeedsSemanticsUpdate(); } } /// Called when the user scrolls to the left or to the right. GestureDragUpdateCallback? get onHorizontalDragUpdate => _onHorizontalDragUpdate; GestureDragUpdateCallback? _onHorizontalDragUpdate; set onHorizontalDragUpdate(GestureDragUpdateCallback? value) { if (_onHorizontalDragUpdate == value) { return; } final bool hadHandler = _onHorizontalDragUpdate != null; _onHorizontalDragUpdate = value; if ((value != null) != hadHandler) { markNeedsSemanticsUpdate(); } } /// Called when the user scrolls up or down. GestureDragUpdateCallback? get onVerticalDragUpdate => _onVerticalDragUpdate; GestureDragUpdateCallback? _onVerticalDragUpdate; set onVerticalDragUpdate(GestureDragUpdateCallback? value) { if (_onVerticalDragUpdate == value) { return; } final bool hadHandler = _onVerticalDragUpdate != null; _onVerticalDragUpdate = value; if ((value != null) != hadHandler) { markNeedsSemanticsUpdate(); } } /// The fraction of the dimension of this render box to use when /// scrolling. For example, if this is 0.8 and the box is 200 pixels /// wide, then when a left-scroll action is received from the /// accessibility system, it will translate into a 160 pixel /// leftwards drag. double scrollFactor; @override void describeSemanticsConfiguration(SemanticsConfiguration config) { super.describeSemanticsConfiguration(config); if (onTap != null && _isValidAction(SemanticsAction.tap)) { config.onTap = onTap; } if (onLongPress != null && _isValidAction(SemanticsAction.longPress)) { config.onLongPress = onLongPress; } if (onHorizontalDragUpdate != null) { if (_isValidAction(SemanticsAction.scrollRight)) { config.onScrollRight = _performSemanticScrollRight; } if (_isValidAction(SemanticsAction.scrollLeft)) { config.onScrollLeft = _performSemanticScrollLeft; } } if (onVerticalDragUpdate != null) { if (_isValidAction(SemanticsAction.scrollUp)) { config.onScrollUp = _performSemanticScrollUp; } if (_isValidAction(SemanticsAction.scrollDown)) { config.onScrollDown = _performSemanticScrollDown; } } } bool _isValidAction(SemanticsAction action) { return validActions == null || validActions!.contains(action); } void _performSemanticScrollLeft() { if (onHorizontalDragUpdate != null) { final double primaryDelta = size.width * -scrollFactor; onHorizontalDragUpdate!(DragUpdateDetails( delta: Offset(primaryDelta, 0.0), primaryDelta: primaryDelta, globalPosition: localToGlobal(size.center(Offset.zero)), )); } } void _performSemanticScrollRight() { if (onHorizontalDragUpdate != null) { final double primaryDelta = size.width * scrollFactor; onHorizontalDragUpdate!(DragUpdateDetails( delta: Offset(primaryDelta, 0.0), primaryDelta: primaryDelta, globalPosition: localToGlobal(size.center(Offset.zero)), )); } } void _performSemanticScrollUp() { if (onVerticalDragUpdate != null) { final double primaryDelta = size.height * -scrollFactor; onVerticalDragUpdate!(DragUpdateDetails( delta: Offset(0.0, primaryDelta), primaryDelta: primaryDelta, globalPosition: localToGlobal(size.center(Offset.zero)), )); } } void _performSemanticScrollDown() { if (onVerticalDragUpdate != null) { final double primaryDelta = size.height * scrollFactor; onVerticalDragUpdate!(DragUpdateDetails( delta: Offset(0.0, primaryDelta), primaryDelta: primaryDelta, globalPosition: localToGlobal(size.center(Offset.zero)), )); } } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); final List<String> gestures = <String>[ if (onTap != null) 'tap', if (onLongPress != null) 'long press', if (onHorizontalDragUpdate != null) 'horizontal scroll', if (onVerticalDragUpdate != null) 'vertical scroll', ]; if (gestures.isEmpty) { gestures.add('<none>'); } properties.add(IterableProperty<String>('gestures', gestures)); } } /// Add annotations to the [SemanticsNode] for this subtree. class RenderSemanticsAnnotations extends RenderProxyBox { /// Creates a render object that attaches a semantic annotation. /// /// If the [SemanticsProperties.attributedLabel] is not null, the [textDirection] must also not be null. RenderSemanticsAnnotations({ RenderBox? child, required SemanticsProperties properties, bool container = false, bool explicitChildNodes = false, bool excludeSemantics = false, bool blockUserActions = false, TextDirection? textDirection, }) : _container = container, _explicitChildNodes = explicitChildNodes, _excludeSemantics = excludeSemantics, _blockUserActions = blockUserActions, _textDirection = textDirection, _properties = properties, super(child) { _updateAttributedFields(_properties); } /// All of the [SemanticsProperties] for this [RenderSemanticsAnnotations]. SemanticsProperties get properties => _properties; SemanticsProperties _properties; set properties(SemanticsProperties value) { if (_properties == value) { return; } _properties = value; _updateAttributedFields(_properties); markNeedsSemanticsUpdate(); } /// If 'container' is true, this [RenderObject] will introduce a new /// node in the semantics tree. Otherwise, the semantics will be /// merged with the semantics of any ancestors. /// /// Whether descendants of this [RenderObject] can add their semantic information /// to the [SemanticsNode] introduced by this configuration is controlled by /// [explicitChildNodes]. bool get container => _container; bool _container; set container(bool value) { if (container == value) { return; } _container = value; markNeedsSemanticsUpdate(); } /// Whether descendants of this [RenderObject] are allowed to add semantic /// information to the [SemanticsNode] annotated by this widget. /// /// When set to false descendants are allowed to annotate [SemanticsNode]s of /// their parent with the semantic information they want to contribute to the /// semantic tree. /// When set to true the only way for descendants to contribute semantic /// information to the semantic tree is to introduce new explicit /// [SemanticsNode]s to the tree. /// /// This setting is often used in combination with /// [SemanticsConfiguration.isSemanticBoundary] to create semantic boundaries /// that are either writable or not for children. bool get explicitChildNodes => _explicitChildNodes; bool _explicitChildNodes; set explicitChildNodes(bool value) { if (_explicitChildNodes == value) { return; } _explicitChildNodes = value; markNeedsSemanticsUpdate(); } /// Whether descendants of this [RenderObject] should have their semantic /// information ignored. /// /// When this flag is set to true, all child semantics nodes are ignored. /// This can be used as a convenience for cases where a child is wrapped in /// an [ExcludeSemantics] widget and then another [Semantics] widget. bool get excludeSemantics => _excludeSemantics; bool _excludeSemantics; set excludeSemantics(bool value) { if (_excludeSemantics == value) { return; } _excludeSemantics = value; markNeedsSemanticsUpdate(); } /// Whether to block user interactions for the semantics subtree. /// /// Setting this true prevents user from activating pointer related /// [SemanticsAction]s, such as [SemanticsAction.tap] or /// [SemanticsAction.longPress]. bool get blockUserActions => _blockUserActions; bool _blockUserActions; set blockUserActions(bool value) { if (_blockUserActions == value) { return; } _blockUserActions = value; markNeedsSemanticsUpdate(); } void _updateAttributedFields(SemanticsProperties value) { _attributedLabel = _effectiveAttributedLabel(value); _attributedValue = _effectiveAttributedValue(value); _attributedIncreasedValue = _effectiveAttributedIncreasedValue(value); _attributedDecreasedValue = _effectiveAttributedDecreasedValue(value); _attributedHint = _effectiveAttributedHint(value); } AttributedString? _effectiveAttributedLabel(SemanticsProperties value) { return value.attributedLabel ?? (value.label == null ? null : AttributedString(value.label!)); } AttributedString? _effectiveAttributedValue(SemanticsProperties value) { return value.attributedValue ?? (value.value == null ? null : AttributedString(value.value!)); } AttributedString? _effectiveAttributedIncreasedValue( SemanticsProperties value) { return value.attributedIncreasedValue ?? (value.increasedValue == null ? null : AttributedString(value.increasedValue!)); } AttributedString? _effectiveAttributedDecreasedValue( SemanticsProperties value) { return properties.attributedDecreasedValue ?? (value.decreasedValue == null ? null : AttributedString(value.decreasedValue!)); } AttributedString? _effectiveAttributedHint(SemanticsProperties value) { return value.attributedHint ?? (value.hint == null ? null : AttributedString(value.hint!)); } AttributedString? _attributedLabel; AttributedString? _attributedValue; AttributedString? _attributedIncreasedValue; AttributedString? _attributedDecreasedValue; AttributedString? _attributedHint; /// If non-null, sets the [SemanticsNode.textDirection] semantic to the given /// value. /// /// This must not be null if [SemanticsProperties.attributedLabel], /// [SemanticsProperties.attributedHint], /// [SemanticsProperties.attributedValue], /// [SemanticsProperties.attributedIncreasedValue], or /// [SemanticsProperties.attributedDecreasedValue] are not null. TextDirection? get textDirection => _textDirection; TextDirection? _textDirection; set textDirection(TextDirection? value) { if (textDirection == value) { return; } _textDirection = value; markNeedsSemanticsUpdate(); } @override void visitChildrenForSemantics(RenderObjectVisitor visitor) { if (excludeSemantics) { return; } super.visitChildrenForSemantics(visitor); } @override void describeSemanticsConfiguration(SemanticsConfiguration config) { super.describeSemanticsConfiguration(config); config.isSemanticBoundary = container; config.explicitChildNodes = explicitChildNodes; config.isBlockingUserActions = blockUserActions; assert( ((_properties.scopesRoute ?? false) && explicitChildNodes) || !(_properties.scopesRoute ?? false), 'explicitChildNodes must be set to true if scopes route is true', ); assert( !((_properties.toggled ?? false) && (_properties.checked ?? false)), 'A semantics node cannot be toggled and checked at the same time', ); if (_properties.enabled != null) { config.isEnabled = _properties.enabled; } if (_properties.checked != null) { config.isChecked = _properties.checked; } if (_properties.mixed != null) { config.isCheckStateMixed = _properties.mixed; } if (_properties.toggled != null) { config.isToggled = _properties.toggled; } if (_properties.selected != null) { config.isSelected = _properties.selected!; } if (_properties.button != null) { config.isButton = _properties.button!; } if (_properties.expanded != null) { config.isExpanded = _properties.expanded; } if (_properties.link != null) { config.isLink = _properties.link!; } if (_properties.slider != null) { config.isSlider = _properties.slider!; } if (_properties.keyboardKey != null) { config.isKeyboardKey = _properties.keyboardKey!; } if (_properties.header != null) { config.isHeader = _properties.header!; } if (_properties.textField != null) { config.isTextField = _properties.textField!; } if (_properties.readOnly != null) { config.isReadOnly = _properties.readOnly!; } if (_properties.focusable != null) { config.isFocusable = _properties.focusable!; } if (_properties.focused != null) { config.isFocused = _properties.focused!; } if (_properties.inMutuallyExclusiveGroup != null) { config.isInMutuallyExclusiveGroup = _properties.inMutuallyExclusiveGroup!; } if (_properties.obscured != null) { config.isObscured = _properties.obscured!; } if (_properties.multiline != null) { config.isMultiline = _properties.multiline!; } if (_properties.hidden != null) { config.isHidden = _properties.hidden!; } if (_properties.image != null) { config.isImage = _properties.image!; } if (_properties.identifier != null) { config.identifier = _properties.identifier!; } if (_attributedLabel != null) { config.attributedLabel = _attributedLabel!; } if (_attributedValue != null) { config.attributedValue = _attributedValue!; } if (_attributedIncreasedValue != null) { config.attributedIncreasedValue = _attributedIncreasedValue!; } if (_attributedDecreasedValue != null) { config.attributedDecreasedValue = _attributedDecreasedValue!; } if (_attributedHint != null) { config.attributedHint = _attributedHint!; } if (_properties.tooltip != null) { config.tooltip = _properties.tooltip!; } if (_properties.hintOverrides != null && _properties.hintOverrides!.isNotEmpty) { config.hintOverrides = _properties.hintOverrides; } if (_properties.scopesRoute != null) { config.scopesRoute = _properties.scopesRoute!; } if (_properties.namesRoute != null) { config.namesRoute = _properties.namesRoute!; } if (_properties.liveRegion != null) { config.liveRegion = _properties.liveRegion!; } if (_properties.maxValueLength != null) { config.maxValueLength = _properties.maxValueLength; } if (_properties.currentValueLength != null) { config.currentValueLength = _properties.currentValueLength; } if (textDirection != null) { config.textDirection = textDirection; } if (_properties.sortKey != null) { config.sortKey = _properties.sortKey; } if (_properties.tagForChildren != null) { config.addTagForChildren(_properties.tagForChildren!); } // Registering _perform* as action handlers instead of the user provided // ones to ensure that changing a user provided handler from a non-null to // another non-null value doesn't require a semantics update. if (_properties.onTap != null) { config.onTap = _performTap; } if (_properties.onLongPress != null) { config.onLongPress = _performLongPress; } if (_properties.onDismiss != null) { config.onDismiss = _performDismiss; } if (_properties.onScrollLeft != null) { config.onScrollLeft = _performScrollLeft; } if (_properties.onScrollRight != null) { config.onScrollRight = _performScrollRight; } if (_properties.onScrollUp != null) { config.onScrollUp = _performScrollUp; } if (_properties.onScrollDown != null) { config.onScrollDown = _performScrollDown; } if (_properties.onIncrease != null) { config.onIncrease = _performIncrease; } if (_properties.onDecrease != null) { config.onDecrease = _performDecrease; } if (_properties.onCopy != null) { config.onCopy = _performCopy; } if (_properties.onCut != null) { config.onCut = _performCut; } if (_properties.onPaste != null) { config.onPaste = _performPaste; } if (_properties.onMoveCursorForwardByCharacter != null) { config.onMoveCursorForwardByCharacter = _performMoveCursorForwardByCharacter; } if (_properties.onMoveCursorBackwardByCharacter != null) { config.onMoveCursorBackwardByCharacter = _performMoveCursorBackwardByCharacter; } if (_properties.onMoveCursorForwardByWord != null) { config.onMoveCursorForwardByWord = _performMoveCursorForwardByWord; } if (_properties.onMoveCursorBackwardByWord != null) { config.onMoveCursorBackwardByWord = _performMoveCursorBackwardByWord; } if (_properties.onSetSelection != null) { config.onSetSelection = _performSetSelection; } if (_properties.onSetText != null) { config.onSetText = _performSetText; } if (_properties.onDidGainAccessibilityFocus != null) { config.onDidGainAccessibilityFocus = _performDidGainAccessibilityFocus; } if (_properties.onDidLoseAccessibilityFocus != null) { config.onDidLoseAccessibilityFocus = _performDidLoseAccessibilityFocus; } if (_properties.customSemanticsActions != null) { config.customSemanticsActions = _properties.customSemanticsActions!; } } void _performTap() { _properties.onTap?.call(); } void _performLongPress() { _properties.onLongPress?.call(); } void _performDismiss() { _properties.onDismiss?.call(); } void _performScrollLeft() { _properties.onScrollLeft?.call(); } void _performScrollRight() { _properties.onScrollRight?.call(); } void _performScrollUp() { _properties.onScrollUp?.call(); } void _performScrollDown() { _properties.onScrollDown?.call(); } void _performIncrease() { _properties.onIncrease?.call(); } void _performDecrease() { _properties.onDecrease?.call(); } void _performCopy() { _properties.onCopy?.call(); } void _performCut() { _properties.onCut?.call(); } void _performPaste() { _properties.onPaste?.call(); } void _performMoveCursorForwardByCharacter(bool extendSelection) { _properties.onMoveCursorForwardByCharacter?.call(extendSelection); } void _performMoveCursorBackwardByCharacter(bool extendSelection) { _properties.onMoveCursorBackwardByCharacter?.call(extendSelection); } void _performMoveCursorForwardByWord(bool extendSelection) { _properties.onMoveCursorForwardByWord?.call(extendSelection); } void _performMoveCursorBackwardByWord(bool extendSelection) { _properties.onMoveCursorBackwardByWord?.call(extendSelection); } void _performSetSelection(TextSelection selection) { _properties.onSetSelection?.call(selection); } void _performSetText(String text) { _properties.onSetText?.call(text); } void _performDidGainAccessibilityFocus() { _properties.onDidGainAccessibilityFocus?.call(); } void _performDidLoseAccessibilityFocus() { _properties.onDidLoseAccessibilityFocus?.call(); } } /// Causes the semantics of all earlier render objects below the same semantic /// boundary to be dropped. /// /// This is useful in a stack where an opaque mask should prevent interactions /// with the render objects painted below the mask. class RenderBlockSemantics extends RenderProxyBox { /// Create a render object that blocks semantics for nodes below it in paint /// order. RenderBlockSemantics({ RenderBox? child, bool blocking = true, }) : _blocking = blocking, super(child); /// Whether this render object is blocking semantics of previously painted /// [RenderObject]s below a common semantics boundary from the semantic tree. bool get blocking => _blocking; bool _blocking; set blocking(bool value) { if (value == _blocking) { return; } _blocking = value; markNeedsSemanticsUpdate(); } @override void describeSemanticsConfiguration(SemanticsConfiguration config) { super.describeSemanticsConfiguration(config); config.isBlockingSemanticsOfPreviouslyPaintedNodes = blocking; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<bool>('blocking', blocking)); } } /// Causes the semantics of all descendants to be merged into this /// node such that the entire subtree becomes a single leaf in the /// semantics tree. /// /// Useful for combining the semantics of multiple render objects that /// form part of a single conceptual widget, e.g. a checkbox, a label, /// and the gesture detector that goes with them. class RenderMergeSemantics extends RenderProxyBox { /// Creates a render object that merges the semantics from its descendants. RenderMergeSemantics({ RenderBox? child }) : super(child); @override void describeSemanticsConfiguration(SemanticsConfiguration config) { super.describeSemanticsConfiguration(config); config ..isSemanticBoundary = true ..isMergingSemanticsOfDescendants = true; } } /// Excludes this subtree from the semantic tree. /// /// When [excluding] is true, this render object (and its subtree) is excluded /// from the semantic tree. /// /// Useful e.g. for hiding text that is redundant with other text next /// to it (e.g. text included only for the visual effect). class RenderExcludeSemantics extends RenderProxyBox { /// Creates a render object that ignores the semantics of its subtree. RenderExcludeSemantics({ RenderBox? child, bool excluding = true, }) : _excluding = excluding, super(child); /// Whether this render object is excluded from the semantic tree. bool get excluding => _excluding; bool _excluding; set excluding(bool value) { if (value == _excluding) { return; } _excluding = value; markNeedsSemanticsUpdate(); } @override void visitChildrenForSemantics(RenderObjectVisitor visitor) { if (excluding) { return; } super.visitChildrenForSemantics(visitor); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<bool>('excluding', excluding)); } } /// A render objects that annotates semantics with an index. /// /// Certain widgets will automatically provide a child index for building /// semantics. For example, the [ScrollView] uses the index of the first /// visible child semantics node to determine the /// [SemanticsConfiguration.scrollIndex]. /// /// See also: /// /// * [CustomScrollView], for an explanation of scroll semantics. class RenderIndexedSemantics extends RenderProxyBox { /// Creates a render object that annotates the child semantics with an index. RenderIndexedSemantics({ RenderBox? child, required int index, }) : _index = index, super(child); /// The index used to annotated child semantics. int get index => _index; int _index; set index(int value) { if (value == index) { return; } _index = value; markNeedsSemanticsUpdate(); } @override void describeSemanticsConfiguration(SemanticsConfiguration config) { super.describeSemanticsConfiguration(config); config.indexInParent = index; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<int>('index', index)); } } /// Provides an anchor for a [RenderFollowerLayer]. /// /// See also: /// /// * [CompositedTransformTarget], the corresponding widget. /// * [LeaderLayer], the layer that this render object creates. class RenderLeaderLayer extends RenderProxyBox { /// Creates a render object that uses a [LeaderLayer]. RenderLeaderLayer({ required LayerLink link, RenderBox? child, }) : _link = link, super(child); /// The link object that connects this [RenderLeaderLayer] with one or more /// [RenderFollowerLayer]s. /// /// The object must not be associated with another [RenderLeaderLayer] that is /// also being painted. LayerLink get link => _link; LayerLink _link; set link(LayerLink value) { if (_link == value) { return; } _link.leaderSize = null; _link = value; if (_previousLayoutSize != null) { _link.leaderSize = _previousLayoutSize; } markNeedsPaint(); } @override bool get alwaysNeedsCompositing => true; // The latest size of this [RenderBox], computed during the previous layout // pass. It should always be equal to [size], but can be accessed even when // [debugDoingThisResize] and [debugDoingThisLayout] are false. Size? _previousLayoutSize; @override void performLayout() { super.performLayout(); _previousLayoutSize = size; link.leaderSize = size; } @override void paint(PaintingContext context, Offset offset) { if (layer == null) { layer = LeaderLayer(link: link, offset: offset); } else { final LeaderLayer leaderLayer = layer! as LeaderLayer; leaderLayer ..link = link ..offset = offset; } context.pushLayer(layer!, super.paint, Offset.zero); assert(() { layer!.debugCreator = debugCreator; return true; }()); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<LayerLink>('link', link)); } } /// Transform the child so that its origin is [offset] from the origin of the /// [RenderLeaderLayer] with the same [LayerLink]. /// /// The [RenderLeaderLayer] in question must be earlier in the paint order. /// /// Hit testing on descendants of this render object will only work if the /// target position is within the box that this render object's parent considers /// to be hittable. /// /// See also: /// /// * [CompositedTransformFollower], the corresponding widget. /// * [FollowerLayer], the layer that this render object creates. class RenderFollowerLayer extends RenderProxyBox { /// Creates a render object that uses a [FollowerLayer]. RenderFollowerLayer({ required LayerLink link, bool showWhenUnlinked = true, Offset offset = Offset.zero, Alignment leaderAnchor = Alignment.topLeft, Alignment followerAnchor = Alignment.topLeft, RenderBox? child, }) : _link = link, _showWhenUnlinked = showWhenUnlinked, _offset = offset, _leaderAnchor = leaderAnchor, _followerAnchor = followerAnchor, super(child); /// The link object that connects this [RenderFollowerLayer] with a /// [RenderLeaderLayer] earlier in the paint order. LayerLink get link => _link; LayerLink _link; set link(LayerLink value) { if (_link == value) { return; } _link = value; markNeedsPaint(); } /// Whether to show the render object's contents when there is no /// corresponding [RenderLeaderLayer] with the same [link]. /// /// When the render object is linked, the child is positioned such that it has /// the same global position as the linked [RenderLeaderLayer]. /// /// When the render object is not linked, then: if [showWhenUnlinked] is true, /// the child is visible and not repositioned; if it is false, then child is /// hidden, and its hit testing is also disabled. bool get showWhenUnlinked => _showWhenUnlinked; bool _showWhenUnlinked; set showWhenUnlinked(bool value) { if (_showWhenUnlinked == value) { return; } _showWhenUnlinked = value; markNeedsPaint(); } /// The offset to apply to the origin of the linked [RenderLeaderLayer] to /// obtain this render object's origin. Offset get offset => _offset; Offset _offset; set offset(Offset value) { if (_offset == value) { return; } _offset = value; markNeedsPaint(); } /// The anchor point on the linked [RenderLeaderLayer] that [followerAnchor] /// will line up with. /// /// {@template flutter.rendering.RenderFollowerLayer.leaderAnchor} /// For example, when [leaderAnchor] and [followerAnchor] are both /// [Alignment.topLeft], this [RenderFollowerLayer] will be top left aligned /// with the linked [RenderLeaderLayer]. When [leaderAnchor] is /// [Alignment.bottomLeft] and [followerAnchor] is [Alignment.topLeft], this /// [RenderFollowerLayer] will be left aligned with the linked /// [RenderLeaderLayer], and its top edge will line up with the /// [RenderLeaderLayer]'s bottom edge. /// {@endtemplate} /// /// Defaults to [Alignment.topLeft]. Alignment get leaderAnchor => _leaderAnchor; Alignment _leaderAnchor; set leaderAnchor(Alignment value) { if (_leaderAnchor == value) { return; } _leaderAnchor = value; markNeedsPaint(); } /// The anchor point on this [RenderFollowerLayer] that will line up with /// [followerAnchor] on the linked [RenderLeaderLayer]. /// /// {@macro flutter.rendering.RenderFollowerLayer.leaderAnchor} /// /// Defaults to [Alignment.topLeft]. Alignment get followerAnchor => _followerAnchor; Alignment _followerAnchor; set followerAnchor(Alignment value) { if (_followerAnchor == value) { return; } _followerAnchor = value; markNeedsPaint(); } @override void detach() { layer = null; super.detach(); } @override bool get alwaysNeedsCompositing => true; /// The layer we created when we were last painted. @override FollowerLayer? get layer => super.layer as FollowerLayer?; /// Return the transform that was used in the last composition phase, if any. /// /// If the [FollowerLayer] has not yet been created, was never composited, or /// was unable to determine the transform (see /// [FollowerLayer.getLastTransform]), this returns the identity matrix (see /// [Matrix4.identity]. Matrix4 getCurrentTransform() { return layer?.getLastTransform() ?? Matrix4.identity(); } @override bool hitTest(BoxHitTestResult result, { required Offset position }) { // Disables the hit testing if this render object is hidden. if (link.leader == null && !showWhenUnlinked) { return false; } // RenderFollowerLayer objects don't check if they are // themselves hit, because it's confusing to think about // how the untransformed size and the child's transformed // position interact. return hitTestChildren(result, position: position); } @override bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { return result.addWithPaintTransform( transform: getCurrentTransform(), position: position, hitTest: (BoxHitTestResult result, Offset position) { return super.hitTestChildren(result, position: position); }, ); } @override void paint(PaintingContext context, Offset offset) { final Size? leaderSize = link.leaderSize; assert( link.leaderSize != null || link.leader == null || leaderAnchor == Alignment.topLeft, '$link: layer is linked to ${link.leader} but a valid leaderSize is not set. ' 'leaderSize is required when leaderAnchor is not Alignment.topLeft ' '(current value is $leaderAnchor).', ); final Offset effectiveLinkedOffset = leaderSize == null ? this.offset : leaderAnchor.alongSize(leaderSize) - followerAnchor.alongSize(size) + this.offset; if (layer == null) { layer = FollowerLayer( link: link, showWhenUnlinked: showWhenUnlinked, linkedOffset: effectiveLinkedOffset, unlinkedOffset: offset, ); } else { layer ?..link = link ..showWhenUnlinked = showWhenUnlinked ..linkedOffset = effectiveLinkedOffset ..unlinkedOffset = offset; } context.pushLayer( layer!, super.paint, Offset.zero, childPaintBounds: const Rect.fromLTRB( // We don't know where we'll end up, so we have no idea what our cull rect should be. double.negativeInfinity, double.negativeInfinity, double.infinity, double.infinity, ), ); assert(() { layer!.debugCreator = debugCreator; return true; }()); } @override void applyPaintTransform(RenderBox child, Matrix4 transform) { transform.multiply(getCurrentTransform()); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<LayerLink>('link', link)); properties.add(DiagnosticsProperty<bool>('showWhenUnlinked', showWhenUnlinked)); properties.add(DiagnosticsProperty<Offset>('offset', offset)); properties.add(TransformProperty('current transform matrix', getCurrentTransform())); } } /// Render object which inserts an [AnnotatedRegionLayer] into the layer tree. /// /// See also: /// /// * [Layer.find], for an example of how this value is retrieved. /// * [AnnotatedRegionLayer], the layer this render object creates. class RenderAnnotatedRegion<T extends Object> extends RenderProxyBox { /// Creates a new [RenderAnnotatedRegion] to insert [value] into the /// layer tree. /// /// If [sized] is true, the layer is provided with the size of this render /// object to clip the results of [Layer.find]. /// /// Neither [value] nor [sized] can be null. RenderAnnotatedRegion({ required T value, required bool sized, RenderBox? child, }) : _value = value, _sized = sized, _layerHandle = LayerHandle<AnnotatedRegionLayer<T>>(), super(child); /// A value which can be retrieved using [Layer.find]. T get value => _value; T _value; set value (T newValue) { if (_value == newValue) { return; } _value = newValue; markNeedsPaint(); } /// Whether the render object will pass its [size] to the [AnnotatedRegionLayer]. bool get sized => _sized; bool _sized; set sized(bool value) { if (_sized == value) { return; } _sized = value; markNeedsPaint(); } final LayerHandle<AnnotatedRegionLayer<T>> _layerHandle; @override final bool alwaysNeedsCompositing = true; @override void paint(PaintingContext context, Offset offset) { // Annotated region layers are not retained because they do not create engine layers. final AnnotatedRegionLayer<T> layer = AnnotatedRegionLayer<T>( value, size: sized ? size : null, offset: sized ? offset : null, ); _layerHandle.layer = layer; context.pushLayer(layer, super.paint, offset); } @override void dispose() { _layerHandle.layer = null; super.dispose(); } }
flutter/packages/flutter/lib/src/rendering/proxy_box.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/rendering/proxy_box.dart", "repo_id": "flutter", "token_count": 55270 }
642
// 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:collection'; import 'dart:math' as math; import 'package:flutter/foundation.dart'; import 'box.dart'; import 'object.dart'; import 'table_border.dart'; /// Parent data used by [RenderTable] for its children. class TableCellParentData extends BoxParentData { /// Where this cell should be placed vertically. /// /// When using [TableCellVerticalAlignment.baseline], the text baseline must be set as well. TableCellVerticalAlignment? verticalAlignment; /// The column that the child was in the last time it was laid out. int? x; /// The row that the child was in the last time it was laid out. int? y; @override String toString() => '${super.toString()}; ${verticalAlignment == null ? "default vertical alignment" : "$verticalAlignment"}'; } /// Base class to describe how wide a column in a [RenderTable] should be. /// /// To size a column to a specific number of pixels, use a [FixedColumnWidth]. /// This is the cheapest way to size a column. /// /// Other algorithms that are relatively cheap include [FlexColumnWidth], which /// distributes the space equally among the flexible columns, /// [FractionColumnWidth], which sizes a column based on the size of the /// table's container. @immutable abstract class TableColumnWidth { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. const TableColumnWidth(); /// The smallest width that the column can have. /// /// The `cells` argument is an iterable that provides all the cells /// in the table for this column. Walking the cells is by definition /// O(N), so algorithms that do that should be considered expensive. /// /// The `containerWidth` argument is the `maxWidth` of the incoming /// constraints for the table, and might be infinite. double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth); /// The ideal width that the column should have. This must be equal /// to or greater than the [minIntrinsicWidth]. The column might be /// bigger than this width, e.g. if the column is flexible or if the /// table's width ends up being forced to be bigger than the sum of /// all the maxIntrinsicWidth values. /// /// The `cells` argument is an iterable that provides all the cells /// in the table for this column. Walking the cells is by definition /// O(N), so algorithms that do that should be considered expensive. /// /// The `containerWidth` argument is the `maxWidth` of the incoming /// constraints for the table, and might be infinite. double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth); /// The flex factor to apply to the cell if there is any room left /// over when laying out the table. The remaining space is /// distributed to any columns with flex in proportion to their flex /// value (higher values get more space). /// /// The `cells` argument is an iterable that provides all the cells /// in the table for this column. Walking the cells is by definition /// O(N), so algorithms that do that should be considered expensive. double? flex(Iterable<RenderBox> cells) => null; @override String toString() => objectRuntimeType(this, 'TableColumnWidth'); } /// Sizes the column according to the intrinsic dimensions of all the /// cells in that column. /// /// This is a very expensive way to size a column. /// /// A flex value can be provided. If specified (and non-null), the /// column will participate in the distribution of remaining space /// once all the non-flexible columns have been sized. class IntrinsicColumnWidth extends TableColumnWidth { /// Creates a column width based on intrinsic sizing. /// /// This sizing algorithm is very expensive. /// /// The `flex` argument specifies the flex factor to apply to the column if /// there is any room left over when laying out the table. If `flex` is /// null (the default), the table will not distribute any extra space to the /// column. const IntrinsicColumnWidth({ double? flex }) : _flex = flex; @override double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) { double result = 0.0; for (final RenderBox cell in cells) { result = math.max(result, cell.getMinIntrinsicWidth(double.infinity)); } return result; } @override double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) { double result = 0.0; for (final RenderBox cell in cells) { result = math.max(result, cell.getMaxIntrinsicWidth(double.infinity)); } return result; } final double? _flex; @override double? flex(Iterable<RenderBox> cells) => _flex; @override String toString() => '${objectRuntimeType(this, 'IntrinsicColumnWidth')}(flex: ${_flex?.toStringAsFixed(1)})'; } /// Sizes the column to a specific number of pixels. /// /// This is the cheapest way to size a column. class FixedColumnWidth extends TableColumnWidth { /// Creates a column width based on a fixed number of logical pixels. const FixedColumnWidth(this.value); /// The width the column should occupy in logical pixels. final double value; @override double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) { return value; } @override double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) { return value; } @override String toString() => '${objectRuntimeType(this, 'FixedColumnWidth')}(${debugFormatDouble(value)})'; } /// Sizes the column to a fraction of the table's constraints' maxWidth. /// /// This is a cheap way to size a column. class FractionColumnWidth extends TableColumnWidth { /// Creates a column width based on a fraction of the table's constraints' /// maxWidth. const FractionColumnWidth(this.value); /// The fraction of the table's constraints' maxWidth that this column should /// occupy. final double value; @override double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) { if (!containerWidth.isFinite) { return 0.0; } return value * containerWidth; } @override double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) { if (!containerWidth.isFinite) { return 0.0; } return value * containerWidth; } @override String toString() => '${objectRuntimeType(this, 'FractionColumnWidth')}($value)'; } /// Sizes the column by taking a part of the remaining space once all /// the other columns have been laid out. /// /// For example, if two columns have a [FlexColumnWidth], then half the /// space will go to one and half the space will go to the other. /// /// This is a cheap way to size a column. class FlexColumnWidth extends TableColumnWidth { /// Creates a column width based on a fraction of the remaining space once all /// the other columns have been laid out. const FlexColumnWidth([this.value = 1.0]); /// The fraction of the remaining space once all the other columns have /// been laid out that this column should occupy. final double value; @override double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) { return 0.0; } @override double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) { return 0.0; } @override double flex(Iterable<RenderBox> cells) { return value; } @override String toString() => '${objectRuntimeType(this, 'FlexColumnWidth')}(${debugFormatDouble(value)})'; } /// Sizes the column such that it is the size that is the maximum of /// two column width specifications. /// /// For example, to have a column be 10% of the container width or /// 100px, whichever is bigger, you could use: /// /// const MaxColumnWidth(const FixedColumnWidth(100.0), FractionColumnWidth(0.1)) /// /// Both specifications are evaluated, so if either specification is /// expensive, so is this. class MaxColumnWidth extends TableColumnWidth { /// Creates a column width that is the maximum of two other column widths. const MaxColumnWidth(this.a, this.b); /// A lower bound for the width of this column. final TableColumnWidth a; /// Another lower bound for the width of this column. final TableColumnWidth b; @override double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) { return math.max( a.minIntrinsicWidth(cells, containerWidth), b.minIntrinsicWidth(cells, containerWidth), ); } @override double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) { return math.max( a.maxIntrinsicWidth(cells, containerWidth), b.maxIntrinsicWidth(cells, containerWidth), ); } @override double? flex(Iterable<RenderBox> cells) { final double? aFlex = a.flex(cells); final double? bFlex = b.flex(cells); if (aFlex == null) { return bFlex; } else if (bFlex == null) { return aFlex; } return math.max(aFlex, bFlex); } @override String toString() => '${objectRuntimeType(this, 'MaxColumnWidth')}($a, $b)'; } /// Sizes the column such that it is the size that is the minimum of /// two column width specifications. /// /// For example, to have a column be 10% of the container width but /// never bigger than 100px, you could use: /// /// const MinColumnWidth(const FixedColumnWidth(100.0), FractionColumnWidth(0.1)) /// /// Both specifications are evaluated, so if either specification is /// expensive, so is this. class MinColumnWidth extends TableColumnWidth { /// Creates a column width that is the minimum of two other column widths. const MinColumnWidth(this.a, this.b); /// An upper bound for the width of this column. final TableColumnWidth a; /// Another upper bound for the width of this column. final TableColumnWidth b; @override double minIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) { return math.min( a.minIntrinsicWidth(cells, containerWidth), b.minIntrinsicWidth(cells, containerWidth), ); } @override double maxIntrinsicWidth(Iterable<RenderBox> cells, double containerWidth) { return math.min( a.maxIntrinsicWidth(cells, containerWidth), b.maxIntrinsicWidth(cells, containerWidth), ); } @override double? flex(Iterable<RenderBox> cells) { final double? aFlex = a.flex(cells); final double? bFlex = b.flex(cells); if (aFlex == null) { return bFlex; } else if (bFlex == null) { return aFlex; } return math.min(aFlex, bFlex); } @override String toString() => '${objectRuntimeType(this, 'MinColumnWidth')}($a, $b)'; } /// Vertical alignment options for cells in [RenderTable] objects. /// /// This is specified using [TableCellParentData] objects on the /// [RenderObject.parentData] of the children of the [RenderTable]. enum TableCellVerticalAlignment { /// Cells with this alignment are placed with their top at the top of the row. top, /// Cells with this alignment are vertically centered in the row. middle, /// Cells with this alignment are placed with their bottom at the bottom of the row. bottom, /// Cells with this alignment are aligned such that they all share the same /// baseline. Cells with no baseline are top-aligned instead. The baseline /// used is specified by [RenderTable.textBaseline]. It is not valid to use /// the baseline value if [RenderTable.textBaseline] is not specified. /// /// This vertical alignment is relatively expensive because it causes the table /// to compute the baseline for each cell in the row. baseline, /// Cells with this alignment are sized to be as tall as the row, then made to fit the row. /// If all the cells have this alignment, then the row will have zero height. fill, /// Cells with this alignment are sized to be the same height as the tallest cell in the row. intrinsicHeight } /// A table where the columns and rows are sized to fit the contents of the cells. class RenderTable extends RenderBox { /// Creates a table render object. /// /// * `columns` must either be null or non-negative. If `columns` is null, /// the number of columns will be inferred from length of the first sublist /// of `children`. /// * `rows` must either be null or non-negative. If `rows` is null, the /// number of rows will be inferred from the `children`. If `rows` is not /// null, then `children` must be null. /// * `children` must either be null or contain lists of all the same length. /// if `children` is not null, then `rows` must be null. /// * [columnWidths] may be null, in which case it defaults to an empty map. RenderTable({ int? columns, int? rows, Map<int, TableColumnWidth>? columnWidths, TableColumnWidth defaultColumnWidth = const FlexColumnWidth(), required TextDirection textDirection, TableBorder? border, List<Decoration?>? rowDecorations, ImageConfiguration configuration = ImageConfiguration.empty, TableCellVerticalAlignment defaultVerticalAlignment = TableCellVerticalAlignment.top, TextBaseline? textBaseline, List<List<RenderBox>>? children, }) : assert(columns == null || columns >= 0), assert(rows == null || rows >= 0), assert(rows == null || children == null), _textDirection = textDirection, _columns = columns ?? (children != null && children.isNotEmpty ? children.first.length : 0), _rows = rows ?? 0, _columnWidths = columnWidths ?? HashMap<int, TableColumnWidth>(), _defaultColumnWidth = defaultColumnWidth, _border = border, _textBaseline = textBaseline, _defaultVerticalAlignment = defaultVerticalAlignment, _configuration = configuration { _children = <RenderBox?>[]..length = _columns * _rows; this.rowDecorations = rowDecorations; // must use setter to initialize box painters array children?.forEach(addRow); } // Children are stored in row-major order. // _children.length must be rows * columns List<RenderBox?> _children = const <RenderBox?>[]; /// The number of vertical alignment lines in this table. /// /// Changing the number of columns will remove any children that no longer fit /// in the table. /// /// Changing the number of columns is an expensive operation because the table /// needs to rearrange its internal representation. int get columns => _columns; int _columns; set columns(int value) { assert(value >= 0); if (value == columns) { return; } final int oldColumns = columns; final List<RenderBox?> oldChildren = _children; _columns = value; _children = List<RenderBox?>.filled(columns * rows, null); final int columnsToCopy = math.min(columns, oldColumns); for (int y = 0; y < rows; y += 1) { for (int x = 0; x < columnsToCopy; x += 1) { _children[x + y * columns] = oldChildren[x + y * oldColumns]; } } if (oldColumns > columns) { for (int y = 0; y < rows; y += 1) { for (int x = columns; x < oldColumns; x += 1) { final int xy = x + y * oldColumns; if (oldChildren[xy] != null) { dropChild(oldChildren[xy]!); } } } } markNeedsLayout(); } /// The number of horizontal alignment lines in this table. /// /// Changing the number of rows will remove any children that no longer fit /// in the table. int get rows => _rows; int _rows; set rows(int value) { assert(value >= 0); if (value == rows) { return; } if (_rows > value) { for (int xy = columns * value; xy < _children.length; xy += 1) { if (_children[xy] != null) { dropChild(_children[xy]!); } } } _rows = value; _children.length = columns * rows; markNeedsLayout(); } /// How the horizontal extents of the columns of this table should be determined. /// /// If the [Map] has a null entry for a given column, the table uses the /// [defaultColumnWidth] instead. /// /// The layout performance of the table depends critically on which column /// sizing algorithms are used here. In particular, [IntrinsicColumnWidth] is /// quite expensive because it needs to measure each cell in the column to /// determine the intrinsic size of the column. /// /// This property can never return null. If it is set to null, and the existing /// map is not empty, then the value is replaced by an empty map. (If it is set /// to null while the current value is an empty map, the value is not changed.) Map<int, TableColumnWidth>? get columnWidths => Map<int, TableColumnWidth>.unmodifiable(_columnWidths); Map<int, TableColumnWidth> _columnWidths; set columnWidths(Map<int, TableColumnWidth>? value) { if (_columnWidths == value) { return; } if (_columnWidths.isEmpty && value == null) { return; } _columnWidths = value ?? HashMap<int, TableColumnWidth>(); markNeedsLayout(); } /// Determines how the width of column with the given index is determined. void setColumnWidth(int column, TableColumnWidth value) { if (_columnWidths[column] == value) { return; } _columnWidths[column] = value; markNeedsLayout(); } /// How to determine with widths of columns that don't have an explicit sizing algorithm. /// /// Specifically, the [defaultColumnWidth] is used for column `i` if /// `columnWidths[i]` is null. TableColumnWidth get defaultColumnWidth => _defaultColumnWidth; TableColumnWidth _defaultColumnWidth; set defaultColumnWidth(TableColumnWidth value) { if (defaultColumnWidth == value) { return; } _defaultColumnWidth = value; markNeedsLayout(); } /// The direction in which the columns are ordered. TextDirection get textDirection => _textDirection; TextDirection _textDirection; set textDirection(TextDirection value) { if (_textDirection == value) { return; } _textDirection = value; markNeedsLayout(); } /// The style to use when painting the boundary and interior divisions of the table. TableBorder? get border => _border; TableBorder? _border; set border(TableBorder? value) { if (border == value) { return; } _border = value; markNeedsPaint(); } /// The decorations to use for each row of the table. /// /// Row decorations fill the horizontal and vertical extent of each row in /// the table, unlike decorations for individual cells, which might not fill /// either. List<Decoration> get rowDecorations => List<Decoration>.unmodifiable(_rowDecorations ?? const <Decoration>[]); // _rowDecorations and _rowDecorationPainters need to be in sync. They have to // either both be null or have same length. List<Decoration?>? _rowDecorations; List<BoxPainter?>? _rowDecorationPainters; set rowDecorations(List<Decoration?>? value) { if (_rowDecorations == value) { return; } _rowDecorations = value; if (_rowDecorationPainters != null) { for (final BoxPainter? painter in _rowDecorationPainters!) { painter?.dispose(); } } _rowDecorationPainters = _rowDecorations != null ? List<BoxPainter?>.filled(_rowDecorations!.length, null) : null; } /// The settings to pass to the [rowDecorations] when painting, so that they /// can resolve images appropriately. See [ImageProvider.resolve] and /// [BoxPainter.paint]. ImageConfiguration get configuration => _configuration; ImageConfiguration _configuration; set configuration(ImageConfiguration value) { if (value == _configuration) { return; } _configuration = value; markNeedsPaint(); } /// How cells that do not explicitly specify a vertical alignment are aligned vertically. TableCellVerticalAlignment get defaultVerticalAlignment => _defaultVerticalAlignment; TableCellVerticalAlignment _defaultVerticalAlignment; set defaultVerticalAlignment(TableCellVerticalAlignment value) { if (_defaultVerticalAlignment == value) { return; } _defaultVerticalAlignment = value; markNeedsLayout(); } /// The text baseline to use when aligning rows using [TableCellVerticalAlignment.baseline]. TextBaseline? get textBaseline => _textBaseline; TextBaseline? _textBaseline; set textBaseline(TextBaseline? value) { if (_textBaseline == value) { return; } _textBaseline = value; markNeedsLayout(); } @override void setupParentData(RenderObject child) { if (child.parentData is! TableCellParentData) { child.parentData = TableCellParentData(); } } /// Replaces the children of this table with the given cells. /// /// The cells are divided into the specified number of columns before /// replacing the existing children. /// /// If the new cells contain any existing children of the table, those /// children are moved to their new location in the table rather than /// removed from the table and re-added. void setFlatChildren(int columns, List<RenderBox?> cells) { if (cells == _children && columns == _columns) { return; } assert(columns >= 0); // consider the case of a newly empty table if (columns == 0 || cells.isEmpty) { assert(cells.isEmpty); _columns = columns; if (_children.isEmpty) { assert(_rows == 0); return; } for (final RenderBox? oldChild in _children) { if (oldChild != null) { dropChild(oldChild); } } _rows = 0; _children.clear(); markNeedsLayout(); return; } assert(cells.length % columns == 0); // fill a set with the cells that are moving (it's important not // to dropChild a child that's remaining with us, because that // would clear their parentData field) final Set<RenderBox> lostChildren = HashSet<RenderBox>(); for (int y = 0; y < _rows; y += 1) { for (int x = 0; x < _columns; x += 1) { final int xyOld = x + y * _columns; final int xyNew = x + y * columns; if (_children[xyOld] != null && (x >= columns || xyNew >= cells.length || _children[xyOld] != cells[xyNew])) { lostChildren.add(_children[xyOld]!); } } } // adopt cells that are arriving, and cross cells that are just moving off our list of lostChildren int y = 0; while (y * columns < cells.length) { for (int x = 0; x < columns; x += 1) { final int xyNew = x + y * columns; final int xyOld = x + y * _columns; if (cells[xyNew] != null && (x >= _columns || y >= _rows || _children[xyOld] != cells[xyNew])) { if (!lostChildren.remove(cells[xyNew])) { adoptChild(cells[xyNew]!); } } } y += 1; } // drop all the lost children lostChildren.forEach(dropChild); // update our internal values _columns = columns; _rows = cells.length ~/ columns; _children = List<RenderBox?>.of(cells); assert(_children.length == rows * columns); markNeedsLayout(); } /// Replaces the children of this table with the given cells. void setChildren(List<List<RenderBox>>? cells) { // TODO(ianh): Make this smarter, like setFlatChildren if (cells == null) { setFlatChildren(0, const <RenderBox?>[]); return; } for (final RenderBox? oldChild in _children) { if (oldChild != null) { dropChild(oldChild); } } _children.clear(); _columns = cells.isNotEmpty ? cells.first.length : 0; _rows = 0; cells.forEach(addRow); assert(_children.length == rows * columns); } /// Adds a row to the end of the table. /// /// The newly added children must not already have parents. void addRow(List<RenderBox?> cells) { assert(cells.length == columns); assert(_children.length == rows * columns); _rows += 1; _children.addAll(cells); for (final RenderBox? cell in cells) { if (cell != null) { adoptChild(cell); } } markNeedsLayout(); } /// Replaces the child at the given position with the given child. /// /// If the given child is already located at the given position, this function /// does not modify the table. Otherwise, the given child must not already /// have a parent. void setChild(int x, int y, RenderBox? value) { assert(x >= 0 && x < columns && y >= 0 && y < rows); assert(_children.length == rows * columns); final int xy = x + y * columns; final RenderBox? oldChild = _children[xy]; if (oldChild == value) { return; } if (oldChild != null) { dropChild(oldChild); } _children[xy] = value; if (value != null) { adoptChild(value); } } @override void attach(PipelineOwner owner) { super.attach(owner); for (final RenderBox? child in _children) { child?.attach(owner); } } @override void detach() { super.detach(); if (_rowDecorationPainters != null) { for (final BoxPainter? painter in _rowDecorationPainters!) { painter?.dispose(); } _rowDecorationPainters = List<BoxPainter?>.filled(_rowDecorations!.length, null); } for (final RenderBox? child in _children) { child?.detach(); } } @override void visitChildren(RenderObjectVisitor visitor) { assert(_children.length == rows * columns); for (final RenderBox? child in _children) { if (child != null) { visitor(child); } } } @override double computeMinIntrinsicWidth(double height) { assert(_children.length == rows * columns); double totalMinWidth = 0.0; for (int x = 0; x < columns; x += 1) { final TableColumnWidth columnWidth = _columnWidths[x] ?? defaultColumnWidth; final Iterable<RenderBox> columnCells = column(x); totalMinWidth += columnWidth.minIntrinsicWidth(columnCells, double.infinity); } return totalMinWidth; } @override double computeMaxIntrinsicWidth(double height) { assert(_children.length == rows * columns); double totalMaxWidth = 0.0; for (int x = 0; x < columns; x += 1) { final TableColumnWidth columnWidth = _columnWidths[x] ?? defaultColumnWidth; final Iterable<RenderBox> columnCells = column(x); totalMaxWidth += columnWidth.maxIntrinsicWidth(columnCells, double.infinity); } return totalMaxWidth; } @override double computeMinIntrinsicHeight(double width) { // winner of the 2016 world's most expensive intrinsic dimension function award // honorable mention, most likely to improve if taught about memoization award assert(_children.length == rows * columns); final List<double> widths = _computeColumnWidths(BoxConstraints.tightForFinite(width: width)); double rowTop = 0.0; for (int y = 0; y < rows; y += 1) { double rowHeight = 0.0; for (int x = 0; x < columns; x += 1) { final int xy = x + y * columns; final RenderBox? child = _children[xy]; if (child != null) { rowHeight = math.max(rowHeight, child.getMaxIntrinsicHeight(widths[x])); } } rowTop += rowHeight; } return rowTop; } @override double computeMaxIntrinsicHeight(double width) { return computeMinIntrinsicHeight(width); } double? _baselineDistance; @override double? computeDistanceToActualBaseline(TextBaseline baseline) { // returns the baseline of the first cell that has a baseline in the first row assert(!debugNeedsLayout); return _baselineDistance; } /// Returns the list of [RenderBox] objects that are in the given /// column, in row order, starting from the first row. /// /// This is a lazily-evaluated iterable. // The following uses sync* because it is public API documented to return a // lazy iterable. Iterable<RenderBox> column(int x) sync* { for (int y = 0; y < rows; y += 1) { final int xy = x + y * columns; final RenderBox? child = _children[xy]; if (child != null) { yield child; } } } /// Returns the list of [RenderBox] objects that are on the given /// row, in column order, starting with the first column. /// /// This is a lazily-evaluated iterable. // The following uses sync* because it is public API documented to return a // lazy iterable. Iterable<RenderBox> row(int y) sync* { final int start = y * columns; final int end = (y + 1) * columns; for (int xy = start; xy < end; xy += 1) { final RenderBox? child = _children[xy]; if (child != null) { yield child; } } } List<double> _computeColumnWidths(BoxConstraints constraints) { assert(_children.length == rows * columns); // We apply the constraints to the column widths in the order of // least important to most important: // 1. apply the ideal widths (maxIntrinsicWidth) // 2. grow the flex columns so that the table has the maxWidth (if // finite) or the minWidth (if not) // 3. if there were no flex columns, then grow the table to the // minWidth. // 4. apply the maximum width of the table, shrinking columns as // necessary, applying minimum column widths as we go // 1. apply ideal widths, and collect information we'll need later final List<double> widths = List<double>.filled(columns, 0.0); final List<double> minWidths = List<double>.filled(columns, 0.0); final List<double?> flexes = List<double?>.filled(columns, null); double tableWidth = 0.0; // running tally of the sum of widths[x] for all x double unflexedTableWidth = 0.0; // sum of the maxIntrinsicWidths of any column that has null flex double totalFlex = 0.0; for (int x = 0; x < columns; x += 1) { final TableColumnWidth columnWidth = _columnWidths[x] ?? defaultColumnWidth; final Iterable<RenderBox> columnCells = column(x); // apply ideal width (maxIntrinsicWidth) final double maxIntrinsicWidth = columnWidth.maxIntrinsicWidth(columnCells, constraints.maxWidth); assert(maxIntrinsicWidth.isFinite); assert(maxIntrinsicWidth >= 0.0); widths[x] = maxIntrinsicWidth; tableWidth += maxIntrinsicWidth; // collect min width information while we're at it final double minIntrinsicWidth = columnWidth.minIntrinsicWidth(columnCells, constraints.maxWidth); assert(minIntrinsicWidth.isFinite); assert(minIntrinsicWidth >= 0.0); minWidths[x] = minIntrinsicWidth; assert(maxIntrinsicWidth >= minIntrinsicWidth); // collect flex information while we're at it final double? flex = columnWidth.flex(columnCells); if (flex != null) { assert(flex.isFinite); assert(flex > 0.0); flexes[x] = flex; totalFlex += flex; } else { unflexedTableWidth = unflexedTableWidth + maxIntrinsicWidth; } } final double maxWidthConstraint = constraints.maxWidth; final double minWidthConstraint = constraints.minWidth; // 2. grow the flex columns so that the table has the maxWidth (if // finite) or the minWidth (if not) if (totalFlex > 0.0) { // this can only grow the table, but it _will_ grow the table at // least as big as the target width. final double targetWidth; if (maxWidthConstraint.isFinite) { targetWidth = maxWidthConstraint; } else { targetWidth = minWidthConstraint; } if (tableWidth < targetWidth) { final double remainingWidth = targetWidth - unflexedTableWidth; assert(remainingWidth.isFinite); assert(remainingWidth >= 0.0); for (int x = 0; x < columns; x += 1) { if (flexes[x] != null) { final double flexedWidth = remainingWidth * flexes[x]! / totalFlex; assert(flexedWidth.isFinite); assert(flexedWidth >= 0.0); if (widths[x] < flexedWidth) { final double delta = flexedWidth - widths[x]; tableWidth += delta; widths[x] = flexedWidth; } } } assert(tableWidth + precisionErrorTolerance >= targetWidth); } } // step 2 and 3 are mutually exclusive // 3. if there were no flex columns, then grow the table to the // minWidth. else if (tableWidth < minWidthConstraint) { final double delta = (minWidthConstraint - tableWidth) / columns; for (int x = 0; x < columns; x += 1) { widths[x] = widths[x] + delta; } tableWidth = minWidthConstraint; } // beyond this point, unflexedTableWidth is no longer valid // 4. apply the maximum width of the table, shrinking columns as // necessary, applying minimum column widths as we go if (tableWidth > maxWidthConstraint) { double deficit = tableWidth - maxWidthConstraint; // Some columns may have low flex but have all the free space. // (Consider a case with a 1px wide column of flex 1000.0 and // a 1000px wide column of flex 1.0; the sizes coming from the // maxIntrinsicWidths. If the maximum table width is 2px, then // just applying the flexes to the deficit would result in a // table with one column at -998px and one column at 990px, // which is wildly unhelpful.) // Similarly, some columns may be flexible, but not actually // be shrinkable due to a large minimum width. (Consider a // case with two columns, one is flex and one isn't, both have // 1000px maxIntrinsicWidths, but the flex one has 1000px // minIntrinsicWidth also. The whole deficit will have to come // from the non-flex column.) // So what we do is we repeatedly iterate through the flexible // columns shrinking them proportionally until we have no // available columns, then do the same to the non-flexible ones. int availableColumns = columns; while (deficit > precisionErrorTolerance && totalFlex > precisionErrorTolerance) { double newTotalFlex = 0.0; for (int x = 0; x < columns; x += 1) { if (flexes[x] != null) { final double newWidth = widths[x] - deficit * flexes[x]! / totalFlex; assert(newWidth.isFinite); if (newWidth <= minWidths[x]) { // shrank to minimum deficit -= widths[x] - minWidths[x]; widths[x] = minWidths[x]; flexes[x] = null; availableColumns -= 1; } else { deficit -= widths[x] - newWidth; widths[x] = newWidth; newTotalFlex += flexes[x]!; } assert(widths[x] >= 0.0); } } totalFlex = newTotalFlex; } while (deficit > precisionErrorTolerance && availableColumns > 0) { // Now we have to take out the remaining space from the // columns that aren't minimum sized. // To make this fair, we repeatedly remove equal amounts from // each column, clamped to the minimum width, until we run out // of columns that aren't at their minWidth. final double delta = deficit / availableColumns; assert(delta != 0); int newAvailableColumns = 0; for (int x = 0; x < columns; x += 1) { final double availableDelta = widths[x] - minWidths[x]; if (availableDelta > 0.0) { if (availableDelta <= delta) { // shrank to minimum deficit -= widths[x] - minWidths[x]; widths[x] = minWidths[x]; } else { deficit -= delta; widths[x] = widths[x] - delta; newAvailableColumns += 1; } } } availableColumns = newAvailableColumns; } } return widths; } // cache the table geometry for painting purposes final List<double> _rowTops = <double>[]; Iterable<double>? _columnLefts; late double _tableWidth; /// Returns the position and dimensions of the box that the given /// row covers, in this render object's coordinate space (so the /// left coordinate is always 0.0). /// /// The row being queried must exist. /// /// This is only valid after layout. Rect getRowBox(int row) { assert(row >= 0); assert(row < rows); assert(!debugNeedsLayout); return Rect.fromLTRB(0.0, _rowTops[row], size.width, _rowTops[row + 1]); } @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { if (rows * columns == 0) { return constraints.constrain(Size.zero); } final List<double> widths = _computeColumnWidths(constraints); final double tableWidth = widths.fold(0.0, (double a, double b) => a + b); double rowTop = 0.0; for (int y = 0; y < rows; y += 1) { double rowHeight = 0.0; for (int x = 0; x < columns; x += 1) { final int xy = x + y * columns; final RenderBox? child = _children[xy]; if (child != null) { final TableCellParentData childParentData = child.parentData! as TableCellParentData; switch (childParentData.verticalAlignment ?? defaultVerticalAlignment) { case TableCellVerticalAlignment.baseline: assert(debugCannotComputeDryLayout( reason: 'TableCellVerticalAlignment.baseline requires a full layout for baseline metrics to be available.', )); return Size.zero; case TableCellVerticalAlignment.top: case TableCellVerticalAlignment.middle: case TableCellVerticalAlignment.bottom: case TableCellVerticalAlignment.intrinsicHeight: final Size childSize = child.getDryLayout(BoxConstraints.tightFor(width: widths[x])); rowHeight = math.max(rowHeight, childSize.height); case TableCellVerticalAlignment.fill: break; } } } rowTop += rowHeight; } return constraints.constrain(Size(tableWidth, rowTop)); } @override void performLayout() { final BoxConstraints constraints = this.constraints; final int rows = this.rows; final int columns = this.columns; assert(_children.length == rows * columns); if (rows * columns == 0) { // TODO(ianh): if columns is zero, this should be zero width // TODO(ianh): if columns is not zero, this should be based on the column width specifications _tableWidth = 0.0; size = constraints.constrain(Size.zero); return; } final List<double> widths = _computeColumnWidths(constraints); final List<double> positions = List<double>.filled(columns, 0.0); switch (textDirection) { case TextDirection.rtl: positions[columns - 1] = 0.0; for (int x = columns - 2; x >= 0; x -= 1) { positions[x] = positions[x+1] + widths[x+1]; } _columnLefts = positions.reversed; _tableWidth = positions.first + widths.first; case TextDirection.ltr: positions[0] = 0.0; for (int x = 1; x < columns; x += 1) { positions[x] = positions[x-1] + widths[x-1]; } _columnLefts = positions; _tableWidth = positions.last + widths.last; } _rowTops.clear(); _baselineDistance = null; // then, lay out each row double rowTop = 0.0; for (int y = 0; y < rows; y += 1) { _rowTops.add(rowTop); double rowHeight = 0.0; bool haveBaseline = false; double beforeBaselineDistance = 0.0; double afterBaselineDistance = 0.0; final List<double> baselines = List<double>.filled(columns, 0.0); for (int x = 0; x < columns; x += 1) { final int xy = x + y * columns; final RenderBox? child = _children[xy]; if (child != null) { final TableCellParentData childParentData = child.parentData! as TableCellParentData; childParentData.x = x; childParentData.y = y; switch (childParentData.verticalAlignment ?? defaultVerticalAlignment) { case TableCellVerticalAlignment.baseline: assert(textBaseline != null, 'An explicit textBaseline is required when using baseline alignment.'); child.layout(BoxConstraints.tightFor(width: widths[x]), parentUsesSize: true); final double? childBaseline = child.getDistanceToBaseline(textBaseline!, onlyReal: true); if (childBaseline != null) { beforeBaselineDistance = math.max(beforeBaselineDistance, childBaseline); afterBaselineDistance = math.max(afterBaselineDistance, child.size.height - childBaseline); baselines[x] = childBaseline; haveBaseline = true; } else { rowHeight = math.max(rowHeight, child.size.height); childParentData.offset = Offset(positions[x], rowTop); } case TableCellVerticalAlignment.top: case TableCellVerticalAlignment.middle: case TableCellVerticalAlignment.bottom: case TableCellVerticalAlignment.intrinsicHeight: child.layout(BoxConstraints.tightFor(width: widths[x]), parentUsesSize: true); rowHeight = math.max(rowHeight, child.size.height); case TableCellVerticalAlignment.fill: break; } } } if (haveBaseline) { if (y == 0) { _baselineDistance = beforeBaselineDistance; } rowHeight = math.max(rowHeight, beforeBaselineDistance + afterBaselineDistance); } for (int x = 0; x < columns; x += 1) { final int xy = x + y * columns; final RenderBox? child = _children[xy]; if (child != null) { final TableCellParentData childParentData = child.parentData! as TableCellParentData; switch (childParentData.verticalAlignment ?? defaultVerticalAlignment) { case TableCellVerticalAlignment.baseline: childParentData.offset = Offset(positions[x], rowTop + beforeBaselineDistance - baselines[x]); case TableCellVerticalAlignment.top: childParentData.offset = Offset(positions[x], rowTop); case TableCellVerticalAlignment.middle: childParentData.offset = Offset(positions[x], rowTop + (rowHeight - child.size.height) / 2.0); case TableCellVerticalAlignment.bottom: childParentData.offset = Offset(positions[x], rowTop + rowHeight - child.size.height); case TableCellVerticalAlignment.fill: case TableCellVerticalAlignment.intrinsicHeight: child.layout(BoxConstraints.tightFor(width: widths[x], height: rowHeight)); childParentData.offset = Offset(positions[x], rowTop); } } } rowTop += rowHeight; } _rowTops.add(rowTop); size = constraints.constrain(Size(_tableWidth, rowTop)); assert(_rowTops.length == rows + 1); } @override bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { assert(_children.length == rows * columns); for (int index = _children.length - 1; index >= 0; index -= 1) { final RenderBox? child = _children[index]; if (child != null) { final BoxParentData childParentData = child.parentData! as BoxParentData; final bool isHit = result.addWithPaintOffset( offset: childParentData.offset, position: position, hitTest: (BoxHitTestResult result, Offset transformed) { assert(transformed == position - childParentData.offset); return child.hitTest(result, position: transformed); }, ); if (isHit) { return true; } } } return false; } @override void paint(PaintingContext context, Offset offset) { assert(_children.length == rows * columns); if (rows * columns == 0) { if (border != null) { final Rect borderRect = Rect.fromLTWH(offset.dx, offset.dy, _tableWidth, 0.0); border!.paint(context.canvas, borderRect, rows: const <double>[], columns: const <double>[]); } return; } assert(_rowTops.length == rows + 1); if (_rowDecorations != null) { assert(_rowDecorations!.length == _rowDecorationPainters!.length); final Canvas canvas = context.canvas; for (int y = 0; y < rows; y += 1) { if (_rowDecorations!.length <= y) { break; } if (_rowDecorations![y] != null) { _rowDecorationPainters![y] ??= _rowDecorations![y]!.createBoxPainter(markNeedsPaint); _rowDecorationPainters![y]!.paint( canvas, Offset(offset.dx, offset.dy + _rowTops[y]), configuration.copyWith(size: Size(size.width, _rowTops[y+1] - _rowTops[y])), ); } } } for (int index = 0; index < _children.length; index += 1) { final RenderBox? child = _children[index]; if (child != null) { final BoxParentData childParentData = child.parentData! as BoxParentData; context.paintChild(child, childParentData.offset + offset); } } assert(_rows == _rowTops.length - 1); assert(_columns == _columnLefts!.length); if (border != null) { // The border rect might not fill the entire height of this render object // if the rows underflow. We always force the columns to fill the width of // the render object, which means the columns cannot underflow. final Rect borderRect = Rect.fromLTWH(offset.dx, offset.dy, _tableWidth, _rowTops.last); final Iterable<double> rows = _rowTops.getRange(1, _rowTops.length - 1); final Iterable<double> columns = _columnLefts!.skip(1); border!.paint(context.canvas, borderRect, rows: rows, columns: columns); } } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<TableBorder>('border', border, defaultValue: null)); properties.add(DiagnosticsProperty<Map<int, TableColumnWidth>>('specified column widths', _columnWidths, level: _columnWidths.isEmpty ? DiagnosticLevel.hidden : DiagnosticLevel.info)); properties.add(DiagnosticsProperty<TableColumnWidth>('default column width', defaultColumnWidth)); properties.add(MessageProperty('table size', '$columns\u00D7$rows')); properties.add(IterableProperty<String>('column offsets', _columnLefts?.map(debugFormatDouble), ifNull: 'unknown')); properties.add(IterableProperty<String>('row offsets', _rowTops.map(debugFormatDouble), ifNull: 'unknown')); } @override List<DiagnosticsNode> debugDescribeChildren() { if (_children.isEmpty) { return <DiagnosticsNode>[DiagnosticsNode.message('table is empty')]; } final List<DiagnosticsNode> children = <DiagnosticsNode>[]; for (int y = 0; y < rows; y += 1) { for (int x = 0; x < columns; x += 1) { final int xy = x + y * columns; final RenderBox? child = _children[xy]; final String name = 'child ($x, $y)'; if (child != null) { children.add(child.toDiagnosticsNode(name: name)); } else { children.add(DiagnosticsProperty<Object>(name, null, ifNull: 'is null', showSeparator: false)); } } } return children; } }
flutter/packages/flutter/lib/src/rendering/table.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/rendering/table.dart", "repo_id": "flutter", "token_count": 17090 }
643
// 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 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; export 'dart:ui' show TextDirection; /// Determines the assertiveness level of the accessibility announcement. /// /// It is used by [AnnounceSemanticsEvent] to determine the priority with which /// assistive technology should treat announcements. enum Assertiveness { /// The assistive technology will speak changes whenever the user is idle. polite, /// The assistive technology will interrupt any announcement that it is /// currently making to notify the user about the change. /// /// It should only be used for time-sensitive/critical notifications. assertive, } /// An event sent by the application to notify interested listeners that /// something happened to the user interface (e.g. a view scrolled). /// /// These events are usually interpreted by assistive technologies to give the /// user additional clues about the current state of the UI. abstract class SemanticsEvent { /// Initializes internal fields. /// /// [type] is a string that identifies this class of [SemanticsEvent]s. const SemanticsEvent(this.type); /// The type of this event. /// /// The type is used by the engine to translate this event into the /// appropriate native event (`UIAccessibility*Notification` on iOS and /// `AccessibilityEvent` on Android). final String type; /// Converts this event to a Map that can be encoded with /// [StandardMessageCodec]. /// /// [nodeId] is the unique identifier of the semantics node associated with /// the event, or null if the event is not associated with a semantics node. Map<String, dynamic> toMap({ int? nodeId }) { final Map<String, dynamic> event = <String, dynamic>{ 'type': type, 'data': getDataMap(), }; if (nodeId != null) { event['nodeId'] = nodeId; } return event; } /// Returns the event's data object. Map<String, dynamic> getDataMap(); @override String toString() { final List<String> pairs = <String>[]; final Map<String, dynamic> dataMap = getDataMap(); final List<String> sortedKeys = dataMap.keys.toList()..sort(); for (final String key in sortedKeys) { pairs.add('$key: ${dataMap[key]}'); } return '${objectRuntimeType(this, 'SemanticsEvent')}(${pairs.join(', ')})'; } } /// An event for a semantic announcement. /// /// This should be used for announcement that are not seamlessly announced by /// the system as a result of a UI state change. /// /// For example a camera application can use this method to make accessibility /// announcements regarding objects in the viewfinder. /// /// When possible, prefer using mechanisms like [Semantics] to implicitly /// trigger announcements over using this event. class AnnounceSemanticsEvent extends SemanticsEvent { /// Constructs an event that triggers an announcement by the platform. const AnnounceSemanticsEvent(this.message, this.textDirection, {this.assertiveness = Assertiveness.polite}) : super('announce'); /// The message to announce. final String message; /// Text direction for [message]. final TextDirection textDirection; /// Determines whether the announcement should interrupt any existing announcement, /// or queue after it. /// /// On the web this option uses the aria-live level to set the assertiveness /// of the announcement. On iOS, Android, Windows, Linux, macOS, and Fuchsia /// this option currently has no effect. final Assertiveness assertiveness; @override Map<String, dynamic> getDataMap() { return <String, dynamic> { 'message': message, 'textDirection': textDirection.index, if (assertiveness != Assertiveness.polite) 'assertiveness': assertiveness.index, }; } } /// An event for a semantic announcement of a tooltip. /// /// This is only used by Android to announce tooltip values. class TooltipSemanticsEvent extends SemanticsEvent { /// Constructs an event that triggers a tooltip announcement by the platform. const TooltipSemanticsEvent(this.message) : super('tooltip'); /// The text content of the tooltip. final String message; @override Map<String, dynamic> getDataMap() { return <String, dynamic>{ 'message': message, }; } } /// An event which triggers long press semantic feedback. /// /// Currently only honored on Android. Triggers a long-press specific sound /// when TalkBack is enabled. class LongPressSemanticsEvent extends SemanticsEvent { /// Constructs an event that triggers a long-press semantic feedback by the platform. const LongPressSemanticsEvent() : super('longPress'); @override Map<String, dynamic> getDataMap() => const <String, dynamic>{}; } /// An event which triggers tap semantic feedback. /// /// Currently only honored on Android. Triggers a tap specific sound when /// TalkBack is enabled. class TapSemanticEvent extends SemanticsEvent { /// Constructs an event that triggers a long-press semantic feedback by the platform. const TapSemanticEvent() : super('tap'); @override Map<String, dynamic> getDataMap() => const <String, dynamic>{}; } /// An event to move the accessibility focus. /// /// Using this API is generally not recommended, as it may break a users' expectation of /// how a11y focus works and therefore should be just very carefully. /// /// One possible use case: /// For example, the currently focused rendering object is replaced by another rendering /// object. In general, such design should be avoided if possible. If not, one may want /// to refocus the newly added rendering object. /// /// One example that is not recommended: /// When a new popup or dropdown opens, moving the focus in these cases may confuse users /// and make it less accessible. /// /// {@tool snippet} /// /// The following code snippet shows how one can request focus on a /// certain widget. /// /// ```dart /// class MyWidget extends StatefulWidget { /// const MyWidget({super.key}); /// /// @override /// State<MyWidget> createState() => _MyWidgetState(); /// } /// /// class _MyWidgetState extends State<MyWidget> { /// final GlobalKey mykey = GlobalKey(); /// /// @override /// void initState() { /// super.initState(); /// // Using addPostFrameCallback because changing focus need to wait for the widget to finish rendering. /// WidgetsBinding.instance.addPostFrameCallback((_) { /// mykey.currentContext?.findRenderObject()?.sendSemanticsEvent(const FocusSemanticEvent()); /// }); /// } /// /// @override /// Widget build(BuildContext context) { /// return Scaffold( /// appBar: AppBar( /// title: const Text('example'), /// ), /// body: Column( /// children: <Widget>[ /// const Text('Hello World'), /// const SizedBox(height: 50), /// Text('set focus here', key: mykey), /// ], /// ), /// ); /// } /// } /// ``` /// {@end-tool} /// /// This currently only supports Android and iOS. class FocusSemanticEvent extends SemanticsEvent { /// Constructs an event that triggers a focus change by the platform. const FocusSemanticEvent() : super('focus'); @override Map<String, dynamic> getDataMap() => const <String, dynamic>{}; }
flutter/packages/flutter/lib/src/semantics/semantics_event.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/semantics/semantics_event.dart", "repo_id": "flutter", "token_count": 2129 }
644
// 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:ui' as ui; import 'package:flutter/foundation.dart'; import 'binding.dart'; import 'debug.dart'; import 'raw_keyboard.dart'; import 'raw_keyboard_android.dart'; import 'system_channels.dart'; export 'dart:ui' show KeyData; export 'package:flutter/foundation.dart' show DiagnosticPropertiesBuilder; export 'keyboard_key.g.dart' show LogicalKeyboardKey, PhysicalKeyboardKey; // When using _keyboardDebug, always call it like so: // // assert(_keyboardDebug(() => 'Blah $foo')); // // It needs to be inside the assert in order to be removed in release mode, and // it needs to use a closure to generate the string in order to avoid string // interpolation when debugPrintKeyboardEvents is false. // // It will throw a StateError if you try to call it when the app is in release // mode. bool _keyboardDebug( String Function() messageFunc, [ Iterable<Object> Function()? detailsFunc, ]) { if (kReleaseMode) { throw StateError( '_keyboardDebug was called in Release mode, which means they are called ' 'without being wrapped in an assert. Always call _keyboardDebug like so:\n' r" assert(_keyboardDebug(() => 'Blah $foo'));" ); } if (!debugPrintKeyboardEvents) { return true; } debugPrint('KEYBOARD: ${messageFunc()}'); final Iterable<Object> details = detailsFunc?.call() ?? const <Object>[]; if (details.isNotEmpty) { for (final Object detail in details) { debugPrint(' $detail'); } } // Return true so that it can be used inside of an assert. return true; } /// Represents a lock mode of a keyboard, such as [KeyboardLockMode.capsLock]. /// /// A lock mode locks some of a keyboard's keys into a distinct mode of operation, /// depending on the lock settings selected. The status of the mode is toggled /// with each key down of its corresponding logical key. A [KeyboardLockMode] /// object is used to query whether this mode is enabled on the keyboard. /// /// Only a limited number of modes are supported, which are enumerated as /// static members of this class. Manual constructing of this class is /// prohibited. enum KeyboardLockMode { /// Represents the number lock mode on the keyboard. /// /// On supporting systems, enabling number lock mode usually allows key /// presses of the number pad to input numbers, instead of acting as up, down, /// left, right, page up, end, etc. numLock._(LogicalKeyboardKey.numLock), /// Represents the scrolling lock mode on the keyboard. /// /// On supporting systems and applications (such as a spreadsheet), enabling /// scrolling lock mode usually allows key presses of the cursor keys to /// scroll the document instead of the cursor. scrollLock._(LogicalKeyboardKey.scrollLock), /// Represents the capital letters lock mode on the keyboard. /// /// On supporting systems, enabling capital lock mode allows key presses of /// the letter keys to input uppercase letters instead of lowercase. capsLock._(LogicalKeyboardKey.capsLock); // KeyboardLockMode has a fixed pool of supported keys, enumerated as static // members of this class, therefore constructing is prohibited. const KeyboardLockMode._(this.logicalKey); /// The logical key that triggers this lock mode. final LogicalKeyboardKey logicalKey; static final Map<int, KeyboardLockMode> _knownLockModes = <int, KeyboardLockMode>{ numLock.logicalKey.keyId: numLock, scrollLock.logicalKey.keyId: scrollLock, capsLock.logicalKey.keyId: capsLock, }; /// Returns the [KeyboardLockMode] constant from the logical key, or /// null, if not found. static KeyboardLockMode? findLockByLogicalKey(LogicalKeyboardKey logicalKey) => _knownLockModes[logicalKey.keyId]; } /// Defines the interface for keyboard key events. /// /// The [KeyEvent] provides a universal model for key event information from a /// hardware keyboard across platforms. /// /// See also: /// /// * [HardwareKeyboard] for full introduction to key event model and handling. /// * [KeyDownEvent], a subclass for events representing the user pressing a /// key. /// * [KeyRepeatEvent], a subclass for events representing the user holding a /// key, causing repeated events. /// * [KeyUpEvent], a subclass for events representing the user releasing a /// key. @immutable abstract class KeyEvent with Diagnosticable { /// Create a const KeyEvent by providing each field. const KeyEvent({ required this.physicalKey, required this.logicalKey, this.character, required this.timeStamp, this.deviceType = ui.KeyEventDeviceType.keyboard, this.synthesized = false, }); /// Returns an object representing the physical location of this key. /// /// A [PhysicalKeyboardKey] represents a USB HID code sent from the keyboard, /// ignoring the key map, modifier keys (like SHIFT), and the label on the key. /// /// [PhysicalKeyboardKey]s are used to describe and test for keys in a /// particular location. A [PhysicalKeyboardKey] may have a name, but the name /// is a mnemonic ("keyA" is easier to remember than 0x70004), derived from the /// key's effect on a QWERTY keyboard. The name does not represent the key's /// effect whatsoever (a physical "keyA" can be the Q key on an AZERTY /// keyboard). /// /// For instance, if you wanted to make a game where the key to the right of /// the CAPS LOCK key made the player move left, you would be comparing a /// physical key with [PhysicalKeyboardKey.keyA], since that is the key next to /// the CAPS LOCK key on a QWERTY keyboard. This would return the same thing /// even on an AZERTY keyboard where the key next to the CAPS LOCK produces a /// "Q" when pressed. /// /// If you want to make your app respond to a key with a particular character /// on it regardless of location of the key, use [KeyEvent.logicalKey] instead. /// /// Also, even though physical keys are defined with USB HID codes, their /// values are not necessarily the same HID codes produced by the hardware and /// presented to the driver. On most platforms, Flutter has to map the /// platform representation back to a HID code because the original HID /// code is not provided. USB HID was chosen because it is a well-defined /// standard for referring to keys such as those a Flutter app may encounter. /// /// See also: /// /// * [logicalKey] for the non-location specific key generated by this event. /// * [character] for the character generated by this keypress (if any). final PhysicalKeyboardKey physicalKey; /// Returns an object representing the logical key that was pressed. /// /// {@template flutter.services.KeyEvent.logicalKey} /// This method takes into account the key map and modifier keys (like SHIFT) /// to determine which logical key to return. /// /// If you are looking for the character produced by a key event, use /// [KeyEvent.character] instead. /// /// If you are collecting text strings, use the [TextField] or /// [CupertinoTextField] widgets, since those automatically handle many of the /// complexities of managing keyboard input, like showing a soft keyboard or /// interacting with an input method editor (IME). /// {@endtemplate} final LogicalKeyboardKey logicalKey; /// Returns the Unicode character (grapheme cluster) completed by this /// keystroke, if any. /// /// This will only return a character if this keystroke, combined with any /// preceding keystroke(s), generates a character, and only on a "key down" /// event. It will return null if no character has been generated by the /// keystroke (e.g. a "dead" or "combining" key), or if the corresponding key /// is a key without a visual representation, such as a modifier key or a /// control key. It will also return null if this is a "key up" event. /// /// This can return multiple Unicode code points, since some characters (more /// accurately referred to as grapheme clusters) are made up of more than one /// code point. /// /// The [character] doesn't take into account edits by an input method editor /// (IME), or manage the visibility of the soft keyboard on touch devices. For /// composing text, use the [TextField] or [CupertinoTextField] widgets, since /// those automatically handle many of the complexities of managing keyboard /// input. /// /// The [character] is not available on [KeyUpEvent]s. final String? character; /// Time of event, relative to an arbitrary start point. /// /// All events share the same timeStamp origin. final Duration timeStamp; /// The source device type for the key event. /// /// Not all platforms supply an accurate type. /// /// Defaults to [ui.KeyEventDeviceType.keyboard]. final ui.KeyEventDeviceType deviceType; /// Whether this event is synthesized by Flutter to synchronize key states. /// /// An non-[synthesized] event is converted from a native event, and a native /// event can only be converted to one non-[synthesized] event. Some properties /// might be changed during the conversion (for example, a native repeat event /// might be converted to a Flutter down event when necessary.) /// /// A [synthesized] event is created without a source native event in order to /// synchronize key states. For example, if the native platform shows that a /// shift key that was previously held has been released somehow without the /// key up event dispatched (probably due to loss of focus), a synthesized key /// up event will be added to regularized the event stream. /// /// For detailed introduction to the regularized event model, see /// [HardwareKeyboard]. /// /// Defaults to false. final bool synthesized; @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<PhysicalKeyboardKey>('physicalKey', physicalKey)); properties.add(DiagnosticsProperty<LogicalKeyboardKey>('logicalKey', logicalKey)); properties.add(StringProperty('character', character)); properties.add(DiagnosticsProperty<Duration>('timeStamp', timeStamp)); properties.add(FlagProperty('synthesized', value: synthesized, ifTrue: 'synthesized')); } } /// An event indicating that the user has pressed a key down on the keyboard. /// /// See also: /// /// * [KeyRepeatEvent], a key event representing the user /// holding a key, causing repeated events. /// * [KeyUpEvent], a key event representing the user /// releasing a key. /// * [HardwareKeyboard], which produces this event. class KeyDownEvent extends KeyEvent { /// Creates a key event that represents the user pressing a key. const KeyDownEvent({ required super.physicalKey, required super.logicalKey, super.character, required super.timeStamp, super.synthesized, super.deviceType, }); } /// An event indicating that the user has released a key on the keyboard. /// /// See also: /// /// * [KeyDownEvent], a key event representing the user /// pressing a key. /// * [KeyRepeatEvent], a key event representing the user /// holding a key, causing repeated events. /// * [HardwareKeyboard], which produces this event. class KeyUpEvent extends KeyEvent { /// Creates a key event that represents the user pressing a key. const KeyUpEvent({ required super.physicalKey, required super.logicalKey, required super.timeStamp, super.synthesized, super.deviceType, }); } /// An event indicating that the user has been holding a key on the keyboard /// and causing repeated events. /// /// Repeat events are not guaranteed and are provided only if supported by the /// underlying platform. /// /// See also: /// /// * [KeyDownEvent], a key event representing the user /// pressing a key. /// * [KeyUpEvent], a key event representing the user /// releasing a key. /// * [HardwareKeyboard], which produces this event. class KeyRepeatEvent extends KeyEvent { /// Creates a key event that represents the user pressing a key. const KeyRepeatEvent({ required super.physicalKey, required super.logicalKey, super.character, required super.timeStamp, super.deviceType, }); } /// The signature for [HardwareKeyboard.addHandler], a callback to decide whether /// the entire framework handles a key event. typedef KeyEventCallback = bool Function(KeyEvent event); /// Manages key events from hardware keyboards. /// /// [HardwareKeyboard] manages all key events of the Flutter application from /// hardware keyboards (in contrast to on-screen keyboards). It receives key /// data from the native platform, dispatches key events to registered /// handlers, and records the keyboard state. /// /// To stay notified whenever keys are pressed, held, or released, add a /// handler with [addHandler]. To only be notified when a specific part of the /// app is focused, use a [Focus] widget's `onFocusChanged` attribute instead /// of [addHandler]. Handlers should be removed with [removeHandler] when /// notification is no longer necessary, or when the handler is being disposed. /// /// To query whether a key is being held, or a lock mode is enabled, use /// [physicalKeysPressed], [logicalKeysPressed], or [lockModesEnabled]. /// These states will have been updated with the event when used during a key /// event handler. /// /// The singleton [HardwareKeyboard] instance is held by the [ServicesBinding] /// as [ServicesBinding.keyboard], and can be conveniently accessed using the /// [HardwareKeyboard.instance] static accessor. /// /// ## Event model /// /// Flutter uses a universal event model ([KeyEvent]) and key options /// ([LogicalKeyboardKey] and [PhysicalKeyboardKey]) regardless of the native /// platform, while preserving platform-specific features as much as /// possible. /// /// [HardwareKeyboard] guarantees that the key model is "regularized": The key /// event stream consists of "key tap sequences", where a key tap sequence is /// defined as one [KeyDownEvent], zero or more [KeyRepeatEvent]s, and one /// [KeyUpEvent] in order, all with the same physical key and logical key. /// /// Example: /// /// * Tap and hold key A, US layout: /// * KeyDownEvent(physicalKey: keyA, logicalKey: keyA, character: "a") /// * KeyRepeatEvent(physicalKey: keyA, logicalKey: keyA, character: "a") /// * KeyUpEvent(physicalKey: keyA, logicalKey: keyA) /// * Press ShiftLeft, tap key A, then release ShiftLeft, US layout: /// * KeyDownEvent(physicalKey: shiftLeft, logicalKey: shiftLeft) /// * KeyDownEvent(physicalKey: keyA, logicalKey: keyA, character: "A") /// * KeyRepeatEvent(physicalKey: keyA, logicalKey: keyA, character: "A") /// * KeyUpEvent(physicalKey: keyA, logicalKey: keyA) /// * KeyUpEvent(physicalKey: shiftLeft, logicalKey: shiftLeft) /// * Tap key Q, French layout: /// * KeyDownEvent(physicalKey: keyA, logicalKey: keyQ, character: "q") /// * KeyUpEvent(physicalKey: keyA, logicalKey: keyQ) /// * Tap CapsLock: /// * KeyDownEvent(physicalKey: capsLock, logicalKey: capsLock) /// * KeyUpEvent(physicalKey: capsLock, logicalKey: capsLock) /// /// When the Flutter application starts, all keys are released, and all lock /// modes are disabled. Upon key events, [HardwareKeyboard] will update its /// states, then dispatch callbacks: [KeyDownEvent]s and [KeyUpEvent]s set /// or reset the pressing state, while [KeyDownEvent]s also toggle lock modes. /// /// Flutter will try to synchronize with the ground truth of keyboard states /// using synthesized events ([KeyEvent.synthesized]), subject to the /// availability of the platform. The desynchronization can be caused by /// non-empty initial state or a change in the focused window or application. /// For example, if CapsLock is enabled when the application starts, then /// immediately before the first key event, a synthesized [KeyDownEvent] and /// [KeyUpEvent] of CapsLock will be dispatched. /// /// The resulting event stream does not map one-to-one to the native key event /// stream. Some native events might be skipped, while some events might be /// synthesized and do not correspond to native events. Synthesized events will /// be indicated by [KeyEvent.synthesized]. /// /// Example: /// /// * Flutter starts with CapsLock on, the first press of keyA: /// * KeyDownEvent(physicalKey: capsLock, logicalKey: capsLock, synthesized: true) /// * KeyUpEvent(physicalKey: capsLock, logicalKey: capsLock, synthesized: true) /// * KeyDownEvent(physicalKey: keyA, logicalKey: keyA, character: "a") /// * While holding ShiftLeft, lose window focus, release shiftLeft, then focus /// back and press keyA: /// * KeyUpEvent(physicalKey: shiftLeft, logicalKey: shiftLeft, synthesized: true) /// * KeyDownEvent(physicalKey: keyA, logicalKey: keyA, character: "a") /// /// Flutter does not distinguish between multiple keyboards. Flutter will /// process all events as if they come from a single keyboard, and try to /// resolve any conflicts and provide a regularized key event stream, which /// can deviate from the ground truth. /// /// See also: /// /// * [KeyDownEvent], [KeyRepeatEvent], and [KeyUpEvent], the classes used to /// describe specific key events. /// * [instance], the singleton instance of this class. class HardwareKeyboard { /// Provides convenient access to the current [HardwareKeyboard] singleton from /// the [ServicesBinding] instance. static HardwareKeyboard get instance => ServicesBinding.instance.keyboard; final Map<PhysicalKeyboardKey, LogicalKeyboardKey> _pressedKeys = <PhysicalKeyboardKey, LogicalKeyboardKey>{}; /// The set of [PhysicalKeyboardKey]s that are pressed. /// /// If called from a key event handler, the result will already include the effect /// of the event. /// /// See also: /// /// * [logicalKeysPressed], which tells if a logical key is being pressed. Set<PhysicalKeyboardKey> get physicalKeysPressed => _pressedKeys.keys.toSet(); /// The set of [LogicalKeyboardKey]s that are pressed. /// /// If called from a key event handler, the result will already include the effect /// of the event. /// /// See also: /// /// * [physicalKeysPressed], which tells if a physical key is being pressed. Set<LogicalKeyboardKey> get logicalKeysPressed => _pressedKeys.values.toSet(); /// Returns the logical key that corresponds to the given pressed physical key. /// /// Returns null if the physical key is not currently pressed. LogicalKeyboardKey? lookUpLayout(PhysicalKeyboardKey physicalKey) => _pressedKeys[physicalKey]; final Set<KeyboardLockMode> _lockModes = <KeyboardLockMode>{}; /// The set of [KeyboardLockMode] that are enabled. /// /// Lock keys, such as CapsLock, are logical keys that toggle their /// respective boolean states on key down events. Such flags are usually used /// as modifier to other keys or events. /// /// If called from a key event handler, the result will already include the effect /// of the event. Set<KeyboardLockMode> get lockModesEnabled => _lockModes; /// Returns true if the given [LogicalKeyboardKey] is pressed, according to /// the [HardwareKeyboard]. bool isLogicalKeyPressed(LogicalKeyboardKey key) => _pressedKeys.values.contains(key); /// Returns true if the given [PhysicalKeyboardKey] is pressed, according to /// the [HardwareKeyboard]. bool isPhysicalKeyPressed(PhysicalKeyboardKey key) => _pressedKeys.containsKey(key); /// Returns true if a logical CTRL modifier key is pressed, regardless of /// which side of the keyboard it is on. /// /// Use [isLogicalKeyPressed] if you need to know which control key was /// pressed. bool get isControlPressed { return isLogicalKeyPressed(LogicalKeyboardKey.controlLeft) || isLogicalKeyPressed(LogicalKeyboardKey.controlRight); } /// Returns true if a logical SHIFT modifier key is pressed, regardless of /// which side of the keyboard it is on. /// /// Use [isLogicalKeyPressed] if you need to know which shift key was pressed. bool get isShiftPressed { return isLogicalKeyPressed(LogicalKeyboardKey.shiftLeft) || isLogicalKeyPressed(LogicalKeyboardKey.shiftRight); } /// Returns true if a logical ALT modifier key is pressed, regardless of which /// side of the keyboard it is on. /// /// The `AltGr` key that appears on some keyboards is considered to be the /// same as [LogicalKeyboardKey.altRight] on some platforms (notably Android). /// On platforms that can distinguish between `altRight` and `altGr`, a press /// of `AltGr` will not return true here, and will need to be tested for /// separately. /// /// Use [isLogicalKeyPressed] if you need to know which alt key was pressed. bool get isAltPressed { return isLogicalKeyPressed(LogicalKeyboardKey.altLeft) || isLogicalKeyPressed(LogicalKeyboardKey.altRight); } /// Returns true if a logical META modifier key is pressed, regardless of /// which side of the keyboard it is on. /// /// Use [isLogicalKeyPressed] if you need to know which meta key was pressed. bool get isMetaPressed { return isLogicalKeyPressed(LogicalKeyboardKey.metaLeft) || isLogicalKeyPressed(LogicalKeyboardKey.metaRight); } void _assertEventIsRegular(KeyEvent event) { assert(() { const String common = 'If this occurs in real application, please report this ' 'bug to Flutter. If this occurs in unit tests, please ensure that ' "simulated events follow Flutter's event model as documented in " '`HardwareKeyboard`. This was the event: '; if (event is KeyDownEvent) { assert(!_pressedKeys.containsKey(event.physicalKey), 'A ${event.runtimeType} is dispatched, but the state shows that the physical ' 'key is already pressed. $common$event'); } else if (event is KeyRepeatEvent || event is KeyUpEvent) { assert(_pressedKeys.containsKey(event.physicalKey), 'A ${event.runtimeType} is dispatched, but the state shows that the physical ' 'key is not pressed. $common$event'); assert(_pressedKeys[event.physicalKey] == event.logicalKey, 'A ${event.runtimeType} is dispatched, but the state shows that the physical ' 'key is pressed on a different logical key. $common$event ' 'and the recorded logical key ${_pressedKeys[event.physicalKey]}'); } else { assert(false, 'Unexpected key event class ${event.runtimeType}'); } return true; }()); } List<KeyEventCallback> _handlers = <KeyEventCallback>[]; bool _duringDispatch = false; List<KeyEventCallback>? _modifiedHandlers; /// Register a listener that is called every time a hardware key event /// occurs. /// /// All registered handlers will be invoked in order regardless of /// their return value. The return value indicates whether Flutter /// "handles" the event. If any handler returns true, the event /// will not be propagated to other native components in the add-to-app /// scenario. /// /// If an object added a handler, it must remove the handler before it is /// disposed. /// /// If used during event dispatching, the addition will not take effect /// until after the dispatching. /// /// See also: /// /// * [removeHandler], which removes the handler. void addHandler(KeyEventCallback handler) { if (_duringDispatch) { _modifiedHandlers ??= <KeyEventCallback>[..._handlers]; _modifiedHandlers!.add(handler); } else { _handlers.add(handler); } } /// Stop calling the given listener every time a hardware key event /// occurs. /// /// The `handler` argument must be [identical] to the one used in /// [addHandler]. If multiple exist, the first one will be removed. /// If none is found, then this method is a no-op. /// /// If used during event dispatching, the removal will not take effect /// until after the event has been dispatched. void removeHandler(KeyEventCallback handler) { if (_duringDispatch) { _modifiedHandlers ??= <KeyEventCallback>[..._handlers]; _modifiedHandlers!.remove(handler); } else { _handlers.remove(handler); } } /// Query the engine and update _pressedKeys accordingly to the engine answer. // /// Both the framework and the engine maintain a state of the current pressed /// keys. There are edge cases, related to startup and restart, where the framework /// needs to resynchronize its keyboard state. Future<void> syncKeyboardState() async { final Map<int, int>? keyboardState = await SystemChannels.keyboard.invokeMapMethod<int, int>( 'getKeyboardState', ); if (keyboardState != null) { for (final int key in keyboardState.keys) { final PhysicalKeyboardKey physicalKey = PhysicalKeyboardKey(key); final LogicalKeyboardKey logicalKey = LogicalKeyboardKey(keyboardState[key]!); _pressedKeys[physicalKey] = logicalKey; } } } bool _dispatchKeyEvent(KeyEvent event) { // This dispatching could have used the same algorithm as [ChangeNotifier], // but since 1) it shouldn't be necessary to support reentrantly // dispatching, 2) there shouldn't be many handlers (most apps should use // only 1, this function just uses a simpler algorithm. assert(!_duringDispatch, 'Nested keyboard dispatching is not supported'); _duringDispatch = true; bool handled = false; for (final KeyEventCallback handler in _handlers) { try { final bool thisResult = handler(event); handled = handled || thisResult; } catch (exception, stack) { InformationCollector? collector; assert(() { collector = () => <DiagnosticsNode>[ DiagnosticsProperty<KeyEvent>('Event', event), ]; return true; }()); FlutterError.reportError(FlutterErrorDetails( exception: exception, stack: stack, library: 'services library', context: ErrorDescription('while processing a key handler'), informationCollector: collector, )); } } _duringDispatch = false; if (_modifiedHandlers != null) { _handlers = _modifiedHandlers!; _modifiedHandlers = null; } return handled; } List<String> _debugPressedKeysDetails() { if (_pressedKeys.isEmpty) { return <String>['Empty']; } final List<String> details = <String>[]; for (final PhysicalKeyboardKey physicalKey in _pressedKeys.keys) { details.add('$physicalKey: ${_pressedKeys[physicalKey]}'); } return details; } /// Process a new [KeyEvent] by recording the state changes and dispatching /// to handlers. bool handleKeyEvent(KeyEvent event) { assert(_keyboardDebug(() => 'Key event received: $event')); assert(_keyboardDebug(() => 'Pressed state before processing the event:', _debugPressedKeysDetails)); _assertEventIsRegular(event); final PhysicalKeyboardKey physicalKey = event.physicalKey; final LogicalKeyboardKey logicalKey = event.logicalKey; if (event is KeyDownEvent) { _pressedKeys[physicalKey] = logicalKey; final KeyboardLockMode? lockMode = KeyboardLockMode.findLockByLogicalKey(event.logicalKey); if (lockMode != null) { if (_lockModes.contains(lockMode)) { _lockModes.remove(lockMode); } else { _lockModes.add(lockMode); } } } else if (event is KeyUpEvent) { _pressedKeys.remove(physicalKey); } else if (event is KeyRepeatEvent) { // Empty } assert(_keyboardDebug(() => 'Pressed state after processing the event:', _debugPressedKeysDetails)); return _dispatchKeyEvent(event); } /// Clear all keyboard states and additional handlers. /// /// All handlers are removed except for the first one, which is added by /// [ServicesBinding]. /// /// This is used by the testing framework to make sure that tests are hermetic. @visibleForTesting void clearState() { _pressedKeys.clear(); _lockModes.clear(); _handlers.clear(); assert(_modifiedHandlers == null); } } /// The mode in which information of key messages is delivered. /// /// This enum is deprecated and will be removed. There is no direct substitute /// planned, since this enum will no longer be necessary once [RawKeyEvent] and /// associated APIs are removed. /// /// Different platforms use different methods, classes, and models to inform the /// framework of native key events, which is called "transit mode". /// /// The framework must determine which transit mode the current platform /// implements and behave accordingly (such as transforming and synthesizing /// events if necessary). Unit tests related to keyboard might also want to /// simulate platform of each transit mode. /// /// The transit mode of the current platform is inferred by [KeyEventManager] at /// the start of the application. /// /// See also: /// /// * [KeyEventManager], which infers the transit mode of the current platform /// and guides how key messages are dispatched. /// * [debugKeyEventSimulatorTransitModeOverride], overrides the transit mode /// used to simulate key events. /// * [KeySimulatorTransitModeVariant], an easier way to set /// [debugKeyEventSimulatorTransitModeOverride] in widget tests. @Deprecated( 'No longer supported. Transit mode is always key data only. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) enum KeyDataTransitMode { /// Key event information is delivered as raw key data. /// /// Raw key data is platform's native key event information sent in JSON /// through a method channel, which is then interpreted as a platform subclass /// of [RawKeyEventData]. /// /// If the current transit mode is [rawKeyData], the raw key data is converted /// to both [KeyMessage.events] and [KeyMessage.rawEvent]. @Deprecated( 'No longer supported. Transit mode is always key data only. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) rawKeyData, /// Key event information is delivered as converted key data, followed by raw /// key data. /// /// Key data ([ui.KeyData]) is a standardized event stream converted from /// platform's native key event information, sent through the embedder API. /// Its event model is described in [HardwareKeyboard]. /// /// Raw key data is platform's native key event information sent in JSON /// through a method channel. It is interpreted by subclasses of /// [RawKeyEventData]. /// /// If the current transit mode is [keyDataThenRawKeyData], then the /// [KeyEventManager] will use the [ui.KeyData] for [KeyMessage.events], and /// the raw data for [KeyMessage.rawEvent]. @Deprecated( 'No longer supported. Transit mode is always key data only. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) keyDataThenRawKeyData, } /// The assembled information converted from a native key message. /// /// This class is deprecated, and will be removed. There is no direct substitute /// planned, since this class will no longer be necessary once [RawKeyEvent] and /// associated APIs are removed. /// /// Native key messages, produced by physically pressing or releasing keyboard /// keys, are translated into two different event streams in Flutter: /// /// * The [KeyEvent] stream, represented by [KeyMessage.events] (recommended). /// * The [RawKeyEvent] stream, represented by [KeyMessage.rawEvent] (legacy, to /// be deprecated). /// /// Either the [KeyEvent] stream or the [RawKeyEvent] stream alone provides a /// complete description of the keyboard messages, but in different event /// models. Flutter is still transitioning from the legacy model to the new /// model, therefore it dispatches both streams simultaneously until the /// transition is completed. [KeyMessage] is used to bundle the stream segments /// of both models from a native key message together for the convenience of /// propagation. /// /// Typically, an application either processes [KeyMessage.events] or /// [KeyMessage.rawEvent], not both. For example, handling a [KeyMessage], means /// handling each event in [KeyMessage.events]. /// /// In advanced cases, a widget needs to process both streams at the same time. /// For example, [FocusNode] has an `onKey` that dispatches [RawKeyEvent]s and /// an `onKeyEvent` that dispatches [KeyEvent]s. To processes a [KeyMessage], it /// first calls `onKeyEvent` with each [KeyEvent] of [events], and then `onKey` /// with [rawEvent]. All callbacks are invoked regardless of their /// [KeyEventResult]. Their results are combined into the result of the node /// using [combineKeyEventResults]. /// /// ```dart /// void handleMessage(FocusNode node, KeyMessage message) { /// final List<KeyEventResult> results = <KeyEventResult>[]; /// if (node.onKeyEvent != null) { /// for (final KeyEvent event in message.events) { /// results.add(node.onKeyEvent!(node, event)); /// } /// } /// if (node.onKey != null && message.rawEvent != null) { /// results.add(node.onKey!(node, message.rawEvent!)); /// } /// final KeyEventResult result = combineKeyEventResults(results); /// // Progress based on `result`... /// } /// ``` @Deprecated( 'No longer supported. Once RawKeyEvent is removed, it will no longer be needed. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) @immutable class KeyMessage { /// Create a [KeyMessage] by providing all information. /// /// The [events] might be empty. @Deprecated( 'No longer supported. Once RawKeyEvent is removed, will no longer be needed. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) const KeyMessage(this.events, this.rawEvent); /// The list of [KeyEvent]s converted from the native key message. /// /// A native key message is converted into multiple [KeyEvent]s in a regular /// event model. The [events] might contain zero or any number of /// [KeyEvent]s. /// /// See also: /// /// * [HardwareKeyboard], which describes the regular event model. /// * [HardwareKeyboard.addHandler], [KeyboardListener], [Focus.onKeyEvent], /// where [KeyEvent]s are commonly used. final List<KeyEvent> events; /// The native key message in the form of a raw key event. /// /// A native key message is sent to the framework in JSON and represented /// in a platform-specific form as [RawKeyEventData] and a platform-neutral /// form as [RawKeyEvent]. Their stream is not as regular as [KeyEvent]'s, /// but keeps as much native information and structure as possible. /// /// The [rawEvent] field might be empty, for example, when the event /// converting system dispatches solitary synthesized events. /// /// The [rawEvent] field will be deprecated in the future. /// /// See also: /// /// * [RawKeyboard.addListener], [RawKeyboardListener], [Focus.onKey], /// where [RawKeyEvent]s are commonly used. final RawKeyEvent? rawEvent; @override String toString() { return 'KeyMessage($events)'; } } /// The signature for [KeyEventManager.keyMessageHandler]. /// /// A [KeyMessageHandler] processes a [KeyMessage] and returns whether the /// message is considered handled. Handled messages should not be propagated to /// other native components. /// /// This message handler signature is deprecated, and will be removed. There is /// no direct substitute planned, since this handler type will no longer be /// necessary once [RawKeyEvent] and associated APIs are removed. @Deprecated( 'No longer supported. Once KeyMessage is removed, will no longer be needed. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) typedef KeyMessageHandler = bool Function(KeyMessage message); /// A singleton class that processes key messages from the platform and /// dispatches converted messages accordingly. /// /// This class is deprecated, and will be removed. There is no direct substitute /// planned, since this class will no longer be necessary once [RawKeyEvent] and /// associated APIs are removed. /// /// [KeyEventManager] receives platform key messages by [handleKeyData] and /// [handleRawKeyMessage], sends converted events to [HardwareKeyboard] and /// [RawKeyboard] for recording keeping, and then dispatches the [KeyMessage] to /// [keyMessageHandler], the global message handler. /// /// [KeyEventManager] is typically created, owned, and invoked by /// [ServicesBinding]. /// /// ## On embedder implementation /// /// Currently, Flutter has two sets of key event API pathways running in /// parallel. /// /// * The "hardware key event" pathway receives messages from the /// "flutter/keydata" message channel (embedder API /// `FlutterEngineSendKeyEvent`) and dispatches [KeyEvent] to /// [HardwareKeyboard] and some methods such as [Focus.onKeyEvent]. /// * The deprecated "raw key event" pathway receives messages from the /// "flutter/keyevent" message channel ([SystemChannels.keyEvent]) and /// dispatches [RawKeyEvent] to [RawKeyboard] and [Focus.onKey] as well as /// similar methods. This pathway will be removed at a future date. /// /// [KeyEventManager] resolves cross-platform compatibility of keyboard /// implementations, since legacy platforms might have not implemented the new /// key data API and only send raw key data on each key message. /// [KeyEventManager] recognizes the platform support by detecting whether a /// message comes from platform channel "flutter/keyevent" before one from /// "flutter/keydata", or vice versa, at the beginning of the app. /// /// * If a "flutter/keydata" message is received first, then this platform is /// considered a modern platform. The hardware key events are stored, and /// dispatched only when a raw key message is received. /// * If a "flutter/keyevent" message is received first, then this platform is /// considered a legacy platform. The raw key event is transformed into a /// hardware key event at best effort. No messages from "flutter/keydata" are /// expected. This behavior has been deprecated, and will be removed at a /// future date. /// /// Therefore, to correctly implement a platform that supports /// `FlutterEngineSendKeyEvent`, the platform must ensure that /// `FlutterEngineSendKeyEvent` is called before sending a message to /// "flutter/keyevent" at the beginning of the app, and every physical key event /// is ended with a "flutter/keyevent" message. @Deprecated( 'No longer supported. Once RawKeyEvent is removed, will no longer be needed. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) class KeyEventManager { /// Create an instance. /// /// This is typically only called by [ServicesBinding]. @Deprecated( 'No longer supported. Once RawKeyEvent is removed, will no longer be needed. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) KeyEventManager(this._hardwareKeyboard, this._rawKeyboard); /// The global entrance which handles all key events sent to Flutter. /// /// This handler is deprecated and will be removed. Use /// [HardwareKeyboard.addHandler]/[HardwareKeyboard.removeHandler] instead. /// /// Typical applications use [WidgetsBinding], where this field is set by the /// focus system (see `FocusManager`) on startup to a function that dispatches /// incoming events to the focus system, including `FocusNode.onKey`, /// `FocusNode.onKeyEvent`, and `Shortcuts`. In this case, the application /// does not need to read, assign, or invoke this value. /// /// For advanced uses, the application can "patch" this callback. See below /// for details. /// /// ## Handlers and event results /// /// Roughly speaking, Flutter processes each native key event with the /// following phases: /// /// 1. Platform-side pre-filtering, sometimes used for IME. /// 2. The key event system. /// 3. The text input system. /// 4. Other native components (possibly non-Flutter). /// /// Each phase will conclude with a boolean called an "event result". If the /// result is true, this phase _handles_ the event and prevents the event from /// being propagated to the next phase. This mechanism allows shortcuts such /// as "Ctrl-C" to not generate a text "C" in the text field, or shortcuts /// that are not handled by any components to trigger special alerts (such as /// the "bonk" noise on macOS). /// /// In the second phase, known as "the key event system", the event is /// dispatched to several destinations: [RawKeyboard]'s listeners, /// [HardwareKeyboard]'s handlers, and [keyMessageHandler]. All destinations /// will always receive the event regardless of the handlers' results. If any /// handler's result is true, then the overall result of the second phase is /// true, and event propagation is stopped. /// /// See also: /// /// * [RawKeyboard.addListener], which adds a raw keyboard listener. /// * [RawKeyboardListener], which is also implemented by adding a raw /// keyboard listener. /// * [HardwareKeyboard.addHandler], which adds a hardware keyboard handler. /// /// ## Advanced usages: Manual assignment or patching /// /// If you are not using the focus system to manage focus, set this attribute /// to a [KeyMessageHandler] that returns true if the propagation on the /// platform should not be continued. If this field is null, key events will /// be assumed to not have been handled by Flutter, a result of "false". /// /// Even if you are using the focus system, you might also want to do more /// than the focus system allows. In these cases, you can _patch_ /// [keyMessageHandler] by setting it to a callback that performs your tasks /// and calls the original callback in between (or not at all.) /// /// Patching [keyMessageHandler] can not be reverted. You should always assume /// that another component might have patched it before you and after you. /// This means that you might want to write your own global notification /// manager, to which callbacks can be added and removed. /// /// You should not patch [keyMessageHandler] until the `FocusManager` has /// assigned its callback. This is assured during any time within the widget /// lifecycle (such as `initState`), or after calling /// `WidgetManager.instance`. /// /// {@tool dartpad} /// This example shows how to process key events that are not /// handled by any focus handler (such as `Shortcuts`) by patching /// [keyMessageHandler]. /// /// The app prints out any key events that are not handled by the app body. /// Try typing something in the first text field. These key presses are not /// handled by `Shortcuts` and will be sent to the fallback handler and /// printed out. Now try some text shortcuts, such as Ctrl+A. The KeyA press /// is handled as a shortcut, and is not sent to the fallback handler and so /// is not printed out. /// /// The key widget is `FallbackKeyEventRegistrar`, a necessity class to allow /// reversible patching. `FallbackFocus` and `FallbackFocusNode` are also /// useful to recognize the widget tree's structure. `FallbackDemo` is an /// example of using them in an app. /// /// ** See code in examples/api/lib/widgets/hardware_keyboard/key_event_manager.0.dart ** /// {@end-tool} /// /// See also: /// /// * [HardwareKeyboard.addHandler], which accepts multiple global handlers to /// process [KeyEvent]s @Deprecated( 'No longer supported. Once RawKeyEvent is removed, will no longer be needed. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) KeyMessageHandler? keyMessageHandler; final HardwareKeyboard _hardwareKeyboard; final RawKeyboard _rawKeyboard; // The [KeyDataTransitMode] of the current platform. // // The `_transitMode` is guaranteed to be non-null during key event callbacks. // // The `_transitMode` is null before the first event, after which it is inferred // and will not change throughout the lifecycle of the application. // // The `_transitMode` can be reset to null in tests using [clearState]. KeyDataTransitMode? _transitMode; // The accumulated [KeyEvent]s since the last time the message is dispatched. // // If _transitMode is [KeyDataTransitMode.keyDataThenRawKeyData], then [KeyEvent]s // are directly received from [handleKeyData]. If _transitMode is // [KeyDataTransitMode.rawKeyData], then [KeyEvent]s are converted from the raw // key data of [handleRawKeyMessage]. Either way, the accumulated key // events are only dispatched along with the next [KeyMessage] when a // dispatchable [RawKeyEvent] is available. final List<KeyEvent> _keyEventsSinceLastMessage = <KeyEvent>[]; // When a RawKeyDownEvent is skipped ([RawKeyEventData.shouldDispatchEvent] // is false), its physical key will be recorded here, so that its up event // can also be properly skipped. final Set<PhysicalKeyboardKey> _skippedRawKeysPressed = <PhysicalKeyboardKey>{}; /// Dispatch a key data to global and leaf listeners. /// /// This method is the handler to the global `onKeyData` API. /// /// This handler is deprecated, and will be removed. Use /// [HardwareKeyboard.addHandler] instead. @Deprecated( 'No longer supported. Use HardwareKeyboard.instance.addHandler instead. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) bool handleKeyData(ui.KeyData data) { _transitMode ??= KeyDataTransitMode.keyDataThenRawKeyData; switch (_transitMode!) { case KeyDataTransitMode.rawKeyData: assert(false, 'Should never encounter KeyData when transitMode is rawKeyData.'); return false; case KeyDataTransitMode.keyDataThenRawKeyData: // Having 0 as the physical and logical ID indicates an empty key data // (the only occasion either field can be 0,) transmitted to ensure // that the transit mode is correctly inferred. These events should be // ignored. if (data.physical == 0 && data.logical == 0) { return false; } assert(data.physical != 0 && data.logical != 0); final KeyEvent event = _eventFromData(data); if (data.synthesized && _keyEventsSinceLastMessage.isEmpty) { // Dispatch the event instantly if both conditions are met: // // - The event is synthesized, therefore the result does not matter. // - The current queue is empty, therefore the order does not matter. // // This allows solitary synthesized `KeyEvent`s to be dispatched, // since they won't be followed by `RawKeyEvent`s. _hardwareKeyboard.handleKeyEvent(event); _dispatchKeyMessage(<KeyEvent>[event], null); } else { // Otherwise, postpone key event dispatching until the next raw // event. Normal key presses always send 0 or more `KeyEvent`s first, // then 1 `RawKeyEvent`. _keyEventsSinceLastMessage.add(event); } return false; } } bool _dispatchKeyMessage(List<KeyEvent> keyEvents, RawKeyEvent? rawEvent) { if (keyMessageHandler != null) { final KeyMessage message = KeyMessage(keyEvents, rawEvent); try { return keyMessageHandler!(message); } catch (exception, stack) { InformationCollector? collector; assert(() { collector = () => <DiagnosticsNode>[ DiagnosticsProperty<KeyMessage>('KeyMessage', message), ]; return true; }()); FlutterError.reportError(FlutterErrorDetails( exception: exception, stack: stack, library: 'services library', context: ErrorDescription('while processing the key message handler'), informationCollector: collector, )); } } return false; } /// Handles a raw key message. /// /// This method is the handler to [SystemChannels.keyEvent], processing the /// JSON form of the native key message and returns the responds for the /// channel. /// /// This handler is deprecated, and will be removed. Use /// [HardwareKeyboard.addHandler] instead. @Deprecated( 'No longer supported. Use HardwareKeyboard.instance.addHandler instead. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) Future<Map<String, dynamic>> handleRawKeyMessage(dynamic message) async { if (_transitMode == null) { _transitMode = KeyDataTransitMode.rawKeyData; // Convert raw events using a listener so that conversion only occurs if // the raw event should be dispatched. _rawKeyboard.addListener(_convertRawEventAndStore); } final RawKeyEvent rawEvent = RawKeyEvent.fromMessage(message as Map<String, dynamic>); bool shouldDispatch = true; if (rawEvent is RawKeyDownEvent) { if (!rawEvent.data.shouldDispatchEvent()) { shouldDispatch = false; _skippedRawKeysPressed.add(rawEvent.physicalKey); } else { _skippedRawKeysPressed.remove(rawEvent.physicalKey); } } else if (rawEvent is RawKeyUpEvent) { if (_skippedRawKeysPressed.contains(rawEvent.physicalKey)) { _skippedRawKeysPressed.remove(rawEvent.physicalKey); shouldDispatch = false; } } bool handled = true; if (shouldDispatch) { // The following `handleRawKeyEvent` will call `_convertRawEventAndStore` // unless the event is not dispatched. handled = _rawKeyboard.handleRawKeyEvent(rawEvent); for (final KeyEvent event in _keyEventsSinceLastMessage) { handled = _hardwareKeyboard.handleKeyEvent(event) || handled; } if (_transitMode == KeyDataTransitMode.rawKeyData) { assert(setEquals(_rawKeyboard.physicalKeysPressed, _hardwareKeyboard.physicalKeysPressed), 'RawKeyboard reported ${_rawKeyboard.physicalKeysPressed}, ' 'while HardwareKeyboard reported ${_hardwareKeyboard.physicalKeysPressed}'); } handled = _dispatchKeyMessage(_keyEventsSinceLastMessage, rawEvent) || handled; _keyEventsSinceLastMessage.clear(); } return <String, dynamic>{ 'handled': handled }; } ui.KeyEventDeviceType _convertDeviceType(RawKeyEvent rawEvent) { final RawKeyEventData data = rawEvent.data; // Device type is only available from Android. if (data is! RawKeyEventDataAndroid) { return ui.KeyEventDeviceType.keyboard; } switch (data.eventSource) { // https://developer.android.com/reference/android/view/InputDevice#SOURCE_KEYBOARD case 0x00000101: return ui.KeyEventDeviceType.keyboard; // https://developer.android.com/reference/android/view/InputDevice#SOURCE_DPAD case 0x00000201: return ui.KeyEventDeviceType.directionalPad; // https://developer.android.com/reference/android/view/InputDevice#SOURCE_GAMEPAD case 0x00000401: return ui.KeyEventDeviceType.gamepad; // https://developer.android.com/reference/android/view/InputDevice#SOURCE_JOYSTICK case 0x01000010: return ui.KeyEventDeviceType.joystick; // https://developer.android.com/reference/android/view/InputDevice#SOURCE_HDMI case 0x02000001: return ui.KeyEventDeviceType.hdmi; } return ui.KeyEventDeviceType.keyboard; } // Convert the raw event to key events, including synthesizing events for // modifiers, and store the key events in `_keyEventsSinceLastMessage`. // // This is only called when `_transitMode` is `rawKeyEvent` and if the raw // event should be dispatched. void _convertRawEventAndStore(RawKeyEvent rawEvent) { final PhysicalKeyboardKey physicalKey = rawEvent.physicalKey; final LogicalKeyboardKey logicalKey = rawEvent.logicalKey; final Set<PhysicalKeyboardKey> physicalKeysPressed = _hardwareKeyboard.physicalKeysPressed; final List<KeyEvent> eventAfterwards = <KeyEvent>[]; final KeyEvent? mainEvent; final LogicalKeyboardKey? recordedLogicalMain = _hardwareKeyboard.lookUpLayout(physicalKey); final Duration timeStamp = ServicesBinding.instance.currentSystemFrameTimeStamp; final String? character = rawEvent.character == '' ? null : rawEvent.character; final ui.KeyEventDeviceType deviceType = _convertDeviceType(rawEvent); if (rawEvent is RawKeyDownEvent) { if (recordedLogicalMain == null) { mainEvent = KeyDownEvent( physicalKey: physicalKey, logicalKey: logicalKey, character: character, timeStamp: timeStamp, deviceType: deviceType, ); physicalKeysPressed.add(physicalKey); } else { assert(physicalKeysPressed.contains(physicalKey)); mainEvent = KeyRepeatEvent( physicalKey: physicalKey, logicalKey: recordedLogicalMain, character: character, timeStamp: timeStamp, deviceType: deviceType, ); } } else { assert(rawEvent is RawKeyUpEvent, 'Unexpected subclass of RawKeyEvent: ${rawEvent.runtimeType}'); if (recordedLogicalMain == null) { mainEvent = null; } else { mainEvent = KeyUpEvent( logicalKey: recordedLogicalMain, physicalKey: physicalKey, timeStamp: timeStamp, deviceType: deviceType, ); physicalKeysPressed.remove(physicalKey); } } for (final PhysicalKeyboardKey key in physicalKeysPressed.difference(_rawKeyboard.physicalKeysPressed)) { if (key == physicalKey) { // Somehow, a down event is dispatched but the key is absent from // keysPressed. Synthesize a up event for the key, but this event must // be added after the main key down event. eventAfterwards.add(KeyUpEvent( physicalKey: key, logicalKey: logicalKey, timeStamp: timeStamp, synthesized: true, deviceType: deviceType, )); } else { _keyEventsSinceLastMessage.add(KeyUpEvent( physicalKey: key, logicalKey: _hardwareKeyboard.lookUpLayout(key)!, timeStamp: timeStamp, synthesized: true, deviceType: deviceType, )); } } for (final PhysicalKeyboardKey key in _rawKeyboard.physicalKeysPressed.difference(physicalKeysPressed)) { _keyEventsSinceLastMessage.add(KeyDownEvent( physicalKey: key, logicalKey: _rawKeyboard.lookUpLayout(key)!, timeStamp: timeStamp, synthesized: true, deviceType: deviceType, )); } if (mainEvent != null) { _keyEventsSinceLastMessage.add(mainEvent); } _keyEventsSinceLastMessage.addAll(eventAfterwards); } /// Reset the inferred platform transit mode and related states. /// /// This method is only used in unit tests. In release mode, this is a no-op. @visibleForTesting void clearState() { assert(() { _transitMode = null; _rawKeyboard.removeListener(_convertRawEventAndStore); _keyEventsSinceLastMessage.clear(); return true; }()); } static KeyEvent _eventFromData(ui.KeyData keyData) { final PhysicalKeyboardKey physicalKey = PhysicalKeyboardKey.findKeyByCode(keyData.physical) ?? PhysicalKeyboardKey(keyData.physical); final LogicalKeyboardKey logicalKey = LogicalKeyboardKey.findKeyByKeyId(keyData.logical) ?? LogicalKeyboardKey(keyData.logical); final Duration timeStamp = keyData.timeStamp; switch (keyData.type) { case ui.KeyEventType.down: return KeyDownEvent( physicalKey: physicalKey, logicalKey: logicalKey, timeStamp: timeStamp, character: keyData.character, synthesized: keyData.synthesized, deviceType: keyData.deviceType, ); case ui.KeyEventType.up: assert(keyData.character == null); return KeyUpEvent( physicalKey: physicalKey, logicalKey: logicalKey, timeStamp: timeStamp, synthesized: keyData.synthesized, deviceType: keyData.deviceType, ); case ui.KeyEventType.repeat: return KeyRepeatEvent( physicalKey: physicalKey, logicalKey: logicalKey, timeStamp: timeStamp, character: keyData.character, deviceType: keyData.deviceType, ); } } }
flutter/packages/flutter/lib/src/services/hardware_keyboard.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/services/hardware_keyboard.dart", "repo_id": "flutter", "token_count": 17200 }
645
// 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 'package:flutter/foundation.dart'; import 'keyboard_maps.g.dart'; import 'raw_keyboard.dart'; export 'package:flutter/foundation.dart' show DiagnosticPropertiesBuilder; export 'keyboard_key.g.dart' show LogicalKeyboardKey, PhysicalKeyboardKey; /// Platform-specific key event data for Linux. /// /// This class is deprecated and will be removed. Platform specific key event /// data will no longer be available. See [KeyEvent] for what is available. /// /// Different window toolkit implementations can map to different key codes. This class /// will use the correct mapping depending on the [keyHelper] provided. /// /// See also: /// /// * [RawKeyboard], which uses this interface to expose key data. @Deprecated( 'Platform specific key event data is no longer available. See KeyEvent for what is available. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) class RawKeyEventDataLinux extends RawKeyEventData { /// Creates a key event data structure specific for Linux. @Deprecated( 'Platform specific key event data is no longer available. See KeyEvent for what is available. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) const RawKeyEventDataLinux({ required this.keyHelper, this.unicodeScalarValues = 0, this.scanCode = 0, this.keyCode = 0, this.modifiers = 0, required this.isDown, this.specifiedLogicalKey, }) : assert((unicodeScalarValues & ~LogicalKeyboardKey.valueMask) == 0); /// A helper class that abstracts the fetching of the toolkit-specific mappings. /// /// There is no real concept of a "native" window toolkit on Linux, and each implementation /// (GLFW, GTK, QT, etc) may have a different key code mapping. final KeyHelper keyHelper; /// An int with up to two Unicode scalar values generated by a single keystroke. An assertion /// will fire if more than two values are encoded in a single keystroke. /// /// This is typically the character that [keyCode] would produce without any modifier keys. /// For dead keys, it is typically the diacritic it would add to a character. Defaults to 0, /// asserted to be not null. final int unicodeScalarValues; /// The hardware scan code id corresponding to this key event. /// /// These values are not reliable and vary from device to device, so this /// information is mainly useful for debugging. final int scanCode; /// The hardware key code corresponding to this key event. /// /// This is the physical key that was pressed, not the Unicode character. /// This value may be different depending on the window toolkit used. See [KeyHelper]. final int keyCode; /// A mask of the current modifiers using the values in Modifier Flags. /// This value may be different depending on the window toolkit used. See [KeyHelper]. final int modifiers; /// Whether or not this key event is a key down (true) or key up (false). final bool isDown; /// A logical key specified by the embedding that should be used instead of /// deriving from raw data. /// /// The GTK embedding detects the keyboard layout and maps some keys to /// logical keys in a way that can not be derived from per-key information. /// /// This is not part of the native GTK key event. final int? specifiedLogicalKey; @override String get keyLabel => unicodeScalarValues == 0 ? '' : String.fromCharCode(unicodeScalarValues); @override PhysicalKeyboardKey get physicalKey => kLinuxToPhysicalKey[scanCode] ?? PhysicalKeyboardKey(LogicalKeyboardKey.webPlane + scanCode); @override LogicalKeyboardKey get logicalKey { if (specifiedLogicalKey != null) { final int key = specifiedLogicalKey!; return LogicalKeyboardKey.findKeyByKeyId(key) ?? LogicalKeyboardKey(key); } // Look to see if the keyCode is a printable number pad key, so that a // difference between regular keys (e.g. "=") and the number pad version // (e.g. the "=" on the number pad) can be determined. final LogicalKeyboardKey? numPadKey = keyHelper.numpadKey(keyCode); if (numPadKey != null) { return numPadKey; } // If it has a non-control-character label, then either return the existing // constant, or construct a new Unicode-based key from it. Don't mark it as // autogenerated, since the label uniquely identifies an ID from the Unicode // plane. if (keyLabel.isNotEmpty && !LogicalKeyboardKey.isControlCharacter(keyLabel)) { final int keyId = LogicalKeyboardKey.unicodePlane | (unicodeScalarValues & LogicalKeyboardKey.valueMask); return LogicalKeyboardKey.findKeyByKeyId(keyId) ?? LogicalKeyboardKey(keyId); } // Look to see if the keyCode is one we know about and have a mapping for. final LogicalKeyboardKey? newKey = keyHelper.logicalKey(keyCode); if (newKey != null) { return newKey; } // This is a non-printable key that we don't know about, so we mint a new // code. return LogicalKeyboardKey(keyCode | keyHelper.platformPlane); } @override bool isModifierPressed(ModifierKey key, {KeyboardSide side = KeyboardSide.any}) { return keyHelper.isModifierPressed(key, modifiers, side: side, keyCode: keyCode, isDown: isDown); } @override KeyboardSide getModifierSide(ModifierKey key) { return keyHelper.getModifierSide(key); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<String>('toolkit', keyHelper.debugToolkit)); properties.add(DiagnosticsProperty<int>('unicodeScalarValues', unicodeScalarValues)); properties.add(DiagnosticsProperty<int>('scanCode', scanCode)); properties.add(DiagnosticsProperty<int>('keyCode', keyCode)); properties.add(DiagnosticsProperty<int>('modifiers', modifiers)); properties.add(DiagnosticsProperty<bool>('isDown', isDown)); properties.add(DiagnosticsProperty<int?>('specifiedLogicalKey', specifiedLogicalKey, defaultValue: null)); } @override bool operator==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is RawKeyEventDataLinux && other.keyHelper.runtimeType == keyHelper.runtimeType && other.unicodeScalarValues == unicodeScalarValues && other.scanCode == scanCode && other.keyCode == keyCode && other.modifiers == modifiers && other.isDown == isDown; } @override int get hashCode => Object.hash( keyHelper.runtimeType, unicodeScalarValues, scanCode, keyCode, modifiers, isDown, ); } /// Abstract class for window-specific key mappings. /// /// Given that there might be multiple window toolkit implementations (GLFW, /// GTK, QT, etc), this creates a common interface for each of the /// different toolkits. /// /// This class is deprecated and will be removed. Platform specific key event /// data will no longer be available. See [KeyEvent] for what is available. @Deprecated( 'No longer supported. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) abstract class KeyHelper { /// Create a KeyHelper implementation depending on the given toolkit. @Deprecated( 'No longer supported. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) factory KeyHelper(String toolkit) { if (toolkit == 'glfw') { return GLFWKeyHelper(); } else if (toolkit == 'gtk') { return GtkKeyHelper(); } else { throw FlutterError('Window toolkit not recognized: $toolkit'); } } /// Returns the name for the toolkit. /// /// This is used in debug mode to generate readable string. String get debugToolkit; /// Returns a [KeyboardSide] enum value that describes which side or sides of /// the given keyboard modifier key were pressed at the time of this event. @Deprecated( 'No longer supported. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) KeyboardSide getModifierSide(ModifierKey key); /// Returns true if the given [ModifierKey] was pressed at the time of this /// event. @Deprecated( 'No longer supported. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) bool isModifierPressed(ModifierKey key, int modifiers, {KeyboardSide side = KeyboardSide.any, required int keyCode, required bool isDown}); /// The numpad key from the specific key code mapping. LogicalKeyboardKey? numpadKey(int keyCode); /// The logical key from the specific key code mapping. LogicalKeyboardKey? logicalKey(int keyCode); /// The platform plane mask value of this platform. int get platformPlane; } /// Helper class that uses GLFW-specific key mappings. /// /// This class is deprecated and will be removed. Platform specific key event /// data will no longer be available. See [KeyEvent] for what is available. @Deprecated( 'No longer supported. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) class GLFWKeyHelper implements KeyHelper { /// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to /// test whether the CAPS LOCK modifier key is on. /// /// {@template flutter.services.GLFWKeyHelper.modifierCapsLock} /// Use this value if you need to decode the [RawKeyEventDataLinux.modifiers] /// field yourself, but it's much easier to use [isModifierPressed] if you /// just want to know if a modifier is pressed. This is especially true on /// GLFW, since its modifiers don't include the effects of the current key /// event. /// {@endtemplate} static const int modifierCapsLock = 0x0010; /// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to /// test whether one of the SHIFT modifier keys is pressed. /// /// {@macro flutter.services.GLFWKeyHelper.modifierCapsLock} static const int modifierShift = 0x0001; /// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to /// test whether one of the CTRL modifier keys is pressed. /// /// {@macro flutter.services.GLFWKeyHelper.modifierCapsLock} static const int modifierControl = 0x0002; /// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to /// test whether one of the ALT modifier keys is pressed. /// /// {@macro flutter.services.GLFWKeyHelper.modifierCapsLock} static const int modifierAlt = 0x0004; /// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to /// test whether one of the Meta(SUPER) modifier keys is pressed. /// /// {@macro flutter.services.GLFWKeyHelper.modifierCapsLock} static const int modifierMeta = 0x0008; /// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to /// test whether any key in the numeric keypad is pressed. /// /// {@macro flutter.services.GLFWKeyHelper.modifierCapsLock} static const int modifierNumericPad = 0x0020; @override String get debugToolkit => 'GLFW'; int _mergeModifiers({required int modifiers, required int keyCode, required bool isDown}) { // GLFW Key codes for modifier keys. const int shiftLeftKeyCode = 340; const int shiftRightKeyCode = 344; const int controlLeftKeyCode = 341; const int controlRightKeyCode = 345; const int altLeftKeyCode = 342; const int altRightKeyCode = 346; const int metaLeftKeyCode = 343; const int metaRightKeyCode = 347; const int capsLockKeyCode = 280; const int numLockKeyCode = 282; // On GLFW, the "modifiers" bitfield is the state as it is BEFORE this event // happened, not AFTER, like every other platform. Consequently, if this is // a key down, then we need to add the correct modifier bits, and if it's a // key up, we need to remove them. final int modifierChange = switch (keyCode) { shiftLeftKeyCode || shiftRightKeyCode => modifierShift, controlLeftKeyCode || controlRightKeyCode => modifierControl, altLeftKeyCode || altRightKeyCode => modifierAlt, metaLeftKeyCode || metaRightKeyCode => modifierMeta, capsLockKeyCode => modifierCapsLock, numLockKeyCode => modifierNumericPad, _ => 0, }; return isDown ? modifiers | modifierChange : modifiers & ~modifierChange; } @override bool isModifierPressed(ModifierKey key, int modifiers, {KeyboardSide side = KeyboardSide.any, required int keyCode, required bool isDown}) { modifiers = _mergeModifiers(modifiers: modifiers, keyCode: keyCode, isDown: isDown); return switch (key) { ModifierKey.controlModifier => modifiers & modifierControl != 0, ModifierKey.shiftModifier => modifiers & modifierShift != 0, ModifierKey.altModifier => modifiers & modifierAlt != 0, ModifierKey.metaModifier => modifiers & modifierMeta != 0, ModifierKey.capsLockModifier => modifiers & modifierCapsLock != 0, ModifierKey.numLockModifier => modifiers & modifierNumericPad != 0, // These are not used in GLFW keyboards. ModifierKey.functionModifier => false, ModifierKey.symbolModifier => false, ModifierKey.scrollLockModifier => false, }; } @override KeyboardSide getModifierSide(ModifierKey key) { // Neither GLFW nor X11 provide a distinction between left and right // modifiers, so defaults to KeyboardSide.all. // https://code.woboq.org/qt5/include/X11/X.h.html#_M/ShiftMask return KeyboardSide.all; } @override LogicalKeyboardKey? numpadKey(int keyCode) { return kGlfwNumpadMap[keyCode]; } @override LogicalKeyboardKey? logicalKey(int keyCode) { return kGlfwToLogicalKey[keyCode]; } @override int get platformPlane => LogicalKeyboardKey.glfwPlane; } /// Helper class that uses GTK-specific key mappings. /// /// This class is deprecated and will be removed. Platform specific key event /// data will no longer be available. See [KeyEvent] for what is available. @Deprecated( 'No longer supported. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) class GtkKeyHelper implements KeyHelper { /// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to /// test whether one of the SHIFT modifier keys is pressed. /// /// {@template flutter.services.GtkKeyHelper.modifierShift} /// Use this value if you need to decode the [RawKeyEventDataLinux.modifiers] field yourself, but /// it's much easier to use [isModifierPressed] if you just want to know if a /// modifier is pressed. This is especially true on GTK, since its modifiers /// don't include the effects of the current key event. /// {@endtemplate} static const int modifierShift = 1 << 0; /// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to /// test whether the CAPS LOCK modifier key is on. /// /// {@macro flutter.services.GtkKeyHelper.modifierShift} static const int modifierCapsLock = 1 << 1; /// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to /// test whether one of the CTRL modifier keys is pressed. /// /// {@macro flutter.services.GtkKeyHelper.modifierShift} static const int modifierControl = 1 << 2; /// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to /// test whether the first modifier key is pressed (usually mapped to alt). /// /// {@macro flutter.services.GtkKeyHelper.modifierShift} static const int modifierMod1 = 1 << 3; /// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to /// test whether the second modifier key is pressed (assumed to be mapped to /// num lock). /// /// {@macro flutter.services.GtkKeyHelper.modifierShift} static const int modifierMod2 = 1 << 4; /// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to /// test whether one of the Meta(SUPER) modifier keys is pressed. /// /// {@macro flutter.services.GtkKeyHelper.modifierShift} static const int modifierMeta = 1 << 26; @override String get debugToolkit => 'GTK'; int _mergeModifiers({required int modifiers, required int keyCode, required bool isDown}) { // GTK Key codes for modifier keys. const int shiftLeftKeyCode = 0xffe1; const int shiftRightKeyCode = 0xffe2; const int controlLeftKeyCode = 0xffe3; const int controlRightKeyCode = 0xffe4; const int capsLockKeyCode = 0xffe5; const int shiftLockKeyCode = 0xffe6; const int altLeftKeyCode = 0xffe9; const int altRightKeyCode = 0xffea; const int metaLeftKeyCode = 0xffeb; const int metaRightKeyCode = 0xffec; const int numLockKeyCode = 0xff7f; // On GTK, the "modifiers" bitfield is the state as it is BEFORE this event // happened, not AFTER, like every other platform. Consequently, if this is // a key down, then we need to add the correct modifier bits, and if it's a // key up, we need to remove them. final int modifierChange = switch (keyCode) { shiftLeftKeyCode || shiftRightKeyCode => modifierShift, controlLeftKeyCode || controlRightKeyCode => modifierControl, altLeftKeyCode || altRightKeyCode => modifierMod1, metaLeftKeyCode || metaRightKeyCode => modifierMeta, capsLockKeyCode || shiftLockKeyCode => modifierCapsLock, numLockKeyCode => modifierMod2, _ => 0, }; return isDown ? modifiers | modifierChange : modifiers & ~modifierChange; } @override bool isModifierPressed(ModifierKey key, int modifiers, {KeyboardSide side = KeyboardSide.any, required int keyCode, required bool isDown}) { modifiers = _mergeModifiers(modifiers: modifiers, keyCode: keyCode, isDown: isDown); return switch (key) { ModifierKey.controlModifier => modifiers & modifierControl != 0, ModifierKey.shiftModifier => modifiers & modifierShift != 0, ModifierKey.altModifier => modifiers & modifierMod1 != 0, ModifierKey.metaModifier => modifiers & modifierMeta != 0, ModifierKey.capsLockModifier => modifiers & modifierCapsLock != 0, ModifierKey.numLockModifier => modifiers & modifierMod2 != 0, // These are not used in GTK keyboards. ModifierKey.functionModifier => false, ModifierKey.symbolModifier => false, ModifierKey.scrollLockModifier => false, }; } @override KeyboardSide getModifierSide(ModifierKey key) { // Neither GTK nor X11 provide a distinction between left and right // modifiers, so defaults to KeyboardSide.all. // https://code.woboq.org/qt5/include/X11/X.h.html#_M/ShiftMask return KeyboardSide.all; } @override LogicalKeyboardKey? numpadKey(int keyCode) { return kGtkNumpadMap[keyCode]; } @override LogicalKeyboardKey? logicalKey(int keyCode) { return kGtkToLogicalKey[keyCode]; } @override int get platformPlane => LogicalKeyboardKey.gtkPlane; }
flutter/packages/flutter/lib/src/services/raw_keyboard_linux.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/services/raw_keyboard_linux.dart", "repo_id": "flutter", "token_count": 6022 }
646
// 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:ui' show TextRange; import 'text_editing.dart'; export 'dart:ui' show TextPosition, TextRange; export 'text_editing.dart' show TextSelection; /// A read-only interface for accessing visual information about the /// implementing text. abstract class TextLayoutMetrics { // TODO(gspencergoog): replace when we expose this ICU information. /// Check if the given code unit is a white space or separator /// character. /// /// Includes newline characters from ASCII and separators from the /// [unicode separator category](https://www.compart.com/en/unicode/category/Zs) static bool isWhitespace(int codeUnit) { switch (codeUnit) { case 0x9: // horizontal tab case 0xA: // line feed case 0xB: // vertical tab case 0xC: // form feed case 0xD: // carriage return case 0x1C: // file separator case 0x1D: // group separator case 0x1E: // record separator case 0x1F: // unit separator case 0x20: // space case 0xA0: // no-break space case 0x1680: // ogham space mark case 0x2000: // en quad case 0x2001: // em quad case 0x2002: // en space case 0x2003: // em space case 0x2004: // three-per-em space case 0x2005: // four-er-em space case 0x2006: // six-per-em space case 0x2007: // figure space case 0x2008: // punctuation space case 0x2009: // thin space case 0x200A: // hair space case 0x202F: // narrow no-break space case 0x205F: // medium mathematical space case 0x3000: // ideographic space break; default: return false; } return true; } /// Check if the given code unit is a line terminator character. /// /// Includes newline characters from ASCII /// (https://www.unicode.org/standard/reports/tr13/tr13-5.html). static bool isLineTerminator(int codeUnit) { switch (codeUnit) { case 0x0A: // line feed case 0x0B: // vertical feed case 0x0C: // form feed case 0x0D: // carriage return case 0x85: // new line case 0x2028: // line separator case 0x2029: // paragraph separator return true; default: return false; } } /// {@template flutter.services.TextLayoutMetrics.getLineAtOffset} /// Return a [TextSelection] containing the line of the given [TextPosition]. /// {@endtemplate} TextSelection getLineAtOffset(TextPosition position); /// {@macro flutter.painting.TextPainter.getWordBoundary} TextRange getWordBoundary(TextPosition position); /// {@template flutter.services.TextLayoutMetrics.getTextPositionAbove} /// Returns the TextPosition above the given offset into the text. /// /// If the offset is already on the first line, the given offset will be /// returned. /// {@endtemplate} TextPosition getTextPositionAbove(TextPosition position); /// {@template flutter.services.TextLayoutMetrics.getTextPositionBelow} /// Returns the TextPosition below the given offset into the text. /// /// If the offset is already on the last line, the given offset will be /// returned. /// {@endtemplate} TextPosition getTextPositionBelow(TextPosition position); }
flutter/packages/flutter/lib/src/services/text_layout_metrics.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/services/text_layout_metrics.dart", "repo_id": "flutter", "token_count": 1171 }
647
// 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' show StreamSubscription; import 'package:flutter/foundation.dart'; import 'framework.dart'; /// Base class for widgets that build themselves based on interaction with /// a specified [Stream]. /// /// A [StreamBuilderBase] is stateful and maintains a summary of the interaction /// so far. The type of the summary and how it is updated with each interaction /// is defined by sub-classes. /// /// Examples of summaries include: /// /// * the running average of a stream of integers; /// * the current direction and speed based on a stream of geolocation data; /// * a graph displaying data points from a stream. /// /// In general, the summary is the result of a fold computation over the data /// items and errors received from the stream along with pseudo-events /// representing termination or change of stream. The initial summary is /// specified by sub-classes by overriding [initial]. The summary updates on /// receipt of stream data and errors are specified by overriding [afterData] and /// [afterError], respectively. If needed, the summary may be updated on stream /// termination by overriding [afterDone]. Finally, the summary may be updated /// on change of stream by overriding [afterDisconnected] and [afterConnected]. /// /// `T` is the type of stream events. /// /// `S` is the type of interaction summary. /// /// See also: /// /// * [StreamBuilder], which is specialized for the case where only the most /// recent interaction is needed for widget building. abstract class StreamBuilderBase<T, S> extends StatefulWidget { /// Creates a [StreamBuilderBase] connected to the specified [stream]. const StreamBuilderBase({ super.key, required this.stream }); /// The asynchronous computation to which this builder is currently connected, /// possibly null. When changed, the current summary is updated using /// [afterDisconnected], if the previous stream was not null, followed by /// [afterConnected], if the new stream is not null. final Stream<T>? stream; /// Returns the initial summary of stream interaction, typically representing /// the fact that no interaction has happened at all. /// /// Sub-classes must override this method to provide the initial value for /// the fold computation. S initial(); /// Returns an updated version of the [current] summary reflecting that we /// are now connected to a stream. /// /// The default implementation returns [current] as is. S afterConnected(S current) => current; /// Returns an updated version of the [current] summary following a data event. /// /// Sub-classes must override this method to specify how the current summary /// is combined with the new data item in the fold computation. S afterData(S current, T data); /// Returns an updated version of the [current] summary following an error /// with a stack trace. /// /// The default implementation returns [current] as is. S afterError(S current, Object error, StackTrace stackTrace) => current; /// Returns an updated version of the [current] summary following stream /// termination. /// /// The default implementation returns [current] as is. S afterDone(S current) => current; /// Returns an updated version of the [current] summary reflecting that we /// are no longer connected to a stream. /// /// The default implementation returns [current] as is. S afterDisconnected(S current) => current; /// Returns a Widget based on the [currentSummary]. Widget build(BuildContext context, S currentSummary); @override State<StreamBuilderBase<T, S>> createState() => _StreamBuilderBaseState<T, S>(); } /// State for [StreamBuilderBase]. class _StreamBuilderBaseState<T, S> extends State<StreamBuilderBase<T, S>> { StreamSubscription<T>? _subscription; late S _summary; @override void initState() { super.initState(); _summary = widget.initial(); _subscribe(); } @override void didUpdateWidget(StreamBuilderBase<T, S> oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.stream != widget.stream) { if (_subscription != null) { _unsubscribe(); _summary = widget.afterDisconnected(_summary); } _subscribe(); } } @override Widget build(BuildContext context) => widget.build(context, _summary); @override void dispose() { _unsubscribe(); super.dispose(); } void _subscribe() { if (widget.stream != null) { _subscription = widget.stream!.listen((T data) { setState(() { _summary = widget.afterData(_summary, data); }); }, onError: (Object error, StackTrace stackTrace) { setState(() { _summary = widget.afterError(_summary, error, stackTrace); }); }, onDone: () { setState(() { _summary = widget.afterDone(_summary); }); }); _summary = widget.afterConnected(_summary); } } void _unsubscribe() { if (_subscription != null) { _subscription!.cancel(); _subscription = null; } } } /// The state of connection to an asynchronous computation. /// /// The usual flow of state is as follows: /// /// 1. [none], maybe with some initial data. /// 2. [waiting], indicating that the asynchronous operation has begun, /// typically with the data being null. /// 3. [active], with data being non-null, and possible changing over time. /// 4. [done], with data being non-null. /// /// See also: /// /// * [AsyncSnapshot], which augments a connection state with information /// received from the asynchronous computation. enum ConnectionState { /// Not currently connected to any asynchronous computation. /// /// For example, a [FutureBuilder] whose [FutureBuilder.future] is null. none, /// Connected to an asynchronous computation and awaiting interaction. waiting, /// Connected to an active asynchronous computation. /// /// For example, a [Stream] that has returned at least one value, but is not /// yet done. active, /// Connected to a terminated asynchronous computation. done, } /// Immutable representation of the most recent interaction with an asynchronous /// computation. /// /// See also: /// /// * [StreamBuilder], which builds itself based on a snapshot from interacting /// with a [Stream]. /// * [FutureBuilder], which builds itself based on a snapshot from interacting /// with a [Future]. @immutable class AsyncSnapshot<T> { /// Creates an [AsyncSnapshot] with the specified [connectionState], /// and optionally either [data] or [error] with an optional [stackTrace] /// (but not both data and error). const AsyncSnapshot._(this.connectionState, this.data, this.error, this.stackTrace) : assert(data == null || error == null), assert(stackTrace == null || error != null); /// Creates an [AsyncSnapshot] in [ConnectionState.none] with null data and error. const AsyncSnapshot.nothing() : this._(ConnectionState.none, null, null, null); /// Creates an [AsyncSnapshot] in [ConnectionState.waiting] with null data and error. const AsyncSnapshot.waiting() : this._(ConnectionState.waiting, null, null, null); /// Creates an [AsyncSnapshot] in the specified [state] and with the specified [data]. const AsyncSnapshot.withData(ConnectionState state, T data): this._(state, data, null, null); /// Creates an [AsyncSnapshot] in the specified [state] with the specified [error] /// and a [stackTrace]. /// /// If no [stackTrace] is explicitly specified, [StackTrace.empty] will be used instead. const AsyncSnapshot.withError( ConnectionState state, Object error, [ StackTrace stackTrace = StackTrace.empty, ]) : this._(state, null, error, stackTrace); /// Current state of connection to the asynchronous computation. final ConnectionState connectionState; /// The latest data received by the asynchronous computation. /// /// If this is non-null, [hasData] will be true. /// /// If [error] is not null, this will be null. See [hasError]. /// /// If the asynchronous computation has never returned a value, this may be /// set to an initial data value specified by the relevant widget. See /// [FutureBuilder.initialData] and [StreamBuilder.initialData]. final T? data; /// Returns latest data received, failing if there is no data. /// /// Throws [error], if [hasError]. Throws [StateError], if neither [hasData] /// nor [hasError]. T get requireData { if (hasData) { return data!; } if (hasError) { Error.throwWithStackTrace(error!, stackTrace!); } throw StateError('Snapshot has neither data nor error'); } /// The latest error object received by the asynchronous computation. /// /// If this is non-null, [hasError] will be true. /// /// If [data] is not null, this will be null. final Object? error; /// The latest stack trace object received by the asynchronous computation. /// /// This will not be null iff [error] is not null. Consequently, [stackTrace] /// will be non-null when [hasError] is true. /// /// However, even when not null, [stackTrace] might be empty. The stack trace /// is empty when there is an error but no stack trace has been provided. final StackTrace? stackTrace; /// Returns a snapshot like this one, but in the specified [state]. /// /// The [data], [error], and [stackTrace] fields persist unmodified, even if /// the new state is [ConnectionState.none]. AsyncSnapshot<T> inState(ConnectionState state) => AsyncSnapshot<T>._(state, data, error, stackTrace); /// Returns whether this snapshot contains a non-null [data] value. /// /// This can be false even when the asynchronous computation has completed /// successfully, if the computation did not return a non-null value. For /// example, a [Future<void>] will complete with the null value even if it /// completes successfully. bool get hasData => data != null; /// Returns whether this snapshot contains a non-null [error] value. /// /// This is always true if the asynchronous computation's last result was /// failure. bool get hasError => error != null; @override String toString() => '${objectRuntimeType(this, 'AsyncSnapshot')}($connectionState, $data, $error, $stackTrace)'; @override bool operator ==(Object other) { if (identical(this, other)) { return true; } return other is AsyncSnapshot<T> && other.connectionState == connectionState && other.data == data && other.error == error && other.stackTrace == stackTrace; } @override int get hashCode => Object.hash(connectionState, data, error); } /// Signature for strategies that build widgets based on asynchronous /// interaction. /// /// See also: /// /// * [StreamBuilder], which delegates to an [AsyncWidgetBuilder] to build /// itself based on a snapshot from interacting with a [Stream]. /// * [FutureBuilder], which delegates to an [AsyncWidgetBuilder] to build /// itself based on a snapshot from interacting with a [Future]. typedef AsyncWidgetBuilder<T> = Widget Function(BuildContext context, AsyncSnapshot<T> snapshot); /// Widget that builds itself based on the latest snapshot of interaction with /// a [Stream]. /// /// {@youtube 560 315 https://www.youtube.com/watch?v=MkKEWHfy99Y} /// /// ## Managing the stream /// /// The [stream] must have been obtained earlier, e.g. during [State.initState], /// [State.didUpdateWidget], or [State.didChangeDependencies]. It must not be /// created during the [State.build] or [StatelessWidget.build] method call when /// constructing the [StreamBuilder]. If the [stream] is created at the same /// time as the [StreamBuilder], then every time the [StreamBuilder]'s parent is /// rebuilt, the asynchronous task will be restarted. /// /// A general guideline is to assume that every `build` method could get called /// every frame, and to treat omitted calls as an optimization. /// /// ## Timing /// /// Widget rebuilding is scheduled by each interaction, using [State.setState], /// but is otherwise decoupled from the timing of the stream. The [builder] /// is called at the discretion of the Flutter pipeline, and will thus receive a /// timing-dependent sub-sequence of the snapshots that represent the /// interaction with the stream. /// /// As an example, when interacting with a stream producing the integers /// 0 through 9, the [builder] may be called with any ordered sub-sequence /// of the following snapshots that includes the last one (the one with /// ConnectionState.done): /// /// * `AsyncSnapshot<int>.withData(ConnectionState.waiting, null)` /// * `AsyncSnapshot<int>.withData(ConnectionState.active, 0)` /// * `AsyncSnapshot<int>.withData(ConnectionState.active, 1)` /// * ... /// * `AsyncSnapshot<int>.withData(ConnectionState.active, 9)` /// * `AsyncSnapshot<int>.withData(ConnectionState.done, 9)` /// /// The actual sequence of invocations of the [builder] depends on the relative /// timing of events produced by the stream and the build rate of the Flutter /// pipeline. /// /// Changing the [StreamBuilder] configuration to another stream during event /// generation introduces snapshot pairs of the form: /// /// * `AsyncSnapshot<int>.withData(ConnectionState.none, 5)` /// * `AsyncSnapshot<int>.withData(ConnectionState.waiting, 5)` /// /// The latter will be produced only when the new stream is non-null, and the /// former only when the old stream is non-null. /// /// The stream may produce errors, resulting in snapshots of the form: /// /// * `AsyncSnapshot<int>.withError(ConnectionState.active, 'some error', someStackTrace)` /// /// The data and error fields of snapshots produced are only changed when the /// state is `ConnectionState.active`. /// /// The initial snapshot data can be controlled by specifying [initialData]. /// This should be used to ensure that the first frame has the expected value, /// as the builder will always be called before the stream listener has a chance /// to be processed. /// /// {@tool dartpad} /// This sample shows a [StreamBuilder] that listens to a Stream that emits bids /// for an auction. Every time the StreamBuilder receives a bid from the Stream, /// it will display the price of the bid below an icon. If the Stream emits an /// error, the error is displayed below an error icon. When the Stream finishes /// emitting bids, the final price is displayed. /// /// ** See code in examples/api/lib/widgets/async/stream_builder.0.dart ** /// {@end-tool} /// /// See also: /// /// * [ValueListenableBuilder], which wraps a [ValueListenable] instead of a /// [Stream]. /// * [StreamBuilderBase], which supports widget building based on a computation /// that spans all interactions made with the stream. class StreamBuilder<T> extends StreamBuilderBase<T, AsyncSnapshot<T>> { /// Creates a new [StreamBuilder] that builds itself based on the latest /// snapshot of interaction with the specified [stream] and whose build /// strategy is given by [builder]. /// /// The [initialData] is used to create the initial snapshot. const StreamBuilder({ super.key, this.initialData, required super.stream, required this.builder, }); /// The build strategy currently used by this builder. /// /// This builder must only return a widget and should not have any side /// effects as it may be called multiple times. final AsyncWidgetBuilder<T> builder; /// The data that will be used to create the initial snapshot. /// /// Providing this value (presumably obtained synchronously somehow when the /// [Stream] was created) ensures that the first frame will show useful data. /// Otherwise, the first frame will be built with the value null, regardless /// of whether a value is available on the stream: since streams are /// asynchronous, no events from the stream can be obtained before the initial /// build. final T? initialData; @override AsyncSnapshot<T> initial() => initialData == null ? AsyncSnapshot<T>.nothing() : AsyncSnapshot<T>.withData(ConnectionState.none, initialData as T); @override AsyncSnapshot<T> afterConnected(AsyncSnapshot<T> current) => current.inState(ConnectionState.waiting); @override AsyncSnapshot<T> afterData(AsyncSnapshot<T> current, T data) { return AsyncSnapshot<T>.withData(ConnectionState.active, data); } @override AsyncSnapshot<T> afterError(AsyncSnapshot<T> current, Object error, StackTrace stackTrace) { return AsyncSnapshot<T>.withError(ConnectionState.active, error, stackTrace); } @override AsyncSnapshot<T> afterDone(AsyncSnapshot<T> current) => current.inState(ConnectionState.done); @override AsyncSnapshot<T> afterDisconnected(AsyncSnapshot<T> current) => current.inState(ConnectionState.none); @override Widget build(BuildContext context, AsyncSnapshot<T> currentSummary) => builder(context, currentSummary); } /// A widget that builds itself based on the latest snapshot of interaction with /// a [Future]. /// /// {@youtube 560 315 https://www.youtube.com/watch?v=zEdw_1B7JHY} /// /// ## Managing the future /// /// The [future] must have been obtained earlier, e.g. during [State.initState], /// [State.didUpdateWidget], or [State.didChangeDependencies]. It must not be /// created during the [State.build] or [StatelessWidget.build] method call when /// constructing the [FutureBuilder]. If the [future] is created at the same /// time as the [FutureBuilder], then every time the [FutureBuilder]'s parent is /// rebuilt, the asynchronous task will be restarted. /// /// A general guideline is to assume that every `build` method could get called /// every frame, and to treat omitted calls as an optimization. /// /// ## Timing /// /// Widget rebuilding is scheduled by the completion of the future, using /// [State.setState], but is otherwise decoupled from the timing of the future. /// The [builder] callback is called at the discretion of the Flutter pipeline, and /// will thus receive a timing-dependent sub-sequence of the snapshots that /// represent the interaction with the future. /// /// A side-effect of this is that providing a new but already-completed future /// to a [FutureBuilder] will result in a single frame in the /// [ConnectionState.waiting] state. This is because there is no way to /// synchronously determine that a [Future] has already completed. /// /// ## Builder contract /// /// For a future that completes successfully with data, assuming [initialData] /// is null, the [builder] will be called with either both or only the latter of /// the following snapshots: /// /// * `AsyncSnapshot<String>.withData(ConnectionState.waiting, null)` /// * `AsyncSnapshot<String>.withData(ConnectionState.done, 'some data')` /// /// If that same future instead completed with an error, the [builder] would be /// called with either both or only the latter of: /// /// * `AsyncSnapshot<String>.withData(ConnectionState.waiting, null)` /// * `AsyncSnapshot<String>.withError(ConnectionState.done, 'some error', someStackTrace)` /// /// The initial snapshot data can be controlled by specifying [initialData]. You /// would use this facility to ensure that if the [builder] is invoked before /// the future completes, the snapshot carries data of your choice rather than /// the default null value. /// /// The data and error fields of the snapshot change only as the connection /// state field transitions from `waiting` to `done`, and they will be retained /// when changing the [FutureBuilder] configuration to another future. If the /// old future has already completed successfully with data as above, changing /// configuration to a new future results in snapshot pairs of the form: /// /// * `AsyncSnapshot<String>.withData(ConnectionState.none, 'data of first future')` /// * `AsyncSnapshot<String>.withData(ConnectionState.waiting, 'data of second future')` /// /// In general, the latter will be produced only when the new future is /// non-null, and the former only when the old future is non-null. /// /// A [FutureBuilder] behaves identically to a [StreamBuilder] configured with /// `future?.asStream()`, except that snapshots with `ConnectionState.active` /// may appear for the latter, depending on how the stream is implemented. /// /// {@tool dartpad} /// This sample shows a [FutureBuilder] that displays a loading spinner while it /// loads data. It displays a success icon and text if the [Future] completes /// with a result, or an error icon and text if the [Future] completes with an /// error. Assume the `_calculation` field is set by pressing a button elsewhere /// in the UI. /// /// ** See code in examples/api/lib/widgets/async/future_builder.0.dart ** /// {@end-tool} class FutureBuilder<T> extends StatefulWidget { /// Creates a widget that builds itself based on the latest snapshot of /// interaction with a [Future]. const FutureBuilder({ super.key, required this.future, this.initialData, required this.builder, }); /// The asynchronous computation to which this builder is currently connected, /// possibly null. /// /// If no future has yet completed, including in the case where [future] is /// null, the data provided to the [builder] will be set to [initialData]. final Future<T>? future; /// The build strategy currently used by this builder. /// /// The builder is provided with an [AsyncSnapshot] object whose /// [AsyncSnapshot.connectionState] property will be one of the following /// values: /// /// * [ConnectionState.none]: [future] is null. The [AsyncSnapshot.data] will /// be set to [initialData], unless a future has previously completed, in /// which case the previous result persists. /// /// * [ConnectionState.waiting]: [future] is not null, but has not yet /// completed. The [AsyncSnapshot.data] will be set to [initialData], /// unless a future has previously completed, in which case the previous /// result persists. /// /// * [ConnectionState.done]: [future] is not null, and has completed. If the /// future completed successfully, the [AsyncSnapshot.data] will be set to /// the value to which the future completed. If it completed with an error, /// [AsyncSnapshot.hasError] will be true and [AsyncSnapshot.error] will be /// set to the error object. /// /// This builder must only return a widget and should not have any side /// effects as it may be called multiple times. final AsyncWidgetBuilder<T> builder; /// The data that will be used to create the snapshots provided until a /// non-null [future] has completed. /// /// If the future completes with an error, the data in the [AsyncSnapshot] /// provided to the [builder] will become null, regardless of [initialData]. /// (The error itself will be available in [AsyncSnapshot.error], and /// [AsyncSnapshot.hasError] will be true.) final T? initialData; /// Whether the latest error received by the asynchronous computation should /// be rethrown or swallowed. This property is useful for debugging purposes. /// /// When set to true, will rethrow the latest error only in debug mode. /// /// Defaults to `false`, resulting in swallowing of errors. static bool debugRethrowError = false; @override State<FutureBuilder<T>> createState() => _FutureBuilderState<T>(); } /// State for [FutureBuilder]. class _FutureBuilderState<T> extends State<FutureBuilder<T>> { /// An object that identifies the currently active callbacks. Used to avoid /// calling setState from stale callbacks, e.g. after disposal of this state, /// or after widget reconfiguration to a new Future. Object? _activeCallbackIdentity; late AsyncSnapshot<T> _snapshot; @override void initState() { super.initState(); _snapshot = widget.initialData == null ? AsyncSnapshot<T>.nothing() : AsyncSnapshot<T>.withData(ConnectionState.none, widget.initialData as T); _subscribe(); } @override void didUpdateWidget(FutureBuilder<T> oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.future == widget.future) { return; } if (_activeCallbackIdentity != null) { _unsubscribe(); _snapshot = _snapshot.inState(ConnectionState.none); } _subscribe(); } @override Widget build(BuildContext context) => widget.builder(context, _snapshot); @override void dispose() { _unsubscribe(); super.dispose(); } void _subscribe() { if (widget.future == null) { // There is no future to subscribe to, do nothing. return; } final Object callbackIdentity = Object(); _activeCallbackIdentity = callbackIdentity; widget.future!.then<void>((T data) { if (_activeCallbackIdentity == callbackIdentity) { setState(() { _snapshot = AsyncSnapshot<T>.withData(ConnectionState.done, data); }); } }, onError: (Object error, StackTrace stackTrace) { if (_activeCallbackIdentity == callbackIdentity) { setState(() { _snapshot = AsyncSnapshot<T>.withError(ConnectionState.done, error, stackTrace); }); } assert(() { if (FutureBuilder.debugRethrowError) { Future<Object>.error(error, stackTrace); } return true; }()); }); // An implementation like `SynchronousFuture` may have already called the // .then closure. Do not overwrite it in that case. if (_snapshot.connectionState != ConnectionState.done) { _snapshot = _snapshot.inState(ConnectionState.waiting); } } void _unsubscribe() { _activeCallbackIdentity = null; } }
flutter/packages/flutter/lib/src/widgets/async.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/async.dart", "repo_id": "flutter", "token_count": 7352 }
648
// 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 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; import 'package:flutter/services.dart'; import 'actions.dart'; import 'focus_traversal.dart'; import 'framework.dart'; import 'scrollable_helpers.dart'; import 'shortcuts.dart'; import 'text_editing_intents.dart'; /// A widget with the shortcuts used for the default text editing behavior. /// /// This default behavior can be overridden by placing a [Shortcuts] widget /// lower in the widget tree than this. See the [Action] class for an example /// of remapping an [Intent] to a custom [Action]. /// /// The [Shortcuts] widget usually takes precedence over system keybindings. /// Proceed with caution if the shortcut you wish to override is also used by /// the system. For example, overriding [LogicalKeyboardKey.backspace] could /// cause CJK input methods to discard more text than they should when the /// backspace key is pressed during text composition on iOS. /// /// {@macro flutter.widgets.editableText.shortcutsAndTextInput} /// /// {@tool snippet} /// /// This example shows how to use an additional [Shortcuts] widget to override /// some default text editing keyboard shortcuts to have new behavior. Instead /// of moving the cursor, alt + up/down will change the focused widget. /// /// ```dart /// @override /// Widget build(BuildContext context) { /// // If using WidgetsApp or its descendants MaterialApp or CupertinoApp, /// // then DefaultTextEditingShortcuts is already being inserted into the /// // widget tree. /// return const DefaultTextEditingShortcuts( /// child: Center( /// child: Shortcuts( /// shortcuts: <ShortcutActivator, Intent>{ /// SingleActivator(LogicalKeyboardKey.arrowDown, alt: true): NextFocusIntent(), /// SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): PreviousFocusIntent(), /// }, /// child: Column( /// children: <Widget>[ /// TextField( /// decoration: InputDecoration( /// hintText: 'alt + down moves to the next field.', /// ), /// ), /// TextField( /// decoration: InputDecoration( /// hintText: 'And alt + up moves to the previous.', /// ), /// ), /// ], /// ), /// ), /// ), /// ); /// } /// ``` /// {@end-tool} /// /// {@tool snippet} /// /// This example shows how to use an additional [Shortcuts] widget to override /// default text editing shortcuts to have completely custom behavior defined by /// a custom Intent and Action. Here, the up/down arrow keys increment/decrement /// a counter instead of moving the cursor. /// /// ```dart /// class IncrementCounterIntent extends Intent {} /// class DecrementCounterIntent extends Intent {} /// /// class MyWidget extends StatefulWidget { /// const MyWidget({ super.key }); /// /// @override /// MyWidgetState createState() => MyWidgetState(); /// } /// /// class MyWidgetState extends State<MyWidget> { /// /// int _counter = 0; /// /// @override /// Widget build(BuildContext context) { /// // If using WidgetsApp or its descendants MaterialApp or CupertinoApp, /// // then DefaultTextEditingShortcuts is already being inserted into the /// // widget tree. /// return DefaultTextEditingShortcuts( /// child: Center( /// child: Column( /// mainAxisAlignment: MainAxisAlignment.center, /// children: <Widget>[ /// const Text( /// 'You have pushed the button this many times:', /// ), /// Text( /// '$_counter', /// style: Theme.of(context).textTheme.headlineMedium, /// ), /// Shortcuts( /// shortcuts: <ShortcutActivator, Intent>{ /// const SingleActivator(LogicalKeyboardKey.arrowUp): IncrementCounterIntent(), /// const SingleActivator(LogicalKeyboardKey.arrowDown): DecrementCounterIntent(), /// }, /// child: Actions( /// actions: <Type, Action<Intent>>{ /// IncrementCounterIntent: CallbackAction<IncrementCounterIntent>( /// onInvoke: (IncrementCounterIntent intent) { /// setState(() { /// _counter++; /// }); /// return null; /// }, /// ), /// DecrementCounterIntent: CallbackAction<DecrementCounterIntent>( /// onInvoke: (DecrementCounterIntent intent) { /// setState(() { /// _counter--; /// }); /// return null; /// }, /// ), /// }, /// child: const TextField( /// maxLines: 2, /// decoration: InputDecoration( /// hintText: 'Up/down increment/decrement here.', /// ), /// ), /// ), /// ), /// const TextField( /// maxLines: 2, /// decoration: InputDecoration( /// hintText: 'Up/down behave normally here.', /// ), /// ), /// ], /// ), /// ), /// ); /// } /// } /// ``` /// {@end-tool} /// /// See also: /// /// * [WidgetsApp], which creates a DefaultTextEditingShortcuts. class DefaultTextEditingShortcuts extends StatelessWidget { /// Creates a [DefaultTextEditingShortcuts] widget that provides the default text editing /// shortcuts on the current platform. const DefaultTextEditingShortcuts({ super.key, required this.child, }); /// {@macro flutter.widgets.ProxyWidget.child} final Widget child; // These shortcuts are shared between all platforms except Apple platforms, // because they use different modifier keys as the line/word modifier. static final Map<ShortcutActivator, Intent> _commonShortcuts = <ShortcutActivator, Intent>{ // Delete Shortcuts. for (final bool pressShift in const <bool>[true, false]) ...<SingleActivator, Intent>{ SingleActivator(LogicalKeyboardKey.backspace, shift: pressShift): const DeleteCharacterIntent(forward: false), SingleActivator(LogicalKeyboardKey.backspace, control: true, shift: pressShift): const DeleteToNextWordBoundaryIntent(forward: false), SingleActivator(LogicalKeyboardKey.backspace, alt: true, shift: pressShift): const DeleteToLineBreakIntent(forward: false), SingleActivator(LogicalKeyboardKey.delete, shift: pressShift): const DeleteCharacterIntent(forward: true), SingleActivator(LogicalKeyboardKey.delete, control: true, shift: pressShift): const DeleteToNextWordBoundaryIntent(forward: true), SingleActivator(LogicalKeyboardKey.delete, alt: true, shift: pressShift): const DeleteToLineBreakIntent(forward: true), }, // Arrow: Move selection. const SingleActivator(LogicalKeyboardKey.arrowLeft): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowRight): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowUp): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowDown): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true), // Shift + Arrow: Extend selection. const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowDown, alt: true): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, alt: true): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, alt: true): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.arrowLeft, control: true): const ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowRight, control: true): const ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, control: true): const ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, control: true): const ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, control: true): const ExtendSelectionToNextParagraphBoundaryIntent(forward: false, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, control: true): const ExtendSelectionToNextParagraphBoundaryIntent(forward: true, collapseSelection: false), // Page Up / Down: Move selection by page. const SingleActivator(LogicalKeyboardKey.pageUp): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.pageDown): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: true), // Shift + Page Up / Down: Extend selection by page. const SingleActivator(LogicalKeyboardKey.pageUp, shift: true): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.pageDown, shift: true): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.keyX, control: true): const CopySelectionTextIntent.cut(SelectionChangedCause.keyboard), const SingleActivator(LogicalKeyboardKey.keyC, control: true): CopySelectionTextIntent.copy, const SingleActivator(LogicalKeyboardKey.keyV, control: true): const PasteTextIntent(SelectionChangedCause.keyboard), const SingleActivator(LogicalKeyboardKey.keyA, control: true): const SelectAllTextIntent(SelectionChangedCause.keyboard), const SingleActivator(LogicalKeyboardKey.keyZ, control: true): const UndoTextIntent(SelectionChangedCause.keyboard), const SingleActivator(LogicalKeyboardKey.keyZ, shift: true, control: true): const RedoTextIntent(SelectionChangedCause.keyboard), // These keys should go to the IME when a field is focused, not to other // Shortcuts. const SingleActivator(LogicalKeyboardKey.space): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.enter): const DoNothingAndStopPropagationTextIntent(), }; // The following key combinations have no effect on text editing on this // platform: // * End // * Home // * Meta + X // * Meta + C // * Meta + V // * Meta + A // * Meta + shift? + Z // * Meta + shift? + arrow down // * Meta + shift? + arrow left // * Meta + shift? + arrow right // * Meta + shift? + arrow up // * Shift + end // * Shift + home // * Meta + shift? + delete // * Meta + shift? + backspace static final Map<ShortcutActivator, Intent> _androidShortcuts = _commonShortcuts; static final Map<ShortcutActivator, Intent> _fuchsiaShortcuts = _androidShortcuts; static final Map<ShortcutActivator, Intent> _linuxShortcuts = <ShortcutActivator, Intent>{ ..._commonShortcuts, const SingleActivator(LogicalKeyboardKey.home): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.end): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.home, shift: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.end, shift: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: false), // The following key combinations have no effect on text editing on this // platform: // * Control + shift? + end // * Control + shift? + home // * Meta + X // * Meta + C // * Meta + V // * Meta + A // * Meta + shift? + Z // * Meta + shift? + arrow down // * Meta + shift? + arrow left // * Meta + shift? + arrow right // * Meta + shift? + arrow up // * Meta + shift? + delete // * Meta + shift? + backspace }; // macOS document shortcuts: https://support.apple.com/en-us/HT201236. // The macOS shortcuts uses different word/line modifiers than most other // platforms. static final Map<ShortcutActivator, Intent> _macShortcuts = <ShortcutActivator, Intent>{ for (final bool pressShift in const <bool>[true, false]) ...<SingleActivator, Intent>{ SingleActivator(LogicalKeyboardKey.backspace, shift: pressShift): const DeleteCharacterIntent(forward: false), SingleActivator(LogicalKeyboardKey.backspace, alt: true, shift: pressShift): const DeleteToNextWordBoundaryIntent(forward: false), SingleActivator(LogicalKeyboardKey.backspace, meta: true, shift: pressShift): const DeleteToLineBreakIntent(forward: false), SingleActivator(LogicalKeyboardKey.delete, shift: pressShift): const DeleteCharacterIntent(forward: true), SingleActivator(LogicalKeyboardKey.delete, alt: true, shift: pressShift): const DeleteToNextWordBoundaryIntent(forward: true), SingleActivator(LogicalKeyboardKey.delete, meta: true, shift: pressShift): const DeleteToLineBreakIntent(forward: true), }, const SingleActivator(LogicalKeyboardKey.arrowLeft): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowRight): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowUp): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowDown): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true), // Shift + Arrow: Extend selection. const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true): const ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true): const ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowDown, alt: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: true): const ExtendSelectionToNextWordBoundaryOrCaretLocationIntent(forward: false), const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: true): const ExtendSelectionToNextWordBoundaryOrCaretLocationIntent(forward: true), const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, alt: true): const ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent(forward: false), const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, alt: true): const ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent(forward: true), const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowUp, meta: true): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowDown, meta: true): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, meta: true): const ExpandSelectionToLineBreakIntent(forward: false), const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, meta: true): const ExpandSelectionToLineBreakIntent(forward: true), const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, meta: true): const ExpandSelectionToDocumentBoundaryIntent(forward: false), const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, meta: true): const ExpandSelectionToDocumentBoundaryIntent(forward: true), const SingleActivator(LogicalKeyboardKey.keyT, control: true): const TransposeCharactersIntent(), const SingleActivator(LogicalKeyboardKey.home): const ScrollToDocumentBoundaryIntent(forward: false), const SingleActivator(LogicalKeyboardKey.end): const ScrollToDocumentBoundaryIntent(forward: true), const SingleActivator(LogicalKeyboardKey.home, shift: true): const ExpandSelectionToDocumentBoundaryIntent(forward: false), const SingleActivator(LogicalKeyboardKey.end, shift: true): const ExpandSelectionToDocumentBoundaryIntent(forward: true), const SingleActivator(LogicalKeyboardKey.pageUp): const ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page), const SingleActivator(LogicalKeyboardKey.pageDown): const ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page), const SingleActivator(LogicalKeyboardKey.pageUp, shift: true): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.pageDown, shift: true): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.keyX, meta: true): const CopySelectionTextIntent.cut(SelectionChangedCause.keyboard), const SingleActivator(LogicalKeyboardKey.keyC, meta: true): CopySelectionTextIntent.copy, const SingleActivator(LogicalKeyboardKey.keyV, meta: true): const PasteTextIntent(SelectionChangedCause.keyboard), const SingleActivator(LogicalKeyboardKey.keyA, meta: true): const SelectAllTextIntent(SelectionChangedCause.keyboard), const SingleActivator(LogicalKeyboardKey.keyZ, meta: true): const UndoTextIntent(SelectionChangedCause.keyboard), const SingleActivator(LogicalKeyboardKey.keyZ, shift: true, meta: true): const RedoTextIntent(SelectionChangedCause.keyboard), const SingleActivator(LogicalKeyboardKey.keyE, control: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.keyA, control: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.keyF, control: true): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.keyB, control: true): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.keyN, control: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.keyP, control: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true), // These keys should go to the IME when a field is focused, not to other // Shortcuts. const SingleActivator(LogicalKeyboardKey.space): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.enter): const DoNothingAndStopPropagationTextIntent(), // The following key combinations have no effect on text editing on this // platform: // * End // * Home // * Control + shift? + end // * Control + shift? + home // * Control + shift? + Z }; // There is no complete documentation of iOS shortcuts: use macOS ones. static final Map<ShortcutActivator, Intent> _iOSShortcuts = _macShortcuts; // The following key combinations have no effect on text editing on this // platform: // * Meta + X // * Meta + C // * Meta + V // * Meta + A // * Meta + shift? + arrow down // * Meta + shift? + arrow left // * Meta + shift? + arrow right // * Meta + shift? + arrow up // * Meta + delete // * Meta + backspace static final Map<ShortcutActivator, Intent> _windowsShortcuts = <ShortcutActivator, Intent>{ ..._commonShortcuts, const SingleActivator(LogicalKeyboardKey.pageUp): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.pageDown): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.home): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true, continuesAtWrap: true), const SingleActivator(LogicalKeyboardKey.end): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true, continuesAtWrap: true), const SingleActivator(LogicalKeyboardKey.home, shift: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: false, continuesAtWrap: true), const SingleActivator(LogicalKeyboardKey.end, shift: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: false, continuesAtWrap: true), const SingleActivator(LogicalKeyboardKey.home, control: true): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.end, control: true): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: true), const SingleActivator(LogicalKeyboardKey.home, shift: true, control: true): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: false), const SingleActivator(LogicalKeyboardKey.end, shift: true, control: true): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: false), }; // Web handles its text selection natively and doesn't use any of these // shortcuts in Flutter. static final Map<ShortcutActivator, Intent> _webDisablingTextShortcuts = <ShortcutActivator, Intent>{ for (final bool pressShift in const <bool>[true, false]) ...<SingleActivator, Intent>{ SingleActivator(LogicalKeyboardKey.backspace, shift: pressShift): const DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.delete, shift: pressShift): const DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.backspace, alt: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.delete, alt: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.backspace, control: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.delete, control: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.backspace, meta: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.delete, meta: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(), }, ..._commonDisablingTextShortcuts, const SingleActivator(LogicalKeyboardKey.keyX, control: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.keyX, meta: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.keyC, control: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.keyC, meta: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.keyV, control: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.keyV, meta: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.keyA, control: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.keyA, meta: true): const DoNothingAndStopPropagationTextIntent(), }; static const Map<ShortcutActivator, Intent> _commonDisablingTextShortcuts = <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.arrowDown, alt: true): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.arrowRight, alt: true): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.arrowDown, meta: true): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.arrowRight, meta: true): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.arrowUp, meta: true): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.arrowDown): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.arrowLeft): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.arrowRight): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.arrowUp): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.arrowLeft, control: true): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.arrowRight, control: true): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, control: true): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, control: true): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.space): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.enter): DoNothingAndStopPropagationTextIntent(), }; static final Map<ShortcutActivator, Intent> _macDisablingTextShortcuts = <ShortcutActivator, Intent>{ ..._commonDisablingTextShortcuts, ..._iOSDisablingTextShortcuts, const SingleActivator(LogicalKeyboardKey.escape): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.tab): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.tab, shift: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, alt: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, alt: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, meta: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, meta: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.pageUp): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.pageDown): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.end): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.home): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.pageUp, shift: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.pageDown, shift: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.end, shift: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.home, shift: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.end, control: true): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.home, control: true): const DoNothingAndStopPropagationTextIntent(), }; // Hand backspace/delete events that do not depend on text layout (delete // character and delete to the next word) back to the IME to allow it to // update composing text properly. static const Map<ShortcutActivator, Intent> _iOSDisablingTextShortcuts = <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.backspace): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.backspace, shift: true): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.delete): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.delete, shift: true): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.backspace, alt: true, shift: true): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.backspace, alt: true): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.delete, alt: true, shift: true): DoNothingAndStopPropagationTextIntent(), SingleActivator(LogicalKeyboardKey.delete, alt: true): DoNothingAndStopPropagationTextIntent(), }; static Map<ShortcutActivator, Intent> get _shortcuts { return switch (defaultTargetPlatform) { TargetPlatform.android => _androidShortcuts, TargetPlatform.fuchsia => _fuchsiaShortcuts, TargetPlatform.iOS => _iOSShortcuts, TargetPlatform.linux => _linuxShortcuts, TargetPlatform.macOS => _macShortcuts, TargetPlatform.windows => _windowsShortcuts, }; } Map<ShortcutActivator, Intent>? _getDisablingShortcut() { if (kIsWeb) { return _webDisablingTextShortcuts; } switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: return null; case TargetPlatform.iOS: return _iOSDisablingTextShortcuts; case TargetPlatform.macOS: return _macDisablingTextShortcuts; } } @override Widget build(BuildContext context) { Widget result = child; final Map<ShortcutActivator, Intent>? disablingShortcut = _getDisablingShortcut(); if (disablingShortcut != null) { // These shortcuts make sure of the following: // // 1. Shortcuts fired when an EditableText is focused are ignored and // forwarded to the platform by the EditableText's Actions, because it // maps DoNothingAndStopPropagationTextIntent to DoNothingAction. // 2. Shortcuts fired when no EditableText is focused will still trigger // _shortcuts assuming DoNothingAndStopPropagationTextIntent is // unhandled elsewhere. result = Shortcuts( debugLabel: '<Web Disabling Text Editing Shortcuts>', shortcuts: disablingShortcut, child: result ); } return Shortcuts( debugLabel: '<Default Text Editing Shortcuts>', shortcuts: _shortcuts, child: result ); } } /// Maps the selector from NSStandardKeyBindingResponding to the Intent if the /// selector is recognized. Intent? intentForMacOSSelector(String selectorName) { const Map<String, Intent> selectorToIntent = <String, Intent>{ 'deleteBackward:': DeleteCharacterIntent(forward: false), 'deleteWordBackward:': DeleteToNextWordBoundaryIntent(forward: false), 'deleteToBeginningOfLine:': DeleteToLineBreakIntent(forward: false), 'deleteForward:': DeleteCharacterIntent(forward: true), 'deleteWordForward:': DeleteToNextWordBoundaryIntent(forward: true), 'deleteToEndOfLine:': DeleteToLineBreakIntent(forward: true), 'moveLeft:': ExtendSelectionByCharacterIntent(forward: false, collapseSelection: true), 'moveRight:': ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), 'moveForward:': ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), 'moveBackward:': ExtendSelectionByCharacterIntent(forward: false, collapseSelection: true), 'moveUp:': ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true), 'moveDown:': ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true), 'moveLeftAndModifySelection:': ExtendSelectionByCharacterIntent(forward: false, collapseSelection: false), 'moveRightAndModifySelection:': ExtendSelectionByCharacterIntent(forward: true, collapseSelection: false), 'moveUpAndModifySelection:': ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: false), 'moveDownAndModifySelection:': ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: false), 'moveWordLeft:': ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: true), 'moveWordRight:': ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: true), 'moveToBeginningOfParagraph:': ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), 'moveToEndOfParagraph:': ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), 'moveWordLeftAndModifySelection:': ExtendSelectionToNextWordBoundaryOrCaretLocationIntent(forward: false), 'moveWordRightAndModifySelection:': ExtendSelectionToNextWordBoundaryOrCaretLocationIntent(forward: true), 'moveParagraphBackwardAndModifySelection:': ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent(forward: false), 'moveParagraphForwardAndModifySelection:': ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent(forward: true), 'moveToLeftEndOfLine:': ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), 'moveToRightEndOfLine:': ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), 'moveToBeginningOfDocument:': ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: true), 'moveToEndOfDocument:': ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: true), 'moveToLeftEndOfLineAndModifySelection:': ExpandSelectionToLineBreakIntent(forward: false), 'moveToRightEndOfLineAndModifySelection:': ExpandSelectionToLineBreakIntent(forward: true), 'moveToBeginningOfDocumentAndModifySelection:': ExpandSelectionToDocumentBoundaryIntent(forward: false), 'moveToEndOfDocumentAndModifySelection:': ExpandSelectionToDocumentBoundaryIntent(forward: true), 'transpose:': TransposeCharactersIntent(), 'scrollToBeginningOfDocument:': ScrollToDocumentBoundaryIntent(forward: false), 'scrollToEndOfDocument:': ScrollToDocumentBoundaryIntent(forward: true), 'scrollPageUp:': ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page), 'scrollPageDown:': ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page), 'pageUpAndModifySelection:': ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: false), 'pageDownAndModifySelection:': ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: false), // Escape key when there's no IME selection popup. 'cancelOperation:': DismissIntent(), // Tab when there's no IME selection. 'insertTab:': NextFocusIntent(), 'insertBacktab:': PreviousFocusIntent(), }; return selectorToIntent[selectorName]; }
flutter/packages/flutter/lib/src/widgets/default_text_editing_shortcuts.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/default_text_editing_shortcuts.dart", "repo_id": "flutter", "token_count": 12415 }
649
// 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 'basic.dart'; import 'framework.dart'; class _GridPaperPainter extends CustomPainter { const _GridPaperPainter({ required this.color, required this.interval, required this.divisions, required this.subdivisions, }); final Color color; final double interval; final int divisions; final int subdivisions; @override void paint(Canvas canvas, Size size) { final Paint linePaint = Paint() ..color = color; final double allDivisions = (divisions * subdivisions).toDouble(); for (double x = 0.0; x <= size.width; x += interval / allDivisions) { linePaint.strokeWidth = (x % interval == 0.0) ? 1.0 : (x % (interval / subdivisions) == 0.0) ? 0.5 : 0.25; canvas.drawLine(Offset(x, 0.0), Offset(x, size.height), linePaint); } for (double y = 0.0; y <= size.height; y += interval / allDivisions) { linePaint.strokeWidth = (y % interval == 0.0) ? 1.0 : (y % (interval / subdivisions) == 0.0) ? 0.5 : 0.25; canvas.drawLine(Offset(0.0, y), Offset(size.width, y), linePaint); } } @override bool shouldRepaint(_GridPaperPainter oldPainter) { return oldPainter.color != color || oldPainter.interval != interval || oldPainter.divisions != divisions || oldPainter.subdivisions != subdivisions; } @override bool hitTest(Offset position) => false; } /// A widget that draws a rectilinear grid of lines one pixel wide. /// /// Useful with a [Stack] for visualizing your layout along a grid. /// /// The grid's origin (where the first primary horizontal line and the first /// primary vertical line intersect) is at the top left of the widget. /// /// The grid is drawn over the [child] widget. class GridPaper extends StatelessWidget { /// Creates a widget that draws a rectilinear grid of 1-pixel-wide lines. const GridPaper({ super.key, this.color = const Color(0x7FC3E8F3), this.interval = 100.0, this.divisions = 2, this.subdivisions = 5, this.child, }) : assert(divisions > 0, 'The "divisions" property must be greater than zero. If there were no divisions, the grid paper would not paint anything.'), assert(subdivisions > 0, 'The "subdivisions" property must be greater than zero. If there were no subdivisions, the grid paper would not paint anything.'); /// The color to draw the lines in the grid. /// /// Defaults to a light blue commonly seen on traditional grid paper. final Color color; /// The distance between the primary lines in the grid, in logical pixels. /// /// Each primary line is one logical pixel wide. final double interval; /// The number of major divisions within each primary grid cell. /// /// This is the number of major divisions per [interval], including the /// primary grid's line. /// /// The lines after the first are half a logical pixel wide. /// /// If this is set to 2 (the default), then for each [interval] there will be /// a 1-pixel line on the left, a half-pixel line in the middle, and a 1-pixel /// line on the right (the latter being the 1-pixel line on the left of the /// next [interval]). final int divisions; /// The number of minor divisions within each major division, including the /// major division itself. /// /// If [subdivisions] is 5 (the default), it means that there will be four /// lines between each major ([divisions]) line. /// /// The subdivision lines after the first are a quarter of a logical pixel wide. final int subdivisions; /// The widget below this widget in the tree. /// /// {@macro flutter.widgets.ProxyWidget.child} final Widget? child; @override Widget build(BuildContext context) { return CustomPaint( foregroundPainter: _GridPaperPainter( color: color, interval: interval, divisions: divisions, subdivisions: subdivisions, ), child: child, ); } }
flutter/packages/flutter/lib/src/widgets/grid_paper.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/grid_paper.dart", "repo_id": "flutter", "token_count": 1305 }
650
// 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:collection'; import 'dart:math' as math; import 'package:flutter/physics.dart'; import 'package:flutter/rendering.dart'; import 'basic.dart'; import 'framework.dart'; import 'notification_listener.dart'; import 'scroll_configuration.dart'; import 'scroll_context.dart'; import 'scroll_controller.dart'; import 'scroll_metrics.dart'; import 'scroll_notification.dart'; import 'scroll_physics.dart'; import 'scroll_position.dart'; import 'scroll_position_with_single_context.dart'; import 'scrollable.dart'; /// A delegate that supplies children for [ListWheelScrollView]. /// /// [ListWheelScrollView] lazily constructs its children during layout to avoid /// creating more children than are visible through the [Viewport]. This /// delegate is responsible for providing children to [ListWheelScrollView] /// during that stage. /// /// See also: /// /// * [ListWheelChildListDelegate], a delegate that supplies children using an /// explicit list. /// * [ListWheelChildLoopingListDelegate], a delegate that supplies infinite /// children by looping an explicit list. /// * [ListWheelChildBuilderDelegate], a delegate that supplies children using /// a builder callback. abstract class ListWheelChildDelegate { /// Return the child at the given index. If the child at the given /// index does not exist, return null. Widget? build(BuildContext context, int index); /// Returns an estimate of the number of children this delegate will build. int? get estimatedChildCount; /// Returns the true index for a child built at a given index. Defaults to /// the given index, however if the delegate is [ListWheelChildLoopingListDelegate], /// this value is the index of the true element that the delegate is looping to. /// /// /// Example: [ListWheelChildLoopingListDelegate] is built by looping a list of /// length 8. Then, trueIndexOf(10) = 2 and trueIndexOf(-5) = 3. int trueIndexOf(int index) => index; /// Called to check whether this and the old delegate are actually 'different', /// so that the caller can decide to rebuild or not. bool shouldRebuild(covariant ListWheelChildDelegate oldDelegate); } /// A delegate that supplies children for [ListWheelScrollView] using an /// explicit list. /// /// [ListWheelScrollView] lazily constructs its children to avoid creating more /// children than are visible through the [Viewport]. This delegate provides /// children using an explicit list, which is convenient but reduces the benefit /// of building children lazily. /// /// In general building all the widgets in advance is not efficient. It is /// better to create a delegate that builds them on demand using /// [ListWheelChildBuilderDelegate] or by subclassing [ListWheelChildDelegate] /// directly. /// /// This class is provided for the cases where either the list of children is /// known well in advance (ideally the children are themselves compile-time /// constants, for example), and therefore will not be built each time the /// delegate itself is created, or the list is small, such that it's likely /// always visible (and thus there is nothing to be gained by building it on /// demand). For example, the body of a dialog box might fit both of these /// conditions. class ListWheelChildListDelegate extends ListWheelChildDelegate { /// Constructs the delegate from a concrete list of children. ListWheelChildListDelegate({required this.children}); /// The list containing all children that can be supplied. final List<Widget> children; @override int get estimatedChildCount => children.length; @override Widget? build(BuildContext context, int index) { if (index < 0 || index >= children.length) { return null; } return IndexedSemantics(index: index, child: children[index]); } @override bool shouldRebuild(covariant ListWheelChildListDelegate oldDelegate) { return children != oldDelegate.children; } } /// A delegate that supplies infinite children for [ListWheelScrollView] by /// looping an explicit list. /// /// [ListWheelScrollView] lazily constructs its children to avoid creating more /// children than are visible through the [Viewport]. This delegate provides /// children using an explicit list, which is convenient but reduces the benefit /// of building children lazily. /// /// In general building all the widgets in advance is not efficient. It is /// better to create a delegate that builds them on demand using /// [ListWheelChildBuilderDelegate] or by subclassing [ListWheelChildDelegate] /// directly. /// /// This class is provided for the cases where either the list of children is /// known well in advance (ideally the children are themselves compile-time /// constants, for example), and therefore will not be built each time the /// delegate itself is created, or the list is small, such that it's likely /// always visible (and thus there is nothing to be gained by building it on /// demand). For example, the body of a dialog box might fit both of these /// conditions. class ListWheelChildLoopingListDelegate extends ListWheelChildDelegate { /// Constructs the delegate from a concrete list of children. ListWheelChildLoopingListDelegate({required this.children}); /// The list containing all children that can be supplied. final List<Widget> children; @override int? get estimatedChildCount => null; @override int trueIndexOf(int index) => index % children.length; @override Widget? build(BuildContext context, int index) { if (children.isEmpty) { return null; } return IndexedSemantics(index: index, child: children[index % children.length]); } @override bool shouldRebuild(covariant ListWheelChildLoopingListDelegate oldDelegate) { return children != oldDelegate.children; } } /// A delegate that supplies children for [ListWheelScrollView] using a builder /// callback. /// /// [ListWheelScrollView] lazily constructs its children to avoid creating more /// children than are visible through the [Viewport]. This delegate provides /// children using an [IndexedWidgetBuilder] callback, so that the children do /// not have to be built until they are displayed. class ListWheelChildBuilderDelegate extends ListWheelChildDelegate { /// Constructs the delegate from a builder callback. ListWheelChildBuilderDelegate({ required this.builder, this.childCount, }); /// Called lazily to build children. final NullableIndexedWidgetBuilder builder; /// {@template flutter.widgets.ListWheelChildBuilderDelegate.childCount} /// If non-null, [childCount] is the maximum number of children that can be /// provided, and children are available from 0 to [childCount] - 1. /// /// If null, then the lower and upper limit are not known. However the [builder] /// must provide children for a contiguous segment. If the builder returns null /// at some index, the segment terminates there. /// {@endtemplate} final int? childCount; @override int? get estimatedChildCount => childCount; @override Widget? build(BuildContext context, int index) { if (childCount == null) { final Widget? child = builder(context, index); return child == null ? null : IndexedSemantics(index: index, child: child); } if (index < 0 || index >= childCount!) { return null; } return IndexedSemantics(index: index, child: builder(context, index)); } @override bool shouldRebuild(covariant ListWheelChildBuilderDelegate oldDelegate) { return builder != oldDelegate.builder || childCount != oldDelegate.childCount; } } /// A controller for scroll views whose items have the same size. /// /// Similar to a standard [ScrollController] but with the added convenience /// mechanisms to read and go to item indices rather than a raw pixel scroll /// offset. /// /// See also: /// /// * [ListWheelScrollView], a scrollable view widget with fixed size items /// that this widget controls. /// * [FixedExtentMetrics], the `metrics` property exposed by /// [ScrollNotification] from [ListWheelScrollView] which can be used /// to listen to the current item index on a push basis rather than polling /// the [FixedExtentScrollController]. class FixedExtentScrollController extends ScrollController { /// Creates a scroll controller for scrollables whose items have the same size. /// /// [initialItem] defaults to zero. FixedExtentScrollController({ this.initialItem = 0, super.onAttach, super.onDetach, }); /// The page to show when first creating the scroll view. /// /// Defaults to zero. final int initialItem; /// The currently selected item index that's closest to the center of the viewport. /// /// There are circumstances that this [FixedExtentScrollController] can't know /// the current item. Reading [selectedItem] will throw an [AssertionError] in /// the following cases: /// /// 1. No scroll view is currently using this [FixedExtentScrollController]. /// 2. More than one scroll views using the same [FixedExtentScrollController]. /// /// The [hasClients] property can be used to check if a scroll view is /// attached prior to accessing [selectedItem]. int get selectedItem { assert( positions.isNotEmpty, 'FixedExtentScrollController.selectedItem cannot be accessed before a ' 'scroll view is built with it.', ); assert( positions.length == 1, 'The selectedItem property cannot be read when multiple scroll views are ' 'attached to the same FixedExtentScrollController.', ); final _FixedExtentScrollPosition position = this.position as _FixedExtentScrollPosition; return position.itemIndex; } /// Animates the controlled scroll view to the given item index. /// /// The animation lasts for the given duration and follows the given curve. /// The returned [Future] resolves when the animation completes. Future<void> animateToItem( int itemIndex, { required Duration duration, required Curve curve, }) async { if (!hasClients) { return; } await Future.wait<void>(<Future<void>>[ for (final _FixedExtentScrollPosition position in positions.cast<_FixedExtentScrollPosition>()) position.animateTo( itemIndex * position.itemExtent, duration: duration, curve: curve, ), ]); } /// Changes which item index is centered in the controlled scroll view. /// /// Jumps the item index position from its current value to the given value, /// without animation, and without checking if the new value is in range. void jumpToItem(int itemIndex) { for (final _FixedExtentScrollPosition position in positions.cast<_FixedExtentScrollPosition>()) { position.jumpTo(itemIndex * position.itemExtent); } } @override ScrollPosition createScrollPosition(ScrollPhysics physics, ScrollContext context, ScrollPosition? oldPosition) { return _FixedExtentScrollPosition( physics: physics, context: context, initialItem: initialItem, oldPosition: oldPosition, ); } } /// Metrics for a [ScrollPosition] to a scroll view with fixed item sizes. /// /// The metrics are available on [ScrollNotification]s generated from a scroll /// views such as [ListWheelScrollView]s with a [FixedExtentScrollController] /// and exposes the current [itemIndex] and the scroll view's extents. /// /// `FixedExtent` refers to the fact that the scrollable items have the same /// size. This is distinct from `Fixed` in the parent class name's /// [FixedScrollMetrics] which refers to its immutability. class FixedExtentMetrics extends FixedScrollMetrics { /// Creates an immutable snapshot of values associated with a /// [ListWheelScrollView]. FixedExtentMetrics({ required super.minScrollExtent, required super.maxScrollExtent, required super.pixels, required super.viewportDimension, required super.axisDirection, required this.itemIndex, required super.devicePixelRatio, }); @override FixedExtentMetrics copyWith({ double? minScrollExtent, double? maxScrollExtent, double? pixels, double? viewportDimension, AxisDirection? axisDirection, int? itemIndex, double? devicePixelRatio, }) { return FixedExtentMetrics( minScrollExtent: minScrollExtent ?? (hasContentDimensions ? this.minScrollExtent : null), maxScrollExtent: maxScrollExtent ?? (hasContentDimensions ? this.maxScrollExtent : null), pixels: pixels ?? (hasPixels ? this.pixels : null), viewportDimension: viewportDimension ?? (hasViewportDimension ? this.viewportDimension : null), axisDirection: axisDirection ?? this.axisDirection, itemIndex: itemIndex ?? this.itemIndex, devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio, ); } /// The scroll view's currently selected item index. final int itemIndex; } int _getItemFromOffset({ required double offset, required double itemExtent, required double minScrollExtent, required double maxScrollExtent, }) { return (_clipOffsetToScrollableRange(offset, minScrollExtent, maxScrollExtent) / itemExtent).round(); } double _clipOffsetToScrollableRange( double offset, double minScrollExtent, double maxScrollExtent, ) { return math.min(math.max(offset, minScrollExtent), maxScrollExtent); } /// A [ScrollPositionWithSingleContext] that can only be created based on /// [_FixedExtentScrollable] and can access its `itemExtent` to derive [itemIndex]. class _FixedExtentScrollPosition extends ScrollPositionWithSingleContext implements FixedExtentMetrics { _FixedExtentScrollPosition({ required super.physics, required super.context, required int initialItem, super.oldPosition, }) : assert( context is _FixedExtentScrollableState, 'FixedExtentScrollController can only be used with ListWheelScrollViews', ), super( initialPixels: _getItemExtentFromScrollContext(context) * initialItem, ); static double _getItemExtentFromScrollContext(ScrollContext context) { final _FixedExtentScrollableState scrollable = context as _FixedExtentScrollableState; return scrollable.itemExtent; } double get itemExtent => _getItemExtentFromScrollContext(context); @override int get itemIndex { return _getItemFromOffset( offset: pixels, itemExtent: itemExtent, minScrollExtent: minScrollExtent, maxScrollExtent: maxScrollExtent, ); } @override FixedExtentMetrics copyWith({ double? minScrollExtent, double? maxScrollExtent, double? pixels, double? viewportDimension, AxisDirection? axisDirection, int? itemIndex, double? devicePixelRatio, }) { return FixedExtentMetrics( minScrollExtent: minScrollExtent ?? (hasContentDimensions ? this.minScrollExtent : null), maxScrollExtent: maxScrollExtent ?? (hasContentDimensions ? this.maxScrollExtent : null), pixels: pixels ?? (hasPixels ? this.pixels : null), viewportDimension: viewportDimension ?? (hasViewportDimension ? this.viewportDimension : null), axisDirection: axisDirection ?? this.axisDirection, itemIndex: itemIndex ?? this.itemIndex, devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio, ); } } /// A [Scrollable] which must be given its viewport children's item extent /// size so it can pass it on ultimately to the [FixedExtentScrollController]. class _FixedExtentScrollable extends Scrollable { const _FixedExtentScrollable({ super.controller, super.physics, required this.itemExtent, required super.viewportBuilder, super.restorationId, super.scrollBehavior, }); final double itemExtent; @override _FixedExtentScrollableState createState() => _FixedExtentScrollableState(); } /// This [ScrollContext] is used by [_FixedExtentScrollPosition] to read the /// prescribed [itemExtent]. class _FixedExtentScrollableState extends ScrollableState { double get itemExtent { // Downcast because only _FixedExtentScrollable can make _FixedExtentScrollableState. final _FixedExtentScrollable actualWidget = widget as _FixedExtentScrollable; return actualWidget.itemExtent; } } /// A snapping physics that always lands directly on items instead of anywhere /// within the scroll extent. /// /// Behaves similarly to a slot machine wheel except the ballistics simulation /// never overshoots and rolls back within a single item if it's to settle on /// that item. /// /// Must be used with a scrollable that uses a [FixedExtentScrollController]. /// /// Defers back to the parent beyond the scroll extents. class FixedExtentScrollPhysics extends ScrollPhysics { /// Creates a scroll physics that always lands on items. const FixedExtentScrollPhysics({ super.parent }); @override FixedExtentScrollPhysics applyTo(ScrollPhysics? ancestor) { return FixedExtentScrollPhysics(parent: buildParent(ancestor)); } @override Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) { assert( position is _FixedExtentScrollPosition, 'FixedExtentScrollPhysics can only be used with Scrollables that uses ' 'the FixedExtentScrollController', ); final _FixedExtentScrollPosition metrics = position as _FixedExtentScrollPosition; // Scenario 1: // If we're out of range and not headed back in range, defer to the parent // ballistics, which should put us back in range at the scrollable's boundary. if ((velocity <= 0.0 && metrics.pixels <= metrics.minScrollExtent) || (velocity >= 0.0 && metrics.pixels >= metrics.maxScrollExtent)) { return super.createBallisticSimulation(metrics, velocity); } // Create a test simulation to see where it would have ballistically fallen // naturally without settling onto items. final Simulation? testFrictionSimulation = super.createBallisticSimulation(metrics, velocity); // Scenario 2: // If it was going to end up past the scroll extent, defer back to the // parent physics' ballistics again which should put us on the scrollable's // boundary. if (testFrictionSimulation != null && (testFrictionSimulation.x(double.infinity) == metrics.minScrollExtent || testFrictionSimulation.x(double.infinity) == metrics.maxScrollExtent)) { return super.createBallisticSimulation(metrics, velocity); } // From the natural final position, find the nearest item it should have // settled to. final int settlingItemIndex = _getItemFromOffset( offset: testFrictionSimulation?.x(double.infinity) ?? metrics.pixels, itemExtent: metrics.itemExtent, minScrollExtent: metrics.minScrollExtent, maxScrollExtent: metrics.maxScrollExtent, ); final double settlingPixels = settlingItemIndex * metrics.itemExtent; // Scenario 3: // If there's no velocity and we're already at where we intend to land, // do nothing. if (velocity.abs() < toleranceFor(position).velocity && (settlingPixels - metrics.pixels).abs() < toleranceFor(position).distance) { return null; } // Scenario 4: // If we're going to end back at the same item because initial velocity // is too low to break past it, use a spring simulation to get back. if (settlingItemIndex == metrics.itemIndex) { return SpringSimulation( spring, metrics.pixels, settlingPixels, velocity, tolerance: toleranceFor(position), ); } // Scenario 5: // Create a new friction simulation except the drag will be tweaked to land // exactly on the item closest to the natural stopping point. return FrictionSimulation.through( metrics.pixels, settlingPixels, velocity, toleranceFor(position).velocity * velocity.sign, ); } } /// A box in which children on a wheel can be scrolled. /// /// This widget is similar to a [ListView] but with the restriction that all /// children must be the same size along the scrolling axis. /// /// {@youtube 560 315 https://www.youtube.com/watch?v=dUhmWAz4C7Y} /// /// When the list is at the zero scroll offset, the first child is aligned with /// the middle of the viewport. When the list is at the final scroll offset, /// the last child is aligned with the middle of the viewport. /// /// The children are rendered as if rotating on a wheel instead of scrolling on /// a plane. class ListWheelScrollView extends StatefulWidget { /// Constructs a list in which children are scrolled a wheel. Its children /// are passed to a delegate and lazily built during layout. ListWheelScrollView({ super.key, this.controller, this.physics, this.diameterRatio = RenderListWheelViewport.defaultDiameterRatio, this.perspective = RenderListWheelViewport.defaultPerspective, this.offAxisFraction = 0.0, this.useMagnifier = false, this.magnification = 1.0, this.overAndUnderCenterOpacity = 1.0, required this.itemExtent, this.squeeze = 1.0, this.onSelectedItemChanged, this.renderChildrenOutsideViewport = false, this.clipBehavior = Clip.hardEdge, this.restorationId, this.scrollBehavior, required List<Widget> children, }) : assert(diameterRatio > 0.0, RenderListWheelViewport.diameterRatioZeroMessage), assert(perspective > 0), assert(perspective <= 0.01, RenderListWheelViewport.perspectiveTooHighMessage), assert(magnification > 0), assert(overAndUnderCenterOpacity >= 0 && overAndUnderCenterOpacity <= 1), assert(itemExtent > 0), assert(squeeze > 0), assert( !renderChildrenOutsideViewport || clipBehavior == Clip.none, RenderListWheelViewport.clipBehaviorAndRenderChildrenOutsideViewportConflict, ), childDelegate = ListWheelChildListDelegate(children: children); /// Constructs a list in which children are scrolled a wheel. Its children /// are managed by a delegate and are lazily built during layout. const ListWheelScrollView.useDelegate({ super.key, this.controller, this.physics, this.diameterRatio = RenderListWheelViewport.defaultDiameterRatio, this.perspective = RenderListWheelViewport.defaultPerspective, this.offAxisFraction = 0.0, this.useMagnifier = false, this.magnification = 1.0, this.overAndUnderCenterOpacity = 1.0, required this.itemExtent, this.squeeze = 1.0, this.onSelectedItemChanged, this.renderChildrenOutsideViewport = false, this.clipBehavior = Clip.hardEdge, this.restorationId, this.scrollBehavior, required this.childDelegate, }) : assert(diameterRatio > 0.0, RenderListWheelViewport.diameterRatioZeroMessage), assert(perspective > 0), assert(perspective <= 0.01, RenderListWheelViewport.perspectiveTooHighMessage), assert(magnification > 0), assert(overAndUnderCenterOpacity >= 0 && overAndUnderCenterOpacity <= 1), assert(itemExtent > 0), assert(squeeze > 0), assert( !renderChildrenOutsideViewport || clipBehavior == Clip.none, RenderListWheelViewport.clipBehaviorAndRenderChildrenOutsideViewportConflict, ); /// Typically a [FixedExtentScrollController] used to control the current item. /// /// A [FixedExtentScrollController] can be used to read the currently /// selected/centered child item and can be used to change the current item. /// /// If none is provided, a new [FixedExtentScrollController] is implicitly /// created. /// /// If a [ScrollController] is used instead of [FixedExtentScrollController], /// [ScrollNotification.metrics] will no longer provide [FixedExtentMetrics] /// to indicate the current item index and [onSelectedItemChanged] will not /// work. /// /// To read the current selected item only when the value changes, use /// [onSelectedItemChanged]. final ScrollController? controller; /// How the scroll view should respond to user input. /// /// For example, determines how the scroll view continues to animate after the /// user stops dragging the scroll view. /// /// If an explicit [ScrollBehavior] is provided to [scrollBehavior], the /// [ScrollPhysics] provided by that behavior will take precedence after /// [physics]. /// /// Defaults to matching platform conventions. final ScrollPhysics? physics; /// {@macro flutter.rendering.RenderListWheelViewport.diameterRatio} final double diameterRatio; /// {@macro flutter.rendering.RenderListWheelViewport.perspective} final double perspective; /// {@macro flutter.rendering.RenderListWheelViewport.offAxisFraction} final double offAxisFraction; /// {@macro flutter.rendering.RenderListWheelViewport.useMagnifier} final bool useMagnifier; /// {@macro flutter.rendering.RenderListWheelViewport.magnification} final double magnification; /// {@macro flutter.rendering.RenderListWheelViewport.overAndUnderCenterOpacity} final double overAndUnderCenterOpacity; /// Size of each child in the main axis. /// /// Must be positive. final double itemExtent; /// {@macro flutter.rendering.RenderListWheelViewport.squeeze} /// /// Defaults to 1. final double squeeze; /// On optional listener that's called when the centered item changes. final ValueChanged<int>? onSelectedItemChanged; /// {@macro flutter.rendering.RenderListWheelViewport.renderChildrenOutsideViewport} final bool renderChildrenOutsideViewport; /// A delegate that helps lazily instantiating child. final ListWheelChildDelegate childDelegate; /// {@macro flutter.material.Material.clipBehavior} /// /// Defaults to [Clip.hardEdge]. final Clip clipBehavior; /// {@macro flutter.widgets.scrollable.restorationId} final String? restorationId; /// {@macro flutter.widgets.shadow.scrollBehavior} /// /// [ScrollBehavior]s also provide [ScrollPhysics]. If an explicit /// [ScrollPhysics] is provided in [physics], it will take precedence, /// followed by [scrollBehavior], and then the inherited ancestor /// [ScrollBehavior]. /// /// The [ScrollBehavior] of the inherited [ScrollConfiguration] will be /// modified by default to not apply a [Scrollbar]. final ScrollBehavior? scrollBehavior; @override State<ListWheelScrollView> createState() => _ListWheelScrollViewState(); } class _ListWheelScrollViewState extends State<ListWheelScrollView> { int _lastReportedItemIndex = 0; ScrollController? _backupController; ScrollController get _effectiveController => widget.controller ?? (_backupController ??= FixedExtentScrollController()); @override void initState() { super.initState(); if (widget.controller is FixedExtentScrollController) { final FixedExtentScrollController controller = widget.controller! as FixedExtentScrollController; _lastReportedItemIndex = controller.initialItem; } } @override void dispose() { _backupController?.dispose(); super.dispose(); } bool _handleScrollNotification(ScrollNotification notification) { if (notification.depth == 0 && widget.onSelectedItemChanged != null && notification is ScrollUpdateNotification && notification.metrics is FixedExtentMetrics) { final FixedExtentMetrics metrics = notification.metrics as FixedExtentMetrics; final int currentItemIndex = metrics.itemIndex; if (currentItemIndex != _lastReportedItemIndex) { _lastReportedItemIndex = currentItemIndex; final int trueIndex = widget.childDelegate.trueIndexOf(currentItemIndex); widget.onSelectedItemChanged!(trueIndex); } } return false; } @override Widget build(BuildContext context) { return NotificationListener<ScrollNotification>( onNotification: _handleScrollNotification, child: _FixedExtentScrollable( controller: _effectiveController, physics: widget.physics, itemExtent: widget.itemExtent, restorationId: widget.restorationId, scrollBehavior: widget.scrollBehavior ?? ScrollConfiguration.of(context).copyWith(scrollbars: false), viewportBuilder: (BuildContext context, ViewportOffset offset) { return ListWheelViewport( diameterRatio: widget.diameterRatio, perspective: widget.perspective, offAxisFraction: widget.offAxisFraction, useMagnifier: widget.useMagnifier, magnification: widget.magnification, overAndUnderCenterOpacity: widget.overAndUnderCenterOpacity, itemExtent: widget.itemExtent, squeeze: widget.squeeze, renderChildrenOutsideViewport: widget.renderChildrenOutsideViewport, offset: offset, childDelegate: widget.childDelegate, clipBehavior: widget.clipBehavior, ); }, ), ); } } /// Element that supports building children lazily for [ListWheelViewport]. class ListWheelElement extends RenderObjectElement implements ListWheelChildManager { /// Creates an element that lazily builds children for the given widget. ListWheelElement(ListWheelViewport super.widget); @override RenderListWheelViewport get renderObject => super.renderObject as RenderListWheelViewport; // We inflate widgets at two different times: // 1. When we ourselves are told to rebuild (see performRebuild). // 2. When our render object needs a new child (see createChild). // In both cases, we cache the results of calling into our delegate to get the // widget, so that if we do case 2 later, we don't call the builder again. // Any time we do case 1, though, we reset the cache. /// A cache of widgets so that we don't have to rebuild every time. final Map<int, Widget?> _childWidgets = HashMap<int, Widget?>(); /// The map containing all active child elements. SplayTreeMap is used so that /// we have all elements ordered and iterable by their keys. final SplayTreeMap<int, Element> _childElements = SplayTreeMap<int, Element>(); @override void update(ListWheelViewport newWidget) { final ListWheelViewport oldWidget = widget as ListWheelViewport; super.update(newWidget); final ListWheelChildDelegate newDelegate = newWidget.childDelegate; final ListWheelChildDelegate oldDelegate = oldWidget.childDelegate; if (newDelegate != oldDelegate && (newDelegate.runtimeType != oldDelegate.runtimeType || newDelegate.shouldRebuild(oldDelegate))) { performRebuild(); renderObject.markNeedsLayout(); } } @override int? get childCount => (widget as ListWheelViewport).childDelegate.estimatedChildCount; @override void performRebuild() { _childWidgets.clear(); super.performRebuild(); if (_childElements.isEmpty) { return; } final int firstIndex = _childElements.firstKey()!; final int lastIndex = _childElements.lastKey()!; for (int index = firstIndex; index <= lastIndex; ++index) { final Element? newChild = updateChild(_childElements[index], retrieveWidget(index), index); if (newChild != null) { _childElements[index] = newChild; } else { _childElements.remove(index); } } } /// Asks the underlying delegate for a widget at the given index. /// /// Normally the builder is only called once for each index and the result /// will be cached. However when the element is rebuilt, the cache will be /// cleared. Widget? retrieveWidget(int index) { return _childWidgets.putIfAbsent(index, () => (widget as ListWheelViewport).childDelegate.build(this, index)); } @override bool childExistsAt(int index) => retrieveWidget(index) != null; @override void createChild(int index, { required RenderBox? after }) { owner!.buildScope(this, () { final bool insertFirst = after == null; assert(insertFirst || _childElements[index - 1] != null); final Element? newChild = updateChild(_childElements[index], retrieveWidget(index), index); if (newChild != null) { _childElements[index] = newChild; } else { _childElements.remove(index); } }); } @override void removeChild(RenderBox child) { final int index = renderObject.indexOf(child); owner!.buildScope(this, () { assert(_childElements.containsKey(index)); final Element? result = updateChild(_childElements[index], null, index); assert(result == null); _childElements.remove(index); assert(!_childElements.containsKey(index)); }); } @override Element? updateChild(Element? child, Widget? newWidget, Object? newSlot) { final ListWheelParentData? oldParentData = child?.renderObject?.parentData as ListWheelParentData?; final Element? newChild = super.updateChild(child, newWidget, newSlot); final ListWheelParentData? newParentData = newChild?.renderObject?.parentData as ListWheelParentData?; if (newParentData != null) { newParentData.index = newSlot! as int; if (oldParentData != null) { newParentData.offset = oldParentData.offset; } } return newChild; } @override void insertRenderObjectChild(RenderObject child, int slot) { final RenderListWheelViewport renderObject = this.renderObject; assert(renderObject.debugValidateChild(child)); renderObject.insert(child as RenderBox, after: _childElements[slot - 1]?.renderObject as RenderBox?); assert(renderObject == this.renderObject); } @override void moveRenderObjectChild(RenderObject child, int oldSlot, int newSlot) { const String moveChildRenderObjectErrorMessage = 'Currently we maintain the list in contiguous increasing order, so ' 'moving children around is not allowed.'; assert(false, moveChildRenderObjectErrorMessage); } @override void removeRenderObjectChild(RenderObject child, int slot) { assert(child.parent == renderObject); renderObject.remove(child as RenderBox); } @override void visitChildren(ElementVisitor visitor) { _childElements.forEach((int key, Element child) { visitor(child); }); } @override void forgetChild(Element child) { _childElements.remove(child.slot); super.forgetChild(child); } } /// A viewport showing a subset of children on a wheel. /// /// Typically used with [ListWheelScrollView], this viewport is similar to /// [Viewport] in that it shows a subset of children in a scrollable based /// on the scrolling offset and the children's dimensions. But uses /// [RenderListWheelViewport] to display the children on a wheel. /// /// See also: /// /// * [ListWheelScrollView], widget that combines this viewport with a scrollable. /// * [RenderListWheelViewport], the render object that renders the children /// on a wheel. class ListWheelViewport extends RenderObjectWidget { /// Creates a viewport where children are rendered onto a wheel. /// /// The [diameterRatio] argument defaults to 2. /// /// The [perspective] argument defaults to 0.003. /// /// The [itemExtent] argument in pixels must be provided and must be positive. /// /// The [clipBehavior] argument defaults to [Clip.hardEdge]. /// /// The [renderChildrenOutsideViewport] argument defaults to false and must /// not be null. /// /// The [offset] argument must be provided. const ListWheelViewport({ super.key, this.diameterRatio = RenderListWheelViewport.defaultDiameterRatio, this.perspective = RenderListWheelViewport.defaultPerspective, this.offAxisFraction = 0.0, this.useMagnifier = false, this.magnification = 1.0, this.overAndUnderCenterOpacity = 1.0, required this.itemExtent, this.squeeze = 1.0, this.renderChildrenOutsideViewport = false, required this.offset, required this.childDelegate, this.clipBehavior = Clip.hardEdge, }) : assert(diameterRatio > 0, RenderListWheelViewport.diameterRatioZeroMessage), assert(perspective > 0), assert(perspective <= 0.01, RenderListWheelViewport.perspectiveTooHighMessage), assert(overAndUnderCenterOpacity >= 0 && overAndUnderCenterOpacity <= 1), assert(itemExtent > 0), assert(squeeze > 0), assert( !renderChildrenOutsideViewport || clipBehavior == Clip.none, RenderListWheelViewport.clipBehaviorAndRenderChildrenOutsideViewportConflict, ); /// {@macro flutter.rendering.RenderListWheelViewport.diameterRatio} final double diameterRatio; /// {@macro flutter.rendering.RenderListWheelViewport.perspective} final double perspective; /// {@macro flutter.rendering.RenderListWheelViewport.offAxisFraction} final double offAxisFraction; /// {@macro flutter.rendering.RenderListWheelViewport.useMagnifier} final bool useMagnifier; /// {@macro flutter.rendering.RenderListWheelViewport.magnification} final double magnification; /// {@macro flutter.rendering.RenderListWheelViewport.overAndUnderCenterOpacity} final double overAndUnderCenterOpacity; /// {@macro flutter.rendering.RenderListWheelViewport.itemExtent} final double itemExtent; /// {@macro flutter.rendering.RenderListWheelViewport.squeeze} /// /// Defaults to 1. final double squeeze; /// {@macro flutter.rendering.RenderListWheelViewport.renderChildrenOutsideViewport} final bool renderChildrenOutsideViewport; /// [ViewportOffset] object describing the content that should be visible /// in the viewport. final ViewportOffset offset; /// A delegate that lazily instantiates children. final ListWheelChildDelegate childDelegate; /// {@macro flutter.material.Material.clipBehavior} /// /// Defaults to [Clip.hardEdge]. final Clip clipBehavior; @override ListWheelElement createElement() => ListWheelElement(this); @override RenderListWheelViewport createRenderObject(BuildContext context) { final ListWheelElement childManager = context as ListWheelElement; return RenderListWheelViewport( childManager: childManager, offset: offset, diameterRatio: diameterRatio, perspective: perspective, offAxisFraction: offAxisFraction, useMagnifier: useMagnifier, magnification: magnification, overAndUnderCenterOpacity: overAndUnderCenterOpacity, itemExtent: itemExtent, squeeze: squeeze, renderChildrenOutsideViewport: renderChildrenOutsideViewport, clipBehavior: clipBehavior, ); } @override void updateRenderObject(BuildContext context, RenderListWheelViewport renderObject) { renderObject ..offset = offset ..diameterRatio = diameterRatio ..perspective = perspective ..offAxisFraction = offAxisFraction ..useMagnifier = useMagnifier ..magnification = magnification ..overAndUnderCenterOpacity = overAndUnderCenterOpacity ..itemExtent = itemExtent ..squeeze = squeeze ..renderChildrenOutsideViewport = renderChildrenOutsideViewport ..clipBehavior = clipBehavior; } }
flutter/packages/flutter/lib/src/widgets/list_wheel_scroll_view.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/list_wheel_scroll_view.dart", "repo_id": "flutter", "token_count": 12124 }
651
// 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 'package:flutter/foundation.dart' show clampDouble, precisionErrorTolerance; import 'package:flutter/gestures.dart' show DragStartBehavior; import 'package:flutter/rendering.dart'; import 'basic.dart'; import 'debug.dart'; import 'framework.dart'; import 'notification_listener.dart'; import 'page_storage.dart'; import 'scroll_configuration.dart'; import 'scroll_context.dart'; import 'scroll_controller.dart'; import 'scroll_delegate.dart'; import 'scroll_metrics.dart'; import 'scroll_notification.dart'; import 'scroll_physics.dart'; import 'scroll_position.dart'; import 'scroll_position_with_single_context.dart'; import 'scroll_view.dart'; import 'scrollable.dart'; import 'sliver_fill.dart'; import 'viewport.dart'; /// A controller for [PageView]. /// /// A page controller lets you manipulate which page is visible in a [PageView]. /// In addition to being able to control the pixel offset of the content inside /// the [PageView], a [PageController] also lets you control the offset in terms /// of pages, which are increments of the viewport size. /// /// See also: /// /// * [PageView], which is the widget this object controls. /// /// {@tool snippet} /// /// This widget introduces a [MaterialApp], [Scaffold] and [PageView] with two pages /// using the default constructor. Both pages contain an [ElevatedButton] allowing you /// to animate the [PageView] using a [PageController]. /// /// ```dart /// class MyPageView extends StatefulWidget { /// const MyPageView({super.key}); /// /// @override /// State<MyPageView> createState() => _MyPageViewState(); /// } /// /// class _MyPageViewState extends State<MyPageView> { /// final PageController _pageController = PageController(); /// /// @override /// void dispose() { /// _pageController.dispose(); /// super.dispose(); /// } /// /// @override /// Widget build(BuildContext context) { /// return MaterialApp( /// home: Scaffold( /// body: PageView( /// controller: _pageController, /// children: <Widget>[ /// ColoredBox( /// color: Colors.red, /// child: Center( /// child: ElevatedButton( /// onPressed: () { /// if (_pageController.hasClients) { /// _pageController.animateToPage( /// 1, /// duration: const Duration(milliseconds: 400), /// curve: Curves.easeInOut, /// ); /// } /// }, /// child: const Text('Next'), /// ), /// ), /// ), /// ColoredBox( /// color: Colors.blue, /// child: Center( /// child: ElevatedButton( /// onPressed: () { /// if (_pageController.hasClients) { /// _pageController.animateToPage( /// 0, /// duration: const Duration(milliseconds: 400), /// curve: Curves.easeInOut, /// ); /// } /// }, /// child: const Text('Previous'), /// ), /// ), /// ), /// ], /// ), /// ), /// ); /// } /// } /// ``` /// {@end-tool} class PageController extends ScrollController { /// Creates a page controller. PageController({ this.initialPage = 0, this.keepPage = true, this.viewportFraction = 1.0, super.onAttach, super.onDetach, }) : assert(viewportFraction > 0.0); /// The page to show when first creating the [PageView]. final int initialPage; /// Save the current [page] with [PageStorage] and restore it if /// this controller's scrollable is recreated. /// /// If this property is set to false, the current [page] is never saved /// and [initialPage] is always used to initialize the scroll offset. /// If true (the default), the initial page is used the first time the /// controller's scrollable is created, since there's isn't a page to /// restore yet. Subsequently the saved page is restored and /// [initialPage] is ignored. /// /// See also: /// /// * [PageStorageKey], which should be used when more than one /// scrollable appears in the same route, to distinguish the [PageStorage] /// locations used to save scroll offsets. final bool keepPage; /// {@template flutter.widgets.pageview.viewportFraction} /// The fraction of the viewport that each page should occupy. /// /// Defaults to 1.0, which means each page fills the viewport in the scrolling /// direction. /// {@endtemplate} final double viewportFraction; /// The current page displayed in the controlled [PageView]. /// /// There are circumstances that this [PageController] can't know the current /// page. Reading [page] will throw an [AssertionError] in the following cases: /// /// 1. No [PageView] is currently using this [PageController]. Once a /// [PageView] starts using this [PageController], the new [page] /// position will be derived: /// /// * First, based on the attached [PageView]'s [BuildContext] and the /// position saved at that context's [PageStorage] if [keepPage] is true. /// * Second, from the [PageController]'s [initialPage]. /// /// 2. More than one [PageView] using the same [PageController]. /// /// The [hasClients] property can be used to check if a [PageView] is attached /// prior to accessing [page]. double? get page { assert( positions.isNotEmpty, 'PageController.page cannot be accessed before a PageView is built with it.', ); assert( positions.length == 1, 'The page property cannot be read when multiple PageViews are attached to ' 'the same PageController.', ); final _PagePosition position = this.position as _PagePosition; return position.page; } /// Animates the controlled [PageView] from the current page to the given page. /// /// The animation lasts for the given duration and follows the given curve. /// The returned [Future] resolves when the animation completes. Future<void> animateToPage( int page, { required Duration duration, required Curve curve, }) { final _PagePosition position = this.position as _PagePosition; if (position._cachedPage != null) { position._cachedPage = page.toDouble(); return Future<void>.value(); } return position.animateTo( position.getPixelsFromPage(page.toDouble()), duration: duration, curve: curve, ); } /// Changes which page is displayed in the controlled [PageView]. /// /// Jumps the page position from its current value to the given value, /// without animation, and without checking if the new value is in range. void jumpToPage(int page) { final _PagePosition position = this.position as _PagePosition; if (position._cachedPage != null) { position._cachedPage = page.toDouble(); return; } position.jumpTo(position.getPixelsFromPage(page.toDouble())); } /// Animates the controlled [PageView] to the next page. /// /// The animation lasts for the given duration and follows the given curve. /// The returned [Future] resolves when the animation completes. Future<void> nextPage({ required Duration duration, required Curve curve }) { return animateToPage(page!.round() + 1, duration: duration, curve: curve); } /// Animates the controlled [PageView] to the previous page. /// /// The animation lasts for the given duration and follows the given curve. /// The returned [Future] resolves when the animation completes. Future<void> previousPage({ required Duration duration, required Curve curve }) { return animateToPage(page!.round() - 1, duration: duration, curve: curve); } @override ScrollPosition createScrollPosition(ScrollPhysics physics, ScrollContext context, ScrollPosition? oldPosition) { return _PagePosition( physics: physics, context: context, initialPage: initialPage, keepPage: keepPage, viewportFraction: viewportFraction, oldPosition: oldPosition, ); } @override void attach(ScrollPosition position) { super.attach(position); final _PagePosition pagePosition = position as _PagePosition; pagePosition.viewportFraction = viewportFraction; } } /// Metrics for a [PageView]. /// /// The metrics are available on [ScrollNotification]s generated from /// [PageView]s. class PageMetrics extends FixedScrollMetrics { /// Creates an immutable snapshot of values associated with a [PageView]. PageMetrics({ required super.minScrollExtent, required super.maxScrollExtent, required super.pixels, required super.viewportDimension, required super.axisDirection, required this.viewportFraction, required super.devicePixelRatio, }); @override PageMetrics copyWith({ double? minScrollExtent, double? maxScrollExtent, double? pixels, double? viewportDimension, AxisDirection? axisDirection, double? viewportFraction, double? devicePixelRatio, }) { return PageMetrics( minScrollExtent: minScrollExtent ?? (hasContentDimensions ? this.minScrollExtent : null), maxScrollExtent: maxScrollExtent ?? (hasContentDimensions ? this.maxScrollExtent : null), pixels: pixels ?? (hasPixels ? this.pixels : null), viewportDimension: viewportDimension ?? (hasViewportDimension ? this.viewportDimension : null), axisDirection: axisDirection ?? this.axisDirection, viewportFraction: viewportFraction ?? this.viewportFraction, devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio, ); } /// The current page displayed in the [PageView]. double? get page { return math.max(0.0, clampDouble(pixels, minScrollExtent, maxScrollExtent)) / math.max(1.0, viewportDimension * viewportFraction); } /// The fraction of the viewport that each page occupies. /// /// Used to compute [page] from the current [pixels]. final double viewportFraction; } class _PagePosition extends ScrollPositionWithSingleContext implements PageMetrics { _PagePosition({ required super.physics, required super.context, this.initialPage = 0, bool keepPage = true, double viewportFraction = 1.0, super.oldPosition, }) : assert(viewportFraction > 0.0), _viewportFraction = viewportFraction, _pageToUseOnStartup = initialPage.toDouble(), super( initialPixels: null, keepScrollOffset: keepPage, ); final int initialPage; double _pageToUseOnStartup; // When the viewport has a zero-size, the `page` can not // be retrieved by `getPageFromPixels`, so we need to cache the page // for use when resizing the viewport to non-zero next time. double? _cachedPage; @override Future<void> ensureVisible( RenderObject object, { double alignment = 0.0, Duration duration = Duration.zero, Curve curve = Curves.ease, ScrollPositionAlignmentPolicy alignmentPolicy = ScrollPositionAlignmentPolicy.explicit, RenderObject? targetRenderObject, }) { // Since the _PagePosition is intended to cover the available space within // its viewport, stop trying to move the target render object to the center // - otherwise, could end up changing which page is visible and moving the // targetRenderObject out of the viewport. return super.ensureVisible( object, alignment: alignment, duration: duration, curve: curve, alignmentPolicy: alignmentPolicy, ); } @override double get viewportFraction => _viewportFraction; double _viewportFraction; set viewportFraction(double value) { if (_viewportFraction == value) { return; } final double? oldPage = page; _viewportFraction = value; if (oldPage != null) { forcePixels(getPixelsFromPage(oldPage)); } } // The amount of offset that will be added to [minScrollExtent] and subtracted // from [maxScrollExtent], such that every page will properly snap to the center // of the viewport when viewportFraction is greater than 1. // // The value is 0 if viewportFraction is less than or equal to 1, larger than 0 // otherwise. double get _initialPageOffset => math.max(0, viewportDimension * (viewportFraction - 1) / 2); double getPageFromPixels(double pixels, double viewportDimension) { assert(viewportDimension > 0.0); final double actual = math.max(0.0, pixels - _initialPageOffset) / (viewportDimension * viewportFraction); final double round = actual.roundToDouble(); if ((actual - round).abs() < precisionErrorTolerance) { return round; } return actual; } double getPixelsFromPage(double page) { return page * viewportDimension * viewportFraction + _initialPageOffset; } @override double? get page { assert( !hasPixels || hasContentDimensions, 'Page value is only available after content dimensions are established.', ); return !hasPixels || !hasContentDimensions ? null : _cachedPage ?? getPageFromPixels(clampDouble(pixels, minScrollExtent, maxScrollExtent), viewportDimension); } @override void saveScrollOffset() { PageStorage.maybeOf(context.storageContext)?.writeState(context.storageContext, _cachedPage ?? getPageFromPixels(pixels, viewportDimension)); } @override void restoreScrollOffset() { if (!hasPixels) { final double? value = PageStorage.maybeOf(context.storageContext)?.readState(context.storageContext) as double?; if (value != null) { _pageToUseOnStartup = value; } } } @override void saveOffset() { context.saveOffset(_cachedPage ?? getPageFromPixels(pixels, viewportDimension)); } @override void restoreOffset(double offset, {bool initialRestore = false}) { if (initialRestore) { _pageToUseOnStartup = offset; } else { jumpTo(getPixelsFromPage(offset)); } } @override bool applyViewportDimension(double viewportDimension) { final double? oldViewportDimensions = hasViewportDimension ? this.viewportDimension : null; if (viewportDimension == oldViewportDimensions) { return true; } final bool result = super.applyViewportDimension(viewportDimension); final double? oldPixels = hasPixels ? pixels : null; double page; if (oldPixels == null) { page = _pageToUseOnStartup; } else if (oldViewportDimensions == 0.0) { // If resize from zero, we should use the _cachedPage to recover the state. page = _cachedPage!; } else { page = getPageFromPixels(oldPixels, oldViewportDimensions!); } final double newPixels = getPixelsFromPage(page); // If the viewportDimension is zero, cache the page // in case the viewport is resized to be non-zero. _cachedPage = (viewportDimension == 0.0) ? page : null; if (newPixels != oldPixels) { correctPixels(newPixels); return false; } return result; } @override void absorb(ScrollPosition other) { super.absorb(other); assert(_cachedPage == null); if (other is! _PagePosition) { return; } if (other._cachedPage != null) { _cachedPage = other._cachedPage; } } @override bool applyContentDimensions(double minScrollExtent, double maxScrollExtent) { final double newMinScrollExtent = minScrollExtent + _initialPageOffset; return super.applyContentDimensions( newMinScrollExtent, math.max(newMinScrollExtent, maxScrollExtent - _initialPageOffset), ); } @override PageMetrics copyWith({ double? minScrollExtent, double? maxScrollExtent, double? pixels, double? viewportDimension, AxisDirection? axisDirection, double? viewportFraction, double? devicePixelRatio, }) { return PageMetrics( minScrollExtent: minScrollExtent ?? (hasContentDimensions ? this.minScrollExtent : null), maxScrollExtent: maxScrollExtent ?? (hasContentDimensions ? this.maxScrollExtent : null), pixels: pixels ?? (hasPixels ? this.pixels : null), viewportDimension: viewportDimension ?? (hasViewportDimension ? this.viewportDimension : null), axisDirection: axisDirection ?? this.axisDirection, viewportFraction: viewportFraction ?? this.viewportFraction, devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio, ); } } class _ForceImplicitScrollPhysics extends ScrollPhysics { const _ForceImplicitScrollPhysics({ required this.allowImplicitScrolling, super.parent, }); @override _ForceImplicitScrollPhysics applyTo(ScrollPhysics? ancestor) { return _ForceImplicitScrollPhysics( allowImplicitScrolling: allowImplicitScrolling, parent: buildParent(ancestor), ); } @override final bool allowImplicitScrolling; } /// Scroll physics used by a [PageView]. /// /// These physics cause the page view to snap to page boundaries. /// /// See also: /// /// * [ScrollPhysics], the base class which defines the API for scrolling /// physics. /// * [PageView.physics], which can override the physics used by a page view. class PageScrollPhysics extends ScrollPhysics { /// Creates physics for a [PageView]. const PageScrollPhysics({ super.parent }); @override PageScrollPhysics applyTo(ScrollPhysics? ancestor) { return PageScrollPhysics(parent: buildParent(ancestor)); } double _getPage(ScrollMetrics position) { if (position is _PagePosition) { return position.page!; } return position.pixels / position.viewportDimension; } double _getPixels(ScrollMetrics position, double page) { if (position is _PagePosition) { return position.getPixelsFromPage(page); } return page * position.viewportDimension; } double _getTargetPixels(ScrollMetrics position, Tolerance tolerance, double velocity) { double page = _getPage(position); if (velocity < -tolerance.velocity) { page -= 0.5; } else if (velocity > tolerance.velocity) { page += 0.5; } return _getPixels(position, page.roundToDouble()); } @override Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) { // If we're out of range and not headed back in range, defer to the parent // ballistics, which should put us back in range at a page boundary. if ((velocity <= 0.0 && position.pixels <= position.minScrollExtent) || (velocity >= 0.0 && position.pixels >= position.maxScrollExtent)) { return super.createBallisticSimulation(position, velocity); } final Tolerance tolerance = toleranceFor(position); final double target = _getTargetPixels(position, tolerance, velocity); if (target != position.pixels) { return ScrollSpringSimulation(spring, position.pixels, target, velocity, tolerance: tolerance); } return null; } @override bool get allowImplicitScrolling => false; } const PageScrollPhysics _kPagePhysics = PageScrollPhysics(); /// A scrollable list that works page by page. /// /// Each child of a page view is forced to be the same size as the viewport. /// /// You can use a [PageController] to control which page is visible in the view. /// In addition to being able to control the pixel offset of the content inside /// the [PageView], a [PageController] also lets you control the offset in terms /// of pages, which are increments of the viewport size. /// /// The [PageController] can also be used to control the /// [PageController.initialPage], which determines which page is shown when the /// [PageView] is first constructed, and the [PageController.viewportFraction], /// which determines the size of the pages as a fraction of the viewport size. /// /// {@youtube 560 315 https://www.youtube.com/watch?v=J1gE9xvph-A} /// /// {@tool dartpad} /// Here is an example of [PageView]. It creates a centered [Text] in each of the three pages /// which scroll horizontally. /// /// ** See code in examples/api/lib/widgets/page_view/page_view.0.dart ** /// {@end-tool} /// /// ## Persisting the scroll position during a session /// /// Scroll views attempt to persist their scroll position using [PageStorage]. /// For a [PageView], this can be disabled by setting [PageController.keepPage] /// to false on the [controller]. If it is enabled, using a [PageStorageKey] for /// the [key] of this widget is recommended to help disambiguate different /// scroll views from each other. /// /// See also: /// /// * [PageController], which controls which page is visible in the view. /// * [SingleChildScrollView], when you need to make a single child scrollable. /// * [ListView], for a scrollable list of boxes. /// * [GridView], for a scrollable grid of boxes. /// * [ScrollNotification] and [NotificationListener], which can be used to watch /// the scroll position without using a [ScrollController]. class PageView extends StatefulWidget { /// Creates a scrollable list that works page by page from an explicit [List] /// of widgets. /// /// This constructor is appropriate for page views with a small number of /// children because constructing the [List] requires doing work for every /// child that could possibly be displayed in the page view, instead of just /// those children that are actually visible. /// /// Like other widgets in the framework, this widget expects that /// the [children] list will not be mutated after it has been passed in here. /// See the documentation at [SliverChildListDelegate.children] for more details. /// /// {@template flutter.widgets.PageView.allowImplicitScrolling} /// If [allowImplicitScrolling] is true, the [PageView] will participate in /// accessibility scrolling more like a [ListView], where implicit scroll /// actions will move to the next page rather than into the contents of the /// [PageView]. /// {@endtemplate} PageView({ super.key, this.scrollDirection = Axis.horizontal, this.reverse = false, this.controller, this.physics, this.pageSnapping = true, this.onPageChanged, List<Widget> children = const <Widget>[], this.dragStartBehavior = DragStartBehavior.start, this.allowImplicitScrolling = false, this.restorationId, this.clipBehavior = Clip.hardEdge, this.scrollBehavior, this.padEnds = true, }) : childrenDelegate = SliverChildListDelegate(children); /// Creates a scrollable list that works page by page using widgets that are /// created on demand. /// /// This constructor is appropriate for page views with a large (or infinite) /// number of children because the builder is called only for those children /// that are actually visible. /// /// Providing a non-null [itemCount] lets the [PageView] compute the maximum /// scroll extent. /// /// [itemBuilder] will be called only with indices greater than or equal to /// zero and less than [itemCount]. /// /// {@macro flutter.widgets.ListView.builder.itemBuilder} /// /// {@template flutter.widgets.PageView.findChildIndexCallback} /// The [findChildIndexCallback] corresponds to the /// [SliverChildBuilderDelegate.findChildIndexCallback] property. If null, /// a child widget may not map to its existing [RenderObject] when the order /// of children returned from the children builder changes. /// This may result in state-loss. This callback needs to be implemented if /// the order of the children may change at a later time. /// {@endtemplate} /// /// {@macro flutter.widgets.PageView.allowImplicitScrolling} PageView.builder({ super.key, this.scrollDirection = Axis.horizontal, this.reverse = false, this.controller, this.physics, this.pageSnapping = true, this.onPageChanged, required NullableIndexedWidgetBuilder itemBuilder, ChildIndexGetter? findChildIndexCallback, int? itemCount, this.dragStartBehavior = DragStartBehavior.start, this.allowImplicitScrolling = false, this.restorationId, this.clipBehavior = Clip.hardEdge, this.scrollBehavior, this.padEnds = true, }) : childrenDelegate = SliverChildBuilderDelegate( itemBuilder, findChildIndexCallback: findChildIndexCallback, childCount: itemCount, ); /// Creates a scrollable list that works page by page with a custom child /// model. /// /// {@tool dartpad} /// This example shows a [PageView] that uses a custom [SliverChildBuilderDelegate] to support child /// reordering. /// /// ** See code in examples/api/lib/widgets/page_view/page_view.1.dart ** /// {@end-tool} /// /// {@macro flutter.widgets.PageView.allowImplicitScrolling} const PageView.custom({ super.key, this.scrollDirection = Axis.horizontal, this.reverse = false, this.controller, this.physics, this.pageSnapping = true, this.onPageChanged, required this.childrenDelegate, this.dragStartBehavior = DragStartBehavior.start, this.allowImplicitScrolling = false, this.restorationId, this.clipBehavior = Clip.hardEdge, this.scrollBehavior, this.padEnds = true, }); /// Controls whether the widget's pages will respond to /// [RenderObject.showOnScreen], which will allow for implicit accessibility /// scrolling. /// /// With this flag set to false, when accessibility focus reaches the end of /// the current page and the user attempts to move it to the next element, the /// focus will traverse to the next widget outside of the page view. /// /// With this flag set to true, when accessibility focus reaches the end of /// the current page and user attempts to move it to the next element, focus /// will traverse to the next page in the page view. final bool allowImplicitScrolling; /// {@macro flutter.widgets.scrollable.restorationId} final String? restorationId; /// The [Axis] along which the scroll view's offset increases with each page. /// /// For the direction in which active scrolling may be occurring, see /// [ScrollDirection]. /// /// Defaults to [Axis.horizontal]. final Axis scrollDirection; /// Whether the page view scrolls in the reading direction. /// /// For example, if the reading direction is left-to-right and /// [scrollDirection] is [Axis.horizontal], then the page view scrolls from /// left to right when [reverse] is false and from right to left when /// [reverse] is true. /// /// Similarly, if [scrollDirection] is [Axis.vertical], then the page view /// scrolls from top to bottom when [reverse] is false and from bottom to top /// when [reverse] is true. /// /// Defaults to false. final bool reverse; /// An object that can be used to control the position to which this page /// view is scrolled. final PageController? controller; /// How the page view should respond to user input. /// /// For example, determines how the page view continues to animate after the /// user stops dragging the page view. /// /// The physics are modified to snap to page boundaries using /// [PageScrollPhysics] prior to being used. /// /// If an explicit [ScrollBehavior] is provided to [scrollBehavior], the /// [ScrollPhysics] provided by that behavior will take precedence after /// [physics]. /// /// Defaults to matching platform conventions. final ScrollPhysics? physics; /// Set to false to disable page snapping, useful for custom scroll behavior. /// /// If the [padEnds] is false and [PageController.viewportFraction] < 1.0, /// the page will snap to the beginning of the viewport; otherwise, the page /// will snap to the center of the viewport. final bool pageSnapping; /// Called whenever the page in the center of the viewport changes. final ValueChanged<int>? onPageChanged; /// A delegate that provides the children for the [PageView]. /// /// The [PageView.custom] constructor lets you specify this delegate /// explicitly. The [PageView] and [PageView.builder] constructors create a /// [childrenDelegate] that wraps the given [List] and [IndexedWidgetBuilder], /// respectively. final SliverChildDelegate childrenDelegate; /// {@macro flutter.widgets.scrollable.dragStartBehavior} final DragStartBehavior dragStartBehavior; /// {@macro flutter.material.Material.clipBehavior} /// /// Defaults to [Clip.hardEdge]. final Clip clipBehavior; /// {@macro flutter.widgets.shadow.scrollBehavior} /// /// [ScrollBehavior]s also provide [ScrollPhysics]. If an explicit /// [ScrollPhysics] is provided in [physics], it will take precedence, /// followed by [scrollBehavior], and then the inherited ancestor /// [ScrollBehavior]. /// /// The [ScrollBehavior] of the inherited [ScrollConfiguration] will be /// modified by default to not apply a [Scrollbar]. final ScrollBehavior? scrollBehavior; /// Whether to add padding to both ends of the list. /// /// If this is set to true and [PageController.viewportFraction] < 1.0, padding will be added /// such that the first and last child slivers will be in the center of /// the viewport when scrolled all the way to the start or end, respectively. /// /// If [PageController.viewportFraction] >= 1.0, this property has no effect. /// /// This property defaults to true. final bool padEnds; @override State<PageView> createState() => _PageViewState(); } class _PageViewState extends State<PageView> { int _lastReportedPage = 0; late PageController _controller; @override void initState() { super.initState(); _initController(); _lastReportedPage = _controller.initialPage; } @override void dispose() { if (widget.controller == null) { _controller.dispose(); } super.dispose(); } void _initController() { _controller = widget.controller ?? PageController(); } @override void didUpdateWidget(PageView oldWidget) { if (oldWidget.controller != widget.controller) { if (oldWidget.controller == null) { _controller.dispose(); } _initController(); } super.didUpdateWidget(oldWidget); } AxisDirection _getDirection(BuildContext context) { switch (widget.scrollDirection) { case Axis.horizontal: assert(debugCheckHasDirectionality(context)); final TextDirection textDirection = Directionality.of(context); final AxisDirection axisDirection = textDirectionToAxisDirection(textDirection); return widget.reverse ? flipAxisDirection(axisDirection) : axisDirection; case Axis.vertical: return widget.reverse ? AxisDirection.up : AxisDirection.down; } } @override Widget build(BuildContext context) { final AxisDirection axisDirection = _getDirection(context); final ScrollPhysics physics = _ForceImplicitScrollPhysics( allowImplicitScrolling: widget.allowImplicitScrolling, ).applyTo( widget.pageSnapping ? _kPagePhysics.applyTo(widget.physics ?? widget.scrollBehavior?.getScrollPhysics(context)) : widget.physics ?? widget.scrollBehavior?.getScrollPhysics(context), ); return NotificationListener<ScrollNotification>( onNotification: (ScrollNotification notification) { if (notification.depth == 0 && widget.onPageChanged != null && notification is ScrollUpdateNotification) { final PageMetrics metrics = notification.metrics as PageMetrics; final int currentPage = metrics.page!.round(); if (currentPage != _lastReportedPage) { _lastReportedPage = currentPage; widget.onPageChanged!(currentPage); } } return false; }, child: Scrollable( dragStartBehavior: widget.dragStartBehavior, axisDirection: axisDirection, controller: _controller, physics: physics, restorationId: widget.restorationId, scrollBehavior: widget.scrollBehavior ?? ScrollConfiguration.of(context).copyWith(scrollbars: false), viewportBuilder: (BuildContext context, ViewportOffset position) { return Viewport( // TODO(dnfield): we should provide a way to set cacheExtent // independent of implicit scrolling: // https://github.com/flutter/flutter/issues/45632 cacheExtent: widget.allowImplicitScrolling ? 1.0 : 0.0, cacheExtentStyle: CacheExtentStyle.viewport, axisDirection: axisDirection, offset: position, clipBehavior: widget.clipBehavior, slivers: <Widget>[ SliverFillViewport( viewportFraction: _controller.viewportFraction, delegate: widget.childrenDelegate, padEnds: widget.padEnds, ), ], ); }, ), ); } @override void debugFillProperties(DiagnosticPropertiesBuilder description) { super.debugFillProperties(description); description.add(EnumProperty<Axis>('scrollDirection', widget.scrollDirection)); description.add(FlagProperty('reverse', value: widget.reverse, ifTrue: 'reversed')); description.add(DiagnosticsProperty<PageController>('controller', _controller, showName: false)); description.add(DiagnosticsProperty<ScrollPhysics>('physics', widget.physics, showName: false)); description.add(FlagProperty('pageSnapping', value: widget.pageSnapping, ifFalse: 'snapping disabled')); description.add(FlagProperty('allowImplicitScrolling', value: widget.allowImplicitScrolling, ifTrue: 'allow implicit scrolling')); } }
flutter/packages/flutter/lib/src/widgets/page_view.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/page_view.dart", "repo_id": "flutter", "token_count": 11281 }
652
// 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 'package:flutter/foundation.dart'; import 'basic.dart'; import 'debug.dart'; import 'framework.dart'; import 'media_query.dart'; /// A widget that insets its child by sufficient padding to avoid intrusions by /// the operating system. /// /// For example, this will indent the child by enough to avoid the status bar at /// the top of the screen. /// /// It will also indent the child by the amount necessary to avoid The Notch on /// the iPhone X, or other similar creative physical features of the display. /// /// When a [minimum] padding is specified, the greater of the minimum padding /// or the safe area padding will be applied. /// /// {@youtube 560 315 https://www.youtube.com/watch?v=lkF0TQJO0bA} /// /// See also: /// /// * [SliverSafeArea], for insetting slivers to avoid operating system /// intrusions. /// * [Padding], for insetting widgets in general. /// * [MediaQuery], from which the window padding is obtained. /// * [dart:ui.FlutterView.padding], which reports the padding from the operating /// system. class SafeArea extends StatelessWidget { /// Creates a widget that avoids operating system interfaces. /// /// The [left], [top], [right], [bottom], and [minimum] arguments must not be /// null. const SafeArea({ super.key, this.left = true, this.top = true, this.right = true, this.bottom = true, this.minimum = EdgeInsets.zero, this.maintainBottomViewPadding = false, required this.child, }); /// Whether to avoid system intrusions on the left. final bool left; /// Whether to avoid system intrusions at the top of the screen, typically the /// system status bar. final bool top; /// Whether to avoid system intrusions on the right. final bool right; /// Whether to avoid system intrusions on the bottom side of the screen. final bool bottom; /// This minimum padding to apply. /// /// The greater of the minimum insets and the media padding will be applied. final EdgeInsets minimum; /// Specifies whether the [SafeArea] should maintain the bottom /// [MediaQueryData.viewPadding] instead of the bottom [MediaQueryData.padding], /// defaults to false. /// /// For example, if there is an onscreen keyboard displayed above the /// SafeArea, the padding can be maintained below the obstruction rather than /// being consumed. This can be helpful in cases where your layout contains /// flexible widgets, which could visibly move when opening a software /// keyboard due to the change in the padding value. Setting this to true will /// avoid the UI shift. final bool maintainBottomViewPadding; /// The widget below this widget in the tree. /// /// The padding on the [MediaQuery] for the [child] will be suitably adjusted /// to zero out any sides that were avoided by this widget. /// /// {@macro flutter.widgets.ProxyWidget.child} final Widget child; @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); EdgeInsets padding = MediaQuery.paddingOf(context); // Bottom padding has been consumed - i.e. by the keyboard if (maintainBottomViewPadding) { padding = padding.copyWith(bottom: MediaQuery.viewPaddingOf(context).bottom); } return Padding( padding: EdgeInsets.only( left: math.max(left ? padding.left : 0.0, minimum.left), top: math.max(top ? padding.top : 0.0, minimum.top), right: math.max(right ? padding.right : 0.0, minimum.right), bottom: math.max(bottom ? padding.bottom : 0.0, minimum.bottom), ), child: MediaQuery.removePadding( context: context, removeLeft: left, removeTop: top, removeRight: right, removeBottom: bottom, child: child, ), ); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(FlagProperty('left', value: left, ifTrue: 'avoid left padding')); properties.add(FlagProperty('top', value: top, ifTrue: 'avoid top padding')); properties.add(FlagProperty('right', value: right, ifTrue: 'avoid right padding')); properties.add(FlagProperty('bottom', value: bottom, ifTrue: 'avoid bottom padding')); } } /// A sliver that insets another sliver by sufficient padding to avoid /// intrusions by the operating system. /// /// For example, this will indent the sliver by enough to avoid the status bar /// at the top of the screen. /// /// It will also indent the sliver by the amount necessary to avoid The Notch /// on the iPhone X, or other similar creative physical features of the /// display. /// /// When a [minimum] padding is specified, the greater of the minimum padding /// or the safe area padding will be applied. /// /// See also: /// /// * [SafeArea], for insetting box widgets to avoid operating system intrusions. /// * [SliverPadding], for insetting slivers in general. /// * [MediaQuery], from which the window padding is obtained. /// * [dart:ui.FlutterView.padding], which reports the padding from the operating /// system. class SliverSafeArea extends StatelessWidget { /// Creates a sliver that avoids operating system interfaces. const SliverSafeArea({ super.key, this.left = true, this.top = true, this.right = true, this.bottom = true, this.minimum = EdgeInsets.zero, required this.sliver, }); /// Whether to avoid system intrusions on the left. final bool left; /// Whether to avoid system intrusions at the top of the screen, typically the /// system status bar. final bool top; /// Whether to avoid system intrusions on the right. final bool right; /// Whether to avoid system intrusions on the bottom side of the screen. final bool bottom; /// This minimum padding to apply. /// /// The greater of the minimum padding and the media padding is be applied. final EdgeInsets minimum; /// The sliver below this sliver in the tree. /// /// The padding on the [MediaQuery] for the [sliver] will be suitably adjusted /// to zero out any sides that were avoided by this sliver. final Widget sliver; @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); final EdgeInsets padding = MediaQuery.paddingOf(context); return SliverPadding( padding: EdgeInsets.only( left: math.max(left ? padding.left : 0.0, minimum.left), top: math.max(top ? padding.top : 0.0, minimum.top), right: math.max(right ? padding.right : 0.0, minimum.right), bottom: math.max(bottom ? padding.bottom : 0.0, minimum.bottom), ), sliver: MediaQuery.removePadding( context: context, removeLeft: left, removeTop: top, removeRight: right, removeBottom: bottom, child: sliver, ), ); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(FlagProperty('left', value: left, ifTrue: 'avoid left padding')); properties.add(FlagProperty('top', value: top, ifTrue: 'avoid top padding')); properties.add(FlagProperty('right', value: right, ifTrue: 'avoid right padding')); properties.add(FlagProperty('bottom', value: bottom, ifTrue: 'avoid bottom padding')); } }
flutter/packages/flutter/lib/src/widgets/safe_area.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/safe_area.dart", "repo_id": "flutter", "token_count": 2315 }
653
// 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 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'actions.dart'; import 'basic.dart'; import 'framework.dart'; import 'primary_scroll_controller.dart'; import 'scroll_configuration.dart'; import 'scroll_controller.dart'; import 'scroll_metrics.dart'; import 'scroll_physics.dart'; import 'scrollable.dart'; export 'package:flutter/physics.dart' show Tolerance; /// Describes the aspects of a Scrollable widget to inform inherited widgets /// like [ScrollBehavior] for decorating or enumerate the properties of combined /// Scrollables, such as [TwoDimensionalScrollable]. /// /// Decorations like [GlowingOverscrollIndicator]s and [Scrollbar]s require /// information about the Scrollable in order to be initialized. @immutable class ScrollableDetails { /// Creates a set of details describing the [Scrollable]. const ScrollableDetails({ required this.direction, this.controller, this.physics, @Deprecated( 'Migrate to decorationClipBehavior. ' 'This property was deprecated so that its application is clearer. This clip ' 'applies to decorators, and does not directly clip a scroll view. ' 'This feature was deprecated after v3.9.0-1.0.pre.' ) Clip? clipBehavior, Clip? decorationClipBehavior, }) : decorationClipBehavior = clipBehavior ?? decorationClipBehavior; /// A constructor specific to a [Scrollable] with an [Axis.vertical]. const ScrollableDetails.vertical({ bool reverse = false, this.controller, this.physics, this.decorationClipBehavior, }) : direction = reverse ? AxisDirection.up : AxisDirection.down; /// A constructor specific to a [Scrollable] with an [Axis.horizontal]. const ScrollableDetails.horizontal({ bool reverse = false, this.controller, this.physics, this.decorationClipBehavior, }) : direction = reverse ? AxisDirection.left : AxisDirection.right; /// {@macro flutter.widgets.Scrollable.axisDirection} final AxisDirection direction; /// {@macro flutter.widgets.Scrollable.controller} final ScrollController? controller; /// {@macro flutter.widgets.Scrollable.physics} final ScrollPhysics? physics; /// {@macro flutter.material.Material.clipBehavior} /// /// This can be used by [MaterialScrollBehavior] to clip a /// [StretchingOverscrollIndicator]. /// /// This [Clip] does not affect the [Viewport.clipBehavior], but is rather /// passed from the same value by [Scrollable] so that decorators like /// [StretchingOverscrollIndicator] honor the same clip. /// /// Defaults to null. final Clip? decorationClipBehavior; /// Deprecated getter for [decorationClipBehavior]. @Deprecated( 'Migrate to decorationClipBehavior. ' 'This property was deprecated so that its application is clearer. This clip ' 'applies to decorators, and does not directly clip a scroll view. ' 'This feature was deprecated after v3.9.0-1.0.pre.' ) Clip? get clipBehavior => decorationClipBehavior; /// Copy the current [ScrollableDetails] with the given values replacing the /// current values. ScrollableDetails copyWith({ AxisDirection? direction, ScrollController? controller, ScrollPhysics? physics, Clip? decorationClipBehavior, }) { return ScrollableDetails( direction: direction ?? this.direction, controller: controller ?? this.controller, physics: physics ?? this.physics, decorationClipBehavior: decorationClipBehavior ?? this.decorationClipBehavior, ); } @override String toString() { final List<String> description = <String>[]; description.add('axisDirection: $direction'); void addIfNonNull(String prefix, Object? value) { if (value != null) { description.add(prefix + value.toString()); } } addIfNonNull('scroll controller: ', controller); addIfNonNull('scroll physics: ', physics); addIfNonNull('decorationClipBehavior: ', decorationClipBehavior); return '${describeIdentity(this)}(${description.join(", ")})'; } @override int get hashCode => Object.hash( direction, controller, physics, decorationClipBehavior, ); @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is ScrollableDetails && other.direction == direction && other.controller == controller && other.physics == physics && other.decorationClipBehavior == decorationClipBehavior; } } /// An auto scroller that scrolls the [scrollable] if a drag gesture drags close /// to its edge. /// /// The scroll velocity is controlled by the [velocityScalar]: /// /// velocity = <distance of overscroll> * [velocityScalar]. class EdgeDraggingAutoScroller { /// Creates a auto scroller that scrolls the [scrollable]. EdgeDraggingAutoScroller( this.scrollable, { this.onScrollViewScrolled, required this.velocityScalar, }); /// The [Scrollable] this auto scroller is scrolling. final ScrollableState scrollable; /// Called when a scroll view is scrolled. /// /// The scroll view may be scrolled multiple times in a row until the drag /// target no longer triggers the auto scroll. This callback will be called /// in between each scroll. final VoidCallback? onScrollViewScrolled; /// {@template flutter.widgets.EdgeDraggingAutoScroller.velocityScalar} /// The velocity scalar per pixel over scroll. /// /// It represents how the velocity scale with the over scroll distance. The /// auto-scroll velocity = <distance of overscroll> * velocityScalar. /// {@endtemplate} final double velocityScalar; late Rect _dragTargetRelatedToScrollOrigin; /// Whether the auto scroll is in progress. bool get scrolling => _scrolling; bool _scrolling = false; double _offsetExtent(Offset offset, Axis scrollDirection) { return switch (scrollDirection) { Axis.horizontal => offset.dx, Axis.vertical => offset.dy, }; } double _sizeExtent(Size size, Axis scrollDirection) { return switch (scrollDirection) { Axis.horizontal => size.width, Axis.vertical => size.height, }; } AxisDirection get _axisDirection => scrollable.axisDirection; Axis get _scrollDirection => axisDirectionToAxis(_axisDirection); /// Starts the auto scroll if the [dragTarget] is close to the edge. /// /// The scroll starts to scroll the [scrollable] if the target rect is close /// to the edge of the [scrollable]; otherwise, it remains stationary. /// /// If the scrollable is already scrolling, calling this method updates the /// previous dragTarget to the new value and continues scrolling if necessary. void startAutoScrollIfNecessary(Rect dragTarget) { final Offset deltaToOrigin = scrollable.deltaToScrollOrigin; _dragTargetRelatedToScrollOrigin = dragTarget.translate(deltaToOrigin.dx, deltaToOrigin.dy); if (_scrolling) { // The change will be picked up in the next scroll. return; } assert(!_scrolling); _scroll(); } /// Stop any ongoing auto scrolling. void stopAutoScroll() { _scrolling = false; } Future<void> _scroll() async { final RenderBox scrollRenderBox = scrollable.context.findRenderObject()! as RenderBox; final Rect globalRect = MatrixUtils.transformRect( scrollRenderBox.getTransformTo(null), Rect.fromLTWH(0, 0, scrollRenderBox.size.width, scrollRenderBox.size.height), ); assert( globalRect.size.width >= _dragTargetRelatedToScrollOrigin.size.width && globalRect.size.height >= _dragTargetRelatedToScrollOrigin.size.height, 'Drag target size is larger than scrollable size, which may cause bouncing', ); _scrolling = true; double? newOffset; const double overDragMax = 20.0; final Offset deltaToOrigin = scrollable.deltaToScrollOrigin; final Offset viewportOrigin = globalRect.topLeft.translate(deltaToOrigin.dx, deltaToOrigin.dy); final double viewportStart = _offsetExtent(viewportOrigin, _scrollDirection); final double viewportEnd = viewportStart + _sizeExtent(globalRect.size, _scrollDirection); final double proxyStart = _offsetExtent(_dragTargetRelatedToScrollOrigin.topLeft, _scrollDirection); final double proxyEnd = _offsetExtent(_dragTargetRelatedToScrollOrigin.bottomRight, _scrollDirection); switch (_axisDirection) { case AxisDirection.up: case AxisDirection.left: if (proxyEnd > viewportEnd && scrollable.position.pixels > scrollable.position.minScrollExtent) { final double overDrag = math.min(proxyEnd - viewportEnd, overDragMax); newOffset = math.max(scrollable.position.minScrollExtent, scrollable.position.pixels - overDrag); } else if (proxyStart < viewportStart && scrollable.position.pixels < scrollable.position.maxScrollExtent) { final double overDrag = math.min(viewportStart - proxyStart, overDragMax); newOffset = math.min(scrollable.position.maxScrollExtent, scrollable.position.pixels + overDrag); } case AxisDirection.right: case AxisDirection.down: if (proxyStart < viewportStart && scrollable.position.pixels > scrollable.position.minScrollExtent) { final double overDrag = math.min(viewportStart - proxyStart, overDragMax); newOffset = math.max(scrollable.position.minScrollExtent, scrollable.position.pixels - overDrag); } else if (proxyEnd > viewportEnd && scrollable.position.pixels < scrollable.position.maxScrollExtent) { final double overDrag = math.min(proxyEnd - viewportEnd, overDragMax); newOffset = math.min(scrollable.position.maxScrollExtent, scrollable.position.pixels + overDrag); } } if (newOffset == null || (newOffset - scrollable.position.pixels).abs() < 1.0) { // Drag should not trigger scroll. _scrolling = false; return; } final Duration duration = Duration(milliseconds: (1000 / velocityScalar).round()); await scrollable.position.animateTo( newOffset, duration: duration, curve: Curves.linear, ); if (onScrollViewScrolled != null) { onScrollViewScrolled!(); } if (_scrolling) { await _scroll(); } } } /// A typedef for a function that can calculate the offset for a type of scroll /// increment given a [ScrollIncrementDetails]. /// /// This function is used as the type for [Scrollable.incrementCalculator], /// which is called from a [ScrollAction]. typedef ScrollIncrementCalculator = double Function(ScrollIncrementDetails details); /// Describes the type of scroll increment that will be performed by a /// [ScrollAction] on a [Scrollable]. /// /// This is used to configure a [ScrollIncrementDetails] object to pass to a /// [ScrollIncrementCalculator] function on a [Scrollable]. /// /// {@template flutter.widgets.ScrollIncrementType.intent} /// This indicates the *intent* of the scroll, not necessarily the size. Not all /// scrollable areas will have the concept of a "line" or "page", but they can /// respond to the different standard key bindings that cause scrolling, which /// are bound to keys that people use to indicate a "line" scroll (e.g. /// control-arrowDown keys) or a "page" scroll (e.g. pageDown key). It is /// recommended that at least the relative magnitudes of the scrolls match /// expectations. /// {@endtemplate} enum ScrollIncrementType { /// Indicates that the [ScrollIncrementCalculator] should return the scroll /// distance it should move when the user requests to scroll by a "line". /// /// The distance a "line" scrolls refers to what should happen when the key /// binding for "scroll down/up by a line" is triggered. It's up to the /// [ScrollIncrementCalculator] function to decide what that means for a /// particular scrollable. line, /// Indicates that the [ScrollIncrementCalculator] should return the scroll /// distance it should move when the user requests to scroll by a "page". /// /// The distance a "page" scrolls refers to what should happen when the key /// binding for "scroll down/up by a page" is triggered. It's up to the /// [ScrollIncrementCalculator] function to decide what that means for a /// particular scrollable. page, } /// A details object that describes the type of scroll increment being requested /// of a [ScrollIncrementCalculator] function, as well as the current metrics /// for the scrollable. class ScrollIncrementDetails { /// A const constructor for a [ScrollIncrementDetails]. const ScrollIncrementDetails({ required this.type, required this.metrics, }); /// The type of scroll this is (e.g. line, page, etc.). /// /// {@macro flutter.widgets.ScrollIncrementType.intent} final ScrollIncrementType type; /// The current metrics of the scrollable that is being scrolled. final ScrollMetrics metrics; } /// An [Intent] that represents scrolling the nearest scrollable by an amount /// appropriate for the [type] specified. /// /// The actual amount of the scroll is determined by the /// [Scrollable.incrementCalculator], or by its defaults if that is not /// specified. class ScrollIntent extends Intent { /// Creates a const [ScrollIntent] that requests scrolling in the given /// [direction], with the given [type]. const ScrollIntent({ required this.direction, this.type = ScrollIncrementType.line, }); /// The direction in which to scroll the scrollable containing the focused /// widget. final AxisDirection direction; /// The type of scrolling that is intended. final ScrollIncrementType type; } /// An [Action] that scrolls the relevant [Scrollable] by the amount configured /// in the [ScrollIntent] given to it. /// /// If a Scrollable cannot be found above the given [BuildContext], the /// [PrimaryScrollController] will be considered for default handling of /// [ScrollAction]s. /// /// If [Scrollable.incrementCalculator] is null for the scrollable, the default /// for a [ScrollIntent.type] set to [ScrollIncrementType.page] is 80% of the /// size of the scroll window, and for [ScrollIncrementType.line], 50 logical /// pixels. class ScrollAction extends ContextAction<ScrollIntent> { @override bool isEnabled(ScrollIntent intent, [BuildContext? context]) { if (context == null) { return false; } if (Scrollable.maybeOf(context) != null) { return true; } final ScrollController? primaryScrollController = PrimaryScrollController.maybeOf(context); return (primaryScrollController != null) && (primaryScrollController.hasClients); } /// Returns the scroll increment for a single scroll request, for use when /// scrolling using a hardware keyboard. /// /// Must not be called when the position is null, or when any of the position /// metrics (pixels, viewportDimension, maxScrollExtent, minScrollExtent) are /// null. The widget must have already been laid out so that the position /// fields are valid. static double _calculateScrollIncrement(ScrollableState state, { ScrollIncrementType type = ScrollIncrementType.line }) { assert(state.position.hasPixels); assert(state.resolvedPhysics == null || state.resolvedPhysics!.shouldAcceptUserOffset(state.position)); if (state.widget.incrementCalculator != null) { return state.widget.incrementCalculator!( ScrollIncrementDetails( type: type, metrics: state.position, ), ); } return switch (type) { ScrollIncrementType.line => 50.0, ScrollIncrementType.page => 0.8 * state.position.viewportDimension, }; } /// Find out how much of an increment to move by, taking the different /// directions into account. static double getDirectionalIncrement(ScrollableState state, ScrollIntent intent) { if (axisDirectionToAxis(intent.direction) == axisDirectionToAxis(state.axisDirection)) { final double increment = _calculateScrollIncrement(state, type: intent.type); return intent.direction == state.axisDirection ? increment : -increment; } return 0.0; } @override void invoke(ScrollIntent intent, [BuildContext? context]) { assert(context != null, 'Cannot scroll without a context.'); ScrollableState? state = Scrollable.maybeOf(context!); if (state == null) { final ScrollController primaryScrollController = PrimaryScrollController.of(context); assert (() { if (primaryScrollController.positions.length != 1) { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary( 'A ScrollAction was invoked with the PrimaryScrollController, but ' 'more than one ScrollPosition is attached.', ), ErrorDescription( 'Only one ScrollPosition can be manipulated by a ScrollAction at ' 'a time.', ), ErrorHint( 'The PrimaryScrollController can be inherited automatically by ' 'descendant ScrollViews based on the TargetPlatform and scroll ' 'direction. By default, the PrimaryScrollController is ' 'automatically inherited on mobile platforms for vertical ' 'ScrollViews. ScrollView.primary can also override this behavior.', ), ]); } return true; }()); if (primaryScrollController.position.context.notificationContext == null && Scrollable.maybeOf(primaryScrollController.position.context.notificationContext!) == null) { return; } state = Scrollable.maybeOf(primaryScrollController.position.context.notificationContext!); } assert(state != null, '$ScrollAction was invoked on a context that has no scrollable parent'); assert(state!.position.hasPixels, 'Scrollable must be laid out before it can be scrolled via a ScrollAction'); // Don't do anything if the user isn't allowed to scroll. if (state!.resolvedPhysics != null && !state.resolvedPhysics!.shouldAcceptUserOffset(state.position)) { return; } final double increment = getDirectionalIncrement(state, intent); if (increment == 0.0) { return; } state.position.moveTo( state.position.pixels + increment, duration: const Duration(milliseconds: 100), curve: Curves.easeInOut, ); } }
flutter/packages/flutter/lib/src/widgets/scrollable_helpers.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/scrollable_helpers.dart", "repo_id": "flutter", "token_count": 5935 }
654
// 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 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'framework.dart'; /// A superclass for [RenderObjectWidget]s that configure [RenderObject] /// subclasses that organize their children in different slots. /// /// Implementers of this mixin have to provide the list of available slots by /// overriding [slots]. The list of slots must never change for a given class /// implementing this mixin. In the common case, [Enum] values are used as slots /// and [slots] is typically implemented to return the value of the enum's /// `values` getter. /// /// Furthermore, [childForSlot] must be implemented to return the current /// widget configuration for a given slot. /// /// The [RenderObject] returned by [createRenderObject] and updated by /// [updateRenderObject] must implement [SlottedContainerRenderObjectMixin]. /// /// The type parameter `SlotType` is the type for the slots to be used by this /// [RenderObjectWidget] and the [RenderObject] it configures. In the typical /// case, `SlotType` is an [Enum] type. /// /// The type parameter `ChildType` is the type used for the [RenderObject] children /// (e.g. [RenderBox] or [RenderSliver]). In the typical case, `ChildType` is /// [RenderBox]. This class does not support having different kinds of children /// for different slots. /// /// {@tool dartpad} /// This example uses the [SlottedMultiChildRenderObjectWidget] in /// combination with the [SlottedContainerRenderObjectMixin] to implement a /// widget that provides two slots: topLeft and bottomRight. The widget arranges /// the children in those slots diagonally. /// /// ** See code in examples/api/lib/widgets/slotted_render_object_widget/slotted_multi_child_render_object_widget_mixin.0.dart ** /// {@end-tool} /// /// See also: /// /// * [MultiChildRenderObjectWidget], which configures a [RenderObject] /// with a single list of children. /// * [ListTile], which uses [SlottedMultiChildRenderObjectWidget] in its /// internal (private) implementation. abstract class SlottedMultiChildRenderObjectWidget<SlotType, ChildType extends RenderObject> extends RenderObjectWidget with SlottedMultiChildRenderObjectWidgetMixin<SlotType, ChildType> { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. const SlottedMultiChildRenderObjectWidget({ super.key }); } /// A mixin version of [SlottedMultiChildRenderObjectWidget]. /// /// This mixin provides the same logic as extending /// [SlottedMultiChildRenderObjectWidget] directly. /// /// It was deprecated to simplify the process of creating slotted widgets. @Deprecated( 'Extend SlottedMultiChildRenderObjectWidget instead of mixing in SlottedMultiChildRenderObjectWidgetMixin. ' 'This feature was deprecated after v3.10.0-1.5.pre.' ) mixin SlottedMultiChildRenderObjectWidgetMixin<SlotType, ChildType extends RenderObject> on RenderObjectWidget { /// Returns a list of all available slots. /// /// The list of slots must be static and must never change for a given class /// implementing this mixin. /// /// Typically, an [Enum] is used to identify the different slots. In that case /// this getter can be implemented by returning what the `values` getter /// of the enum used returns. @protected Iterable<SlotType> get slots; /// Returns the widget that is currently occupying the provided `slot`. /// /// The [RenderObject] configured by this class will be configured to have /// the [RenderObject] produced by the returned [Widget] in the provided /// `slot`. @protected Widget? childForSlot(SlotType slot); @override SlottedContainerRenderObjectMixin<SlotType, ChildType> createRenderObject(BuildContext context); @override void updateRenderObject(BuildContext context, SlottedContainerRenderObjectMixin<SlotType, ChildType> renderObject); @override SlottedRenderObjectElement<SlotType, ChildType> createElement() => SlottedRenderObjectElement<SlotType, ChildType>(this); } /// Mixin for a [RenderObject] configured by a [SlottedMultiChildRenderObjectWidget]. /// /// The [RenderObject] child currently occupying a given slot can be obtained by /// calling [childForSlot]. /// /// Implementers may consider overriding [children] to return the children /// of this render object in a consistent order (e.g. hit test order). /// /// The type parameter `SlotType` is the type for the slots to be used by this /// [RenderObject] and the [SlottedMultiChildRenderObjectWidget] it was /// configured by. In the typical case, `SlotType` is an [Enum] type. /// /// The type parameter `ChildType` is the type of [RenderObject] used for the children /// (e.g. [RenderBox] or [RenderSliver]). In the typical case, `ChildType` is /// [RenderBox]. This mixin does not support having different kinds of children /// for different slots. /// /// See [SlottedMultiChildRenderObjectWidget] for example code showcasing how /// this mixin is used in combination with [SlottedMultiChildRenderObjectWidget]. /// /// See also: /// /// * [ContainerRenderObjectMixin], which organizes its children in a single /// list. mixin SlottedContainerRenderObjectMixin<SlotType, ChildType extends RenderObject> on RenderObject { /// Returns the [RenderObject] child that is currently occupying the provided /// `slot`. /// /// Returns null if no [RenderObject] is configured for the given slot. @protected ChildType? childForSlot(SlotType slot) => _slotToChild[slot]; /// Returns an [Iterable] of all non-null children. /// /// This getter is used by the default implementation of [attach], [detach], /// [redepthChildren], [visitChildren], and [debugDescribeChildren] to iterate /// over the children of this [RenderObject]. The base implementation makes no /// guarantee about the order in which the children are returned. Subclasses /// for which the child order is important should override this getter and /// return the children in the desired order. @protected Iterable<ChildType> get children => _slotToChild.values; /// Returns the debug name for a given `slot`. /// /// This method is called by [debugDescribeChildren] for each slot that is /// currently occupied by a child to obtain a name for that slot for debug /// outputs. /// /// The default implementation calls [EnumName.name] on `slot` if it is an /// [Enum] value and `toString` if it is not. @protected String debugNameForSlot(SlotType slot) { if (slot is Enum) { return slot.name; } return slot.toString(); } @override void attach(PipelineOwner owner) { super.attach(owner); for (final ChildType child in children) { child.attach(owner); } } @override void detach() { super.detach(); for (final ChildType child in children) { child.detach(); } } @override void redepthChildren() { children.forEach(redepthChild); } @override void visitChildren(RenderObjectVisitor visitor) { children.forEach(visitor); } @override List<DiagnosticsNode> debugDescribeChildren() { final List<DiagnosticsNode> value = <DiagnosticsNode>[]; final Map<ChildType, SlotType> childToSlot = Map<ChildType, SlotType>.fromIterables( _slotToChild.values, _slotToChild.keys, ); for (final ChildType child in children) { _addDiagnostics(child, value, debugNameForSlot(childToSlot[child] as SlotType)); } return value; } void _addDiagnostics(ChildType child, List<DiagnosticsNode> value, String name) { value.add(child.toDiagnosticsNode(name: name)); } final Map<SlotType, ChildType> _slotToChild = <SlotType, ChildType>{}; void _setChild(ChildType? child, SlotType slot) { final ChildType? oldChild = _slotToChild[slot]; if (oldChild != null) { dropChild(oldChild); _slotToChild.remove(slot); } if (child != null) { _slotToChild[slot] = child; adoptChild(child); } } void _moveChild(ChildType child, SlotType slot, SlotType oldSlot) { assert(slot != oldSlot); final ChildType? oldChild = _slotToChild[oldSlot]; if (oldChild == child) { _setChild(null, oldSlot); } _setChild(child, slot); } } /// Element used by the [SlottedMultiChildRenderObjectWidget]. class SlottedRenderObjectElement<SlotType, ChildType extends RenderObject> extends RenderObjectElement { /// Creates an element that uses the given widget as its configuration. SlottedRenderObjectElement(SlottedMultiChildRenderObjectWidgetMixin<SlotType, ChildType> super.widget); Map<SlotType, Element> _slotToChild = <SlotType, Element>{}; Map<Key, Element> _keyedChildren = <Key, Element>{}; @override SlottedContainerRenderObjectMixin<SlotType, ChildType> get renderObject => super.renderObject as SlottedContainerRenderObjectMixin<SlotType, ChildType>; @override void visitChildren(ElementVisitor visitor) { _slotToChild.values.forEach(visitor); } @override void forgetChild(Element child) { assert(_slotToChild.containsValue(child)); assert(child.slot is SlotType); assert(_slotToChild.containsKey(child.slot)); _slotToChild.remove(child.slot); super.forgetChild(child); } @override void mount(Element? parent, Object? newSlot) { super.mount(parent, newSlot); _updateChildren(); } @override void update(SlottedMultiChildRenderObjectWidgetMixin<SlotType, ChildType> newWidget) { super.update(newWidget); assert(widget == newWidget); _updateChildren(); } List<SlotType>? _debugPreviousSlots; void _updateChildren() { final SlottedMultiChildRenderObjectWidgetMixin<SlotType, ChildType> slottedMultiChildRenderObjectWidgetMixin = widget as SlottedMultiChildRenderObjectWidgetMixin<SlotType, ChildType>; assert(() { _debugPreviousSlots ??= slottedMultiChildRenderObjectWidgetMixin.slots.toList(); return listEquals(_debugPreviousSlots, slottedMultiChildRenderObjectWidgetMixin.slots.toList()); }(), '${widget.runtimeType}.slots must not change.'); assert(slottedMultiChildRenderObjectWidgetMixin.slots.toSet().length == slottedMultiChildRenderObjectWidgetMixin.slots.length, 'slots must be unique'); final Map<Key, Element> oldKeyedElements = _keyedChildren; _keyedChildren = <Key, Element>{}; final Map<SlotType, Element> oldSlotToChild = _slotToChild; _slotToChild = <SlotType, Element>{}; Map<Key, List<Element>>? debugDuplicateKeys; for (final SlotType slot in slottedMultiChildRenderObjectWidgetMixin.slots) { final Widget? widget = slottedMultiChildRenderObjectWidgetMixin.childForSlot(slot); final Key? newWidgetKey = widget?.key; final Element? oldSlotChild = oldSlotToChild[slot]; final Element? oldKeyChild = oldKeyedElements[newWidgetKey]; // Try to find the slot for the correct Element that `widget` should update. // If key matching fails, resort to `oldSlotChild` from the same slot. final Element? fromElement; if (oldKeyChild != null) { fromElement = oldSlotToChild.remove(oldKeyChild.slot as SlotType); } else if (oldSlotChild?.widget.key == null) { fromElement = oldSlotToChild.remove(slot); } else { // The only case we can't use `oldSlotChild` is when its widget has a key. assert(oldSlotChild!.widget.key != newWidgetKey); fromElement = null; } final Element? newChild = updateChild(fromElement, widget, slot); if (newChild != null) { _slotToChild[slot] = newChild; if (newWidgetKey != null) { assert(() { final Element? existingElement = _keyedChildren[newWidgetKey]; if (existingElement != null) { (debugDuplicateKeys ??= <Key, List<Element>>{}) .putIfAbsent(newWidgetKey, () => <Element>[existingElement]) .add(newChild); } return true; }()); _keyedChildren[newWidgetKey] = newChild; } } } oldSlotToChild.values.forEach(deactivateChild); assert(_debugDuplicateKeys(debugDuplicateKeys)); assert(_keyedChildren.values.every(_slotToChild.values.contains), '_keyedChildren ${_keyedChildren.values} should be a subset of ${_slotToChild.values}'); } bool _debugDuplicateKeys(Map<Key, List<Element>>? debugDuplicateKeys) { if (debugDuplicateKeys == null) { return true; } for (final MapEntry<Key, List<Element>> duplicateKey in debugDuplicateKeys.entries) { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('Multiple widgets used the same key in ${widget.runtimeType}.'), ErrorDescription( 'The key ${duplicateKey.key} was used by multiple widgets. The offending widgets were:\n' ), for (final Element element in duplicateKey.value) ErrorDescription(' - $element\n'), ErrorDescription( 'A key can only be specified on one widget at a time in the same parent widget.', ), ]); } return true; } @override void insertRenderObjectChild(ChildType child, SlotType slot) { renderObject._setChild(child, slot); assert(renderObject._slotToChild[slot] == child); } @override void removeRenderObjectChild(ChildType child, SlotType slot) { if (renderObject._slotToChild[slot] == child) { renderObject._setChild(null, slot); assert(renderObject._slotToChild[slot] == null); } } @override void moveRenderObjectChild(ChildType child, SlotType oldSlot, SlotType newSlot) { renderObject._moveChild(child, newSlot, oldSlot); } }
flutter/packages/flutter/lib/src/widgets/slotted_render_object_widget.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/slotted_render_object_widget.dart", "repo_id": "flutter", "token_count": 4348 }
655
// 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 'package:flutter/animation.dart'; import 'framework.dart'; import 'implicit_animations.dart'; import 'value_listenable_builder.dart'; /// [Widget] builder that animates a property of a [Widget] to a target value /// whenever the target value changes. /// /// {@youtube 560 315 https://www.youtube.com/watch?v=l9uHB8VXZOg} /// /// The type of the animated property ([Color], [Rect], [double], etc.) is /// defined via the type of the provided [tween] (e.g. [ColorTween], /// [RectTween], [Tween<double>], etc.). /// /// The [tween] also defines the target value for the animation: When the widget /// first builds, it animates from [Tween.begin] to [Tween.end]. A new animation /// can be triggered anytime by providing a new [tween] with a new [Tween.end] /// value. The new animation runs from the current animation value (which may be /// [Tween.end] of the old [tween], if that animation completed) to [Tween.end] /// of the new [tween]. /// /// The animation is further customized by providing a [curve] and [duration]. /// /// The current value of the animation along with the [child] is passed to /// the [builder] callback, which is expected to build a [Widget] based on the /// current animation value. The [builder] is called throughout the animation /// for every animation value until [Tween.end] is reached. /// /// A provided [onEnd] callback is called whenever an animation completes. /// Registering an [onEnd] callback my be useful to trigger an action (like /// another animation) at the end of the current animation. /// /// ## Performance optimizations /// /// If your [builder] function contains a subtree that does not depend on the /// animation, it's more efficient to build that subtree once instead of /// rebuilding it on every animation tick. /// /// If you pass the pre-built subtree as the [child] parameter, the /// AnimatedBuilder will pass it back to your builder function so that you /// can incorporate it into your build. /// /// Using this pre-built child is entirely optional, but can improve /// performance significantly in some cases and is therefore a good practice. /// /// ## Ownership of the [Tween] /// /// The [TweenAnimationBuilder] takes full ownership of the provided [tween] /// instance and it will mutate it. Once a [Tween] has been passed to a /// [TweenAnimationBuilder], its properties should not be accessed or changed /// anymore to avoid interference with the [TweenAnimationBuilder]. /// /// It is good practice to never store a [Tween] provided to a /// [TweenAnimationBuilder] in an instance variable to avoid accidental /// modifications of the [Tween]. /// /// ## Example Code /// /// {@tool dartpad} /// This example shows an [IconButton] that "zooms" in when the widget first /// builds (its size smoothly increases from 0 to 24) and whenever the button /// is pressed, it smoothly changes its size to the new target value of either /// 48 or 24. /// /// ** See code in examples/api/lib/widgets/tween_animation_builder/tween_animation_builder.0.dart ** /// {@end-tool} /// /// ## Relationship to [ImplicitlyAnimatedWidget]s and [AnimatedWidget]s /// /// The [ImplicitlyAnimatedWidget] has many subclasses that provide animated /// versions of regular widgets. These subclasses (like [AnimatedOpacity], /// [AnimatedContainer], [AnimatedSize], etc.) animate changes in their /// properties smoothly and they are easier to use than this general-purpose /// builder. However, [TweenAnimationBuilder] (which itself is a subclass of /// [ImplicitlyAnimatedWidget]) is handy for animating any widget property to a /// given target value even when the framework (or third-party widget library) /// doesn't ship with an animated version of that widget. /// /// Those [ImplicitlyAnimatedWidget]s (including this [TweenAnimationBuilder]) /// all manage an internal [AnimationController] to drive the animation. If you /// want more control over the animation than just setting a target value, /// [duration], and [curve], have a look at (subclasses of) [AnimatedWidget]s. /// For those, you have to manually manage an [AnimationController] giving you /// full control over the animation. An example of an [AnimatedWidget] is the /// [AnimatedBuilder], which can be used similarly to this /// [TweenAnimationBuilder], but unlike the latter it is powered by a /// developer-managed [AnimationController]. class TweenAnimationBuilder<T extends Object?> extends ImplicitlyAnimatedWidget { /// Creates a [TweenAnimationBuilder]. /// /// The [TweenAnimationBuilder] takes full ownership of the provided [tween] /// instance and mutates it. Once a [Tween] has been passed to a /// [TweenAnimationBuilder], its properties should not be accessed or changed /// anymore to avoid interference with the [TweenAnimationBuilder]. const TweenAnimationBuilder({ super.key, required this.tween, required super.duration, super.curve, required this.builder, super.onEnd, this.child, }); /// Defines the target value for the animation. /// /// When the widget first builds, the animation runs from [Tween.begin] to /// [Tween.end], if [Tween.begin] is non-null. A new animation can be /// triggered at anytime by providing a new [Tween] with a new [Tween.end] /// value. The new animation runs from the current animation value (which may /// be [Tween.end] of the old [tween], if that animation completed) to /// [Tween.end] of the new [tween]. The [Tween.begin] value is ignored except /// for the initial animation that is triggered when the widget builds for the /// first time. /// /// Any (subclass of) [Tween] is accepted as an argument. For example, to /// animate the height or width of a [Widget], use a [Tween<double>], or /// check out the [ColorTween] to animate the color property of a [Widget]. /// /// Any [Tween] provided must have a non-null [Tween.end] value. /// /// ## Ownership /// /// The [TweenAnimationBuilder] takes full ownership of the provided [Tween] /// and it will mutate the [Tween]. Once a [Tween] instance has been passed /// to [TweenAnimationBuilder] its properties should not be accessed or /// changed anymore to avoid any interference with the /// [TweenAnimationBuilder]. If you need to change the [Tween], create a /// **new instance** with the new values. /// /// It is good practice to never store a [Tween] provided to a /// [TweenAnimationBuilder] in an instance variable to avoid accidental /// modifications of the [Tween]. final Tween<T> tween; /// Called every time the animation value changes. /// /// The current animation value is passed to the builder along with the /// [child]. The builder should build a [Widget] based on the current /// animation value and incorporate the [child] into it, if it is non-null. final ValueWidgetBuilder<T> builder; /// The child widget to pass to the builder. /// /// If a builder callback's return value contains a subtree that does not /// depend on the animation, it's more efficient to build that subtree once /// instead of rebuilding it on every animation tick. /// /// If the pre-built subtree is passed as the child parameter, the /// [TweenAnimationBuilder] will pass it back to the [builder] function so /// that it can be incorporated into the build. /// /// Using this pre-built child is entirely optional, but can improve /// performance significantly in some cases and is therefore a good practice. final Widget? child; @override ImplicitlyAnimatedWidgetState<ImplicitlyAnimatedWidget> createState() { return _TweenAnimationBuilderState<T>(); } } class _TweenAnimationBuilderState<T extends Object?> extends AnimatedWidgetBaseState<TweenAnimationBuilder<T>> { Tween<T>? _currentTween; @override void initState() { _currentTween = widget.tween; _currentTween!.begin ??= _currentTween!.end; super.initState(); if (_currentTween!.begin != _currentTween!.end) { controller.forward(); } } @override void forEachTween(TweenVisitor<dynamic> visitor) { assert( widget.tween.end != null, 'Tween provided to TweenAnimationBuilder must have non-null Tween.end value.', ); _currentTween = visitor(_currentTween, widget.tween.end, (dynamic value) { assert(false); throw StateError('Constructor will never be called because null is never provided as current tween.'); }) as Tween<T>?; } @override Widget build(BuildContext context) { return widget.builder(context, _currentTween!.evaluate(animation), widget.child); } }
flutter/packages/flutter/lib/src/widgets/tween_animation_builder.dart/0
{ "file_path": "flutter/packages/flutter/lib/src/widgets/tween_animation_builder.dart", "repo_id": "flutter", "token_count": 2416 }
656
// 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 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import '../widgets/semantics_tester.dart'; void main() { testWidgets('Verify that a tap on modal barrier dismisses an action sheet', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( const CupertinoActionSheet( title: Text('Action Sheet'), ), ), ); await tester.tap(find.text('Go')); await tester.pump(); expect(find.text('Action Sheet'), findsOneWidget); await tester.tapAt(const Offset(20.0, 20.0)); await tester.pump(); expect(find.text('Action Sheet'), findsNothing); }); testWidgets('Verify that a tap on title section (not buttons) does not dismiss an action sheet', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( const CupertinoActionSheet( title: Text('Action Sheet'), ), ), ); await tester.tap(find.text('Go')); await tester.pump(); await tester.pump(const Duration(seconds: 5)); expect(find.text('Action Sheet'), findsOneWidget); await tester.tap(find.text('Action Sheet')); await tester.pump(); expect(find.text('Action Sheet'), findsOneWidget); }); testWidgets('Action sheet destructive text style', (WidgetTester tester) async { await tester.pumpWidget( boilerplate( CupertinoActionSheetAction( isDestructiveAction: true, child: const Text('Ok'), onPressed: () { }, ), ), ); final DefaultTextStyle widget = tester.widget(find.widgetWithText(DefaultTextStyle, 'Ok')); expect(widget.style.color, const CupertinoDynamicColor.withBrightnessAndContrast( color: Color.fromARGB(255, 255, 59, 48), darkColor: Color.fromARGB(255, 255, 69, 58), highContrastColor: Color.fromARGB(255, 215, 0, 21), darkHighContrastColor: Color.fromARGB(255, 255, 105, 97), )); }); testWidgets('Action sheet dark mode', (WidgetTester tester) async { final Widget action = CupertinoActionSheetAction( child: const Text('action'), onPressed: () {}, ); Brightness brightness = Brightness.light; late StateSetter stateSetter; TextStyle actionTextStyle(String text) { return tester.widget<DefaultTextStyle>( find.descendant( of: find.widgetWithText(CupertinoActionSheetAction, text), matching: find.byType(DefaultTextStyle), ), ).style; } await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( StatefulBuilder( builder: (BuildContext context, StateSetter setter) { stateSetter = setter; return CupertinoTheme( data: CupertinoThemeData( brightness: brightness, primaryColor: const CupertinoDynamicColor.withBrightnessAndContrast( color: Color.fromARGB(255, 0, 122, 255), darkColor: Color.fromARGB(255, 10, 132, 255), highContrastColor: Color.fromARGB(255, 0, 64, 221), darkHighContrastColor: Color.fromARGB(255, 64, 156, 255), ), ), child: CupertinoActionSheet(actions: <Widget>[action]), ); }, ), ), ); await tester.tap(find.text('Go')); await tester.pump(); expect( actionTextStyle('action').color!.value, const Color.fromARGB(255, 0, 122, 255).value, ); stateSetter(() { brightness = Brightness.dark; }); await tester.pump(); expect( actionTextStyle('action').color!.value, const Color.fromARGB(255, 10, 132, 255).value, ); }); testWidgets('Action sheet default text style', (WidgetTester tester) async { await tester.pumpWidget( boilerplate( CupertinoActionSheetAction( isDefaultAction: true, child: const Text('Ok'), onPressed: () { }, ), ), ); final DefaultTextStyle widget = tester.widget(find.widgetWithText(DefaultTextStyle, 'Ok')); expect(widget.style.fontWeight, equals(FontWeight.w600)); }); testWidgets('Action sheet text styles are correct when both title and message are included', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( const CupertinoActionSheet( title: Text('Action Sheet'), message: Text('An action sheet'), ), ), ); await tester.tap(find.text('Go')); await tester.pump(); final DefaultTextStyle titleStyle = tester.firstWidget(find.widgetWithText(DefaultTextStyle, 'Action Sheet')); final DefaultTextStyle messageStyle = tester.firstWidget(find.widgetWithText(DefaultTextStyle, 'An action sheet')); expect(titleStyle.style.fontWeight, FontWeight.w600); expect(messageStyle.style.fontWeight, FontWeight.w400); }); testWidgets('Action sheet text styles are correct when title but no message is included', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( const CupertinoActionSheet( title: Text('Action Sheet'), ), ), ); await tester.tap(find.text('Go')); await tester.pump(); final DefaultTextStyle titleStyle = tester.firstWidget(find.widgetWithText(DefaultTextStyle, 'Action Sheet')); expect(titleStyle.style.fontWeight, FontWeight.w400); }); testWidgets('Action sheet text styles are correct when message but no title is included', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( const CupertinoActionSheet( message: Text('An action sheet'), ), ), ); await tester.tap(find.text('Go')); await tester.pump(); final DefaultTextStyle messageStyle = tester.firstWidget(find.widgetWithText(DefaultTextStyle, 'An action sheet')); expect(messageStyle.style.fontWeight, FontWeight.w600); }); testWidgets('Content section but no actions', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: const Text('The message.'), messageScrollController: scrollController, ), ), ); await tester.tap(find.text('Go')); await tester.pump(); await tester.pump(const Duration(seconds: 1)); // Content section should be at the bottom left of action sheet // (minus padding). expect( tester.getBottomLeft(find.byType(ClipRRect)), tester.getBottomLeft(find.byType(CupertinoActionSheet)) - const Offset(-8.0, 10.0), ); // Check that the dialog size is the same as the content section size // (minus padding). expect( tester.getSize(find.byType(ClipRRect)).height, tester.getSize(find.byType(CupertinoActionSheet)).height - 20.0, ); expect( tester.getSize(find.byType(ClipRRect)).width, tester.getSize(find.byType(CupertinoActionSheet)).width - 16.0, ); }); testWidgets('Actions but no content section', (WidgetTester tester) async { final ScrollController actionScrollController = ScrollController(); addTearDown(actionScrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], actionScrollController: actionScrollController, ), ), ); await tester.tap(find.text('Go')); await tester.pump(); await tester.pump(const Duration(seconds: 1)); final Finder finder = find.byElementPredicate( (Element element) { return element.widget.runtimeType.toString() == '_CupertinoAlertActionSection'; }, ); // Check that the title/message section is not displayed (action section is // at the top of the action sheet + padding). expect( tester.getTopLeft(finder), tester.getTopLeft(find.byType(CupertinoActionSheet)) + const Offset(8.0, 10.0), ); expect( tester.getTopLeft(find.byType(CupertinoActionSheet)) + const Offset(8.0, 10.0), tester.getTopLeft(find.widgetWithText(CupertinoActionSheetAction, 'One')), ); expect( tester.getBottomLeft(find.byType(CupertinoActionSheet)) + const Offset(8.0, -10.0), tester.getBottomLeft(find.widgetWithText(CupertinoActionSheetAction, 'Two')), ); }); testWidgets('Action section is scrollable', (WidgetTester tester) async { final ScrollController actionScrollController = ScrollController(); addTearDown(actionScrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( Builder(builder: (BuildContext context) { return MediaQuery.withClampedTextScaling( minScaleFactor: 3.0, maxScaleFactor: 3.0, child: CupertinoActionSheet( title: const Text('The title'), message: const Text('The message.'), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Three'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Four'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Five'), onPressed: () { }, ), ], actionScrollController: actionScrollController, ), ); }), ), ); await tester.tap(find.text('Go')); await tester.pump(); await tester.pump(const Duration(seconds: 1)); // Check that the action buttons list is scrollable. expect(actionScrollController.offset, 0.0); actionScrollController.jumpTo(100.0); expect(actionScrollController.offset, 100.0); actionScrollController.jumpTo(0.0); // Check that the action buttons are aligned vertically. expect(tester.getCenter(find.widgetWithText(CupertinoActionSheetAction, 'One')).dx, equals(400.0)); expect(tester.getCenter(find.widgetWithText(CupertinoActionSheetAction, 'Two')).dx, equals(400.0)); expect(tester.getCenter(find.widgetWithText(CupertinoActionSheetAction, 'Three')).dx, equals(400.0)); expect(tester.getCenter(find.widgetWithText(CupertinoActionSheetAction, 'Four')).dx, equals(400.0)); expect(tester.getCenter(find.widgetWithText(CupertinoActionSheetAction, 'Five')).dx, equals(400.0)); // Check that the action buttons are the correct heights. expect(tester.getSize(find.widgetWithText(CupertinoActionSheetAction, 'One')).height, equals(83.0)); expect(tester.getSize(find.widgetWithText(CupertinoActionSheetAction, 'Two')).height, equals(83.0)); expect(tester.getSize(find.widgetWithText(CupertinoActionSheetAction, 'Three')).height, equals(83.0)); expect(tester.getSize(find.widgetWithText(CupertinoActionSheetAction, 'Four')).height, equals(83.0)); expect(tester.getSize(find.widgetWithText(CupertinoActionSheetAction, 'Five')).height, equals(83.0)); }); testWidgets('Content section is scrollable', (WidgetTester tester) async { final ScrollController messageScrollController = ScrollController(); addTearDown(messageScrollController.dispose); late double screenHeight; await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( Builder(builder: (BuildContext context) { screenHeight = MediaQuery.sizeOf(context).height; return MediaQuery.withClampedTextScaling( minScaleFactor: 3.0, maxScaleFactor: 3.0, child: CupertinoActionSheet( title: const Text('The title'), message: Text('Very long content' * 200), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], messageScrollController: messageScrollController, ), ); }), ), ); await tester.tap(find.text('Go')); await tester.pump(); expect(messageScrollController.offset, 0.0); messageScrollController.jumpTo(100.0); expect(messageScrollController.offset, 100.0); // Set the scroll position back to zero. messageScrollController.jumpTo(0.0); // Expect the action sheet to take all available height. expect(tester.getSize(find.byType(CupertinoActionSheet)).height, screenHeight); }); testWidgets('CupertinoActionSheet scrollbars controllers should be different', (WidgetTester tester) async { // https://github.com/flutter/flutter/pull/81278 await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: Text('Very long content' * 200), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), ], ) ), ); await tester.tap(find.text('Go')); await tester.pump(); final List<CupertinoScrollbar> scrollbars = find.descendant( of: find.byType(CupertinoActionSheet), matching: find.byType(CupertinoScrollbar), ).evaluate().map((Element e) => e.widget as CupertinoScrollbar).toList(); expect(scrollbars.length, 2); expect(scrollbars[0].controller != scrollbars[1].controller, isTrue); }); testWidgets('Tap on button calls onPressed', (WidgetTester tester) async { bool wasPressed = false; await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( Builder(builder: (BuildContext context) { return CupertinoActionSheet( actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { wasPressed = true; Navigator.pop(context); }, ), ], ); }), ), ); await tester.tap(find.text('Go')); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(wasPressed, isFalse); await tester.tap(find.text('One')); expect(wasPressed, isTrue); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(find.text('One'), findsNothing); }); testWidgets('Action sheet width is correct when given infinite horizontal space', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( Row( children: <Widget>[ CupertinoActionSheet( actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], ), ], ), ), ); await tester.tap(find.text('Go')); await tester.pump(); expect(tester.getSize(find.byType(CupertinoActionSheet)).width, 600.0); }); testWidgets('Action sheet height is correct when given infinite vertical space', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( Column( children: <Widget>[ CupertinoActionSheet( actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], ), ], ), ), ); await tester.tap(find.text('Go')); await tester.pump(); expect(tester.getSize(find.byType(CupertinoActionSheet)).height, moreOrLessEquals(132.3)); }); testWidgets('1 action button with cancel button', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: Text('Very long content' * 200), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), ], cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), ); await tester.tap(find.text('Go')); await tester.pump(); // Action section is size of one action button. expect(findScrollableActionsSectionRenderBox(tester).size.height, 56.0); }); testWidgets('2 action buttons with cancel button', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: Text('Very long content' * 200), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), ); await tester.tap(find.text('Go')); await tester.pump(); expect(findScrollableActionsSectionRenderBox(tester).size.height, moreOrLessEquals(112.3)); }); testWidgets('3 action buttons with cancel button', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: Text('Very long content' * 200), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Three'), onPressed: () { }, ), ], cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), ); await tester.tap(find.text('Go')); await tester.pump(); expect(findScrollableActionsSectionRenderBox(tester).size.height, moreOrLessEquals(168.6)); }); testWidgets('4+ action buttons with cancel button', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: Text('Very long content' * 200), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Three'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Four'), onPressed: () { }, ), ], cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), ); await tester.tap(find.text('Go')); await tester.pump(); expect(findScrollableActionsSectionRenderBox(tester).size.height, moreOrLessEquals(84.3)); }); testWidgets('1 action button without cancel button', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: Text('Very long content' * 200), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), ], ), ), ); await tester.tap(find.text('Go')); await tester.pump(); expect(findScrollableActionsSectionRenderBox(tester).size.height, 56.0); }); testWidgets('2+ action buttons without cancel button', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: Text('Very long content' * 200), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], ), ), ); await tester.tap(find.text('Go')); await tester.pump(); expect(findScrollableActionsSectionRenderBox(tester).size.height, moreOrLessEquals(84.3)); }); testWidgets('Action sheet with just cancel button is correct', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), ); await tester.tap(find.text('Go')); await tester.pump(); // Height should be cancel button height + padding expect(tester.getSize(find.byType(CupertinoActionSheet)).height, 76.0); expect(tester.getSize(find.byType(CupertinoActionSheet)).width, 600.0); }); testWidgets('Cancel button tap calls onPressed', (WidgetTester tester) async { bool wasPressed = false; await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( Builder(builder: (BuildContext context) { return CupertinoActionSheet( cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { wasPressed = true; Navigator.pop(context); }, ), ); }), ), ); await tester.tap(find.text('Go')); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(wasPressed, isFalse); await tester.tap(find.text('Cancel')); expect(wasPressed, isTrue); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(find.text('Cancel'), findsNothing); }); testWidgets('Layout is correct when cancel button is present', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: const Text('The message'), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), ); await tester.tap(find.text('Go')); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(tester.getBottomLeft(find.widgetWithText(CupertinoActionSheetAction, 'Cancel')).dy, 590.0); expect( tester.getBottomLeft(find.widgetWithText(CupertinoActionSheetAction, 'One')).dy, moreOrLessEquals(469.7), ); expect(tester.getBottomLeft(find.widgetWithText(CupertinoActionSheetAction, 'Two')).dy, 526.0); }); testWidgets('Enter/exit animation is correct', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: const Text('The message'), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), ); // Enter animation await tester.tap(find.text('Go')); await tester.pump(); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, 600.0); await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(483.9, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(398.6, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(365.3, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(354.8, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(350.7, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(349.4, epsilon: 0.1)); // Action sheet has reached final height await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(349.4, epsilon: 0.1)); // Exit animation await tester.tapAt(const Offset(20.0, 20.0)); await tester.pump(); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(349.4, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(465.5, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(550.8, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(584.1, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(594.6, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(598.7, epsilon: 0.1)); // Action sheet has disappeared await tester.pump(const Duration(milliseconds: 60)); expect(find.byType(CupertinoActionSheet), findsNothing); }); testWidgets('Modal barrier is pressed during transition', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: const Text('The message'), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), ); // Enter animation await tester.tap(find.text('Go')); await tester.pump(); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, 600.0); await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(483.92863239836686, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(398.5571539306641, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(365.3034101784229, epsilon: 0.1)); // Exit animation await tester.tapAt(const Offset(20.0, 20.0)); await tester.pump(const Duration(milliseconds: 60)); await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(398.5571539306641, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(483.92863239836686, epsilon: 0.1)); await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, 600.0); // Action sheet has disappeared await tester.pump(const Duration(milliseconds: 60)); expect(find.byType(CupertinoActionSheet), findsNothing); }); testWidgets('Action sheet semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: const Text('The message'), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), ); await tester.tap(find.text('Go')); await tester.pumpAndSettle(); expect( semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.scopesRoute, SemanticsFlag.namesRoute, ], label: 'Alert', children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.hasImplicitScrolling, ], children: <TestSemantics>[ TestSemantics( label: 'The title', ), TestSemantics( label: 'The message', ), ], ), TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.hasImplicitScrolling, ], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.isButton, ], actions: <SemanticsAction>[ SemanticsAction.tap, ], label: 'One', ), TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.isButton, ], actions: <SemanticsAction>[ SemanticsAction.tap, ], label: 'Two', ), ], ), TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.isButton, ], actions: <SemanticsAction>[ SemanticsAction.tap, ], label: 'Cancel', ), ], ), ], ), ], ), ], ), ignoreId: true, ignoreRect: true, ignoreTransform: true, ), ); semantics.dispose(); }); testWidgets('Conflicting scrollbars are not applied by ScrollBehavior to CupertinoActionSheet', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/83819 final ScrollController actionScrollController = ScrollController(); addTearDown(actionScrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( Builder(builder: (BuildContext context) { return MediaQuery.withClampedTextScaling( minScaleFactor: 3.0, maxScaleFactor: 3.0, child: CupertinoActionSheet( title: const Text('The title'), message: const Text('The message.'), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], actionScrollController: actionScrollController, ), ); }), ), ); await tester.tap(find.text('Go')); await tester.pump(); // The inherited ScrollBehavior should not apply Scrollbars since they are // already built in to the widget. expect(find.byType(Scrollbar), findsNothing); expect(find.byType(RawScrollbar), findsNothing); // Built in CupertinoScrollbars should only number 2: one for the actions, // one for the content. expect(find.byType(CupertinoScrollbar), findsNWidgets(2)); }, variant: TargetPlatformVariant.all()); testWidgets('Hovering over Cupertino action sheet action updates cursor to clickable on Web', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: const Text('Message'), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), ], ) ), ); await tester.tap(find.text('Go')); await tester.pump(); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: const Offset(10, 10)); await tester.pumpAndSettle(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); final Offset actionSheetAction = tester.getCenter(find.text('One')); await gesture.moveTo(actionSheetAction); await tester.pumpAndSettle(); expect( RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), kIsWeb ? SystemMouseCursors.click : SystemMouseCursors.basic, ); }); } RenderBox findScrollableActionsSectionRenderBox(WidgetTester tester) { final RenderObject actionsSection = tester.renderObject( find.byElementPredicate((Element element) { return element.widget.runtimeType.toString() == '_CupertinoAlertActionSection'; }), ); assert(actionsSection is RenderBox); return actionsSection as RenderBox; } Widget createAppWithButtonThatLaunchesActionSheet(Widget actionSheet) { return CupertinoApp( home: Center( child: Builder(builder: (BuildContext context) { return CupertinoButton( onPressed: () { showCupertinoModalPopup<void>( context: context, builder: (BuildContext context) { return actionSheet; }, ); }, child: const Text('Go'), ); }), ), ); } Widget boilerplate(Widget child) { return Directionality( textDirection: TextDirection.ltr, child: child, ); }
flutter/packages/flutter/test/cupertino/action_sheet_test.dart/0
{ "file_path": "flutter/packages/flutter/test/cupertino/action_sheet_test.dart", "repo_id": "flutter", "token_count": 17605 }
657
// 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 'package:flutter/cupertino.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Shows header', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( header: const Text('Header'), children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), ); expect(find.text('Header'), findsOneWidget); }); testWidgets('Shows footer', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( footer: const Text('Footer'), children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), ); expect(find.text('Footer'), findsOneWidget); }); testWidgets('Shows long dividers in edge-to-edge section part 1', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), ); // Since the children list is reconstructed with dividers in it, the column // retrieved should have 3 items for an input [children] param with 1 child. final Column childrenColumn = tester.widget(find.byType(Column).at(1)); expect(childrenColumn.children.length, 3); }); testWidgets('Shows long dividers in edge-to-edge section part 2', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( children: <Widget>[ CupertinoTextFormFieldRow(), CupertinoTextFormFieldRow(), ], ), ), ), ); // Since the children list is reconstructed with dividers in it, the column // retrieved should have 5 items for an input [children] param with 2 // children. Two long dividers, two rows, and one short divider. final Column childrenColumn = tester.widget(find.byType(Column).at(1)); expect(childrenColumn.children.length, 5); }); testWidgets('Does not show long dividers in insetGrouped section part 1', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection.insetGrouped( children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), ); // Since the children list is reconstructed without long dividers in it, the // column retrieved should have 1 item for an input [children] param with 1 // child. final Column childrenColumn = tester.widget(find.byType(Column).at(1)); expect(childrenColumn.children.length, 1); }); testWidgets('Does not show long dividers in insetGrouped section part 2', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( restorationScopeId: 'App', home: Center( child: CupertinoFormSection.insetGrouped( children: <Widget>[ CupertinoTextFormFieldRow(), CupertinoTextFormFieldRow(), ], ), ), ), ); // Since the children list is reconstructed with short dividers in it, the // column retrieved should have 3 items for an input [children] param with 2 // children. Two long dividers, two rows, and one short divider. final Column childrenColumn = tester.widget(find.byType(Column).at(1)); expect(childrenColumn.children.length, 3); }); testWidgets('Sets background color for section', (WidgetTester tester) async { const Color backgroundColor = CupertinoColors.systemBlue; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: CupertinoFormSection( backgroundColor: backgroundColor, children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), ); final DecoratedBox decoratedBox = tester.widget(find.byType(DecoratedBox).first); final BoxDecoration boxDecoration = decoratedBox.decoration as BoxDecoration; expect(boxDecoration.color, backgroundColor); }); testWidgets('Setting clipBehavior clips children section', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( clipBehavior: Clip.antiAlias, children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), ); expect(find.byType(ClipRRect), findsOneWidget); }); testWidgets('Not setting clipBehavior does not produce a RenderClipRRect object', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), ); final Iterable<RenderClipRRect> renderClips = tester.allRenderObjects.whereType<RenderClipRRect>(); expect(renderClips, isEmpty); }); testWidgets('Does not double up padding on header', (WidgetTester tester) async { const Widget header = Text('Header'); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( header: header, children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), ); expect(tester.getTopLeft(find.byWidget(header)), const Offset(20, 22)); }); testWidgets('Does not double up padding on footer', (WidgetTester tester) async { const Widget footer = Text('Footer'); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( footer: footer, children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), ); expect(tester.getTopLeft(find.byWidget(footer)), offsetMoreOrLessEquals(const Offset(20, 65), epsilon: 1)); }); testWidgets('Sets custom margin', (WidgetTester tester) async { final Widget child = CupertinoTextFormFieldRow(); const double margin = 35; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( margin: const EdgeInsets.all(margin), children: <Widget>[child], ), ), ), ); expect(tester.getTopLeft(find.byWidget(child)), offsetMoreOrLessEquals(const Offset(margin, 22 + margin), epsilon: 1)); }); }
flutter/packages/flutter/test/cupertino/form_section_test.dart/0
{ "file_path": "flutter/packages/flutter/test/cupertino/form_section_test.dart", "repo_id": "flutter", "token_count": 2799 }
658
// 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 'package:flutter/cupertino.dart'; import 'package:flutter_test/flutter_test.dart'; const Color _kScrollbarColor = Color(0x59000000); // The `y` offset has to be larger than `ScrollDragController._bigThresholdBreakDistance` // to prevent [motionStartDistanceThreshold] from affecting the actual drag distance. const Offset _kGestureOffset = Offset(0, -25); const Radius _kScrollbarRadius = Radius.circular(1.5); void main() { testWidgets('Paints iOS spec', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: MediaQueryData(), child: CupertinoScrollbar( child: SingleChildScrollView( child: SizedBox(width: 4000.0, height: 4000.0), ), ), ), ), ); expect(find.byType(CupertinoScrollbar), isNot(paints..rrect())); final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(SingleChildScrollView))); await gesture.moveBy(_kGestureOffset); // Move back to original position. await gesture.moveBy(Offset.zero.translate(-_kGestureOffset.dx, -_kGestureOffset.dy)); await tester.pump(); await tester.pump(const Duration(milliseconds: 500)); expect(find.byType(CupertinoScrollbar), paints..rrect( color: _kScrollbarColor, rrect: RRect.fromRectAndRadius( const Rect.fromLTWH( 800.0 - 3 - 3, // Screen width - margin - thickness. 3.0, // Initial position is the top margin. 3, // Thickness. // Fraction in viewport * scrollbar height - top, bottom margin. 600.0 / 4000.0 * (600.0 - 2 * 3), ), _kScrollbarRadius, ), )); }); testWidgets('Paints iOS spec with nav bar', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: MediaQuery( data: const MediaQueryData( padding: EdgeInsets.fromLTRB(0, 20, 0, 34), ), child: CupertinoPageScaffold( navigationBar: const CupertinoNavigationBar( middle: Text('Title'), backgroundColor: Color(0x11111111), ), child: CupertinoScrollbar( child: ListView( children: const <Widget>[SizedBox(width: 4000, height: 4000)], ), ), ), ), ), ); final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(ListView))); await gesture.moveBy(_kGestureOffset); // Move back to original position. await gesture.moveBy(Offset(-_kGestureOffset.dx, -_kGestureOffset.dy)); await tester.pump(); await tester.pump(const Duration(milliseconds: 500)); expect(find.byType(CupertinoScrollbar), paints..rrect( color: _kScrollbarColor, rrect: RRect.fromRectAndRadius( const Rect.fromLTWH( 800.0 - 3 - 3, // Screen width - margin - thickness. 44 + 20 + 3.0, // nav bar height + top margin 3, // Thickness. // Fraction visible * (viewport size - padding - margin) // where Fraction visible = (viewport size - padding) / content size (600.0 - 34 - 44 - 20) / 4000.0 * (600.0 - 2 * 3 - 34 - 44 - 20), ), _kScrollbarRadius, ), )); }); testWidgets("should not paint when there isn't enough space", (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: MediaQuery( data: const MediaQueryData( padding: EdgeInsets.fromLTRB(0, 20, 0, 34), ), child: CupertinoPageScaffold( navigationBar: const CupertinoNavigationBar( middle: Text('Title'), backgroundColor: Color(0x11111111), ), child: CupertinoScrollbar( child: ListView( physics: const AlwaysScrollableScrollPhysics(parent: BouncingScrollPhysics()), children: const <Widget> [SizedBox(width: 10, height: 10)], ), ), ), ), ), ); final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(ListView))); await gesture.moveBy(_kGestureOffset); // Move back to original position. await gesture.moveBy(Offset(-_kGestureOffset.dx, -_kGestureOffset.dy)); await tester.pump(); await tester.pump(const Duration(milliseconds: 500)); expect(find.byType(CupertinoScrollbar), isNot(paints..rrect())); // The scrollbar should not appear even when overscrolled. final TestGesture overscrollGesture = await tester.startGesture(tester.getCenter(find.byType(ListView))); await overscrollGesture.moveBy(_kGestureOffset); await tester.pump(); await tester.pump(const Duration(milliseconds: 500)); expect(find.byType(CupertinoScrollbar), isNot(paints..rrect())); }); }
flutter/packages/flutter/test/cupertino/scrollbar_paint_test.dart/0
{ "file_path": "flutter/packages/flutter/test/cupertino/scrollbar_paint_test.dart", "repo_id": "flutter", "token_count": 2190 }
659
// 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. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import '../widgets/editable_text_utils.dart' show textOffsetToPosition; // These constants are copied from cupertino/text_selection_toolbar.dart. const double _kArrowScreenPadding = 26.0; const double _kToolbarContentDistance = 8.0; const Size _kToolbarArrowSize = Size(14.0, 7.0); // A custom text selection menu that just displays a single custom button. class _CustomCupertinoTextSelectionControls extends CupertinoTextSelectionControls { @override Widget buildToolbar( BuildContext context, Rect globalEditableRegion, double textLineHeight, Offset selectionMidpoint, List<TextSelectionPoint> endpoints, TextSelectionDelegate delegate, ValueListenable<ClipboardStatus>? clipboardStatus, Offset? lastSecondaryTapDownPosition, ) { final EdgeInsets mediaQueryPadding = MediaQuery.paddingOf(context); final double anchorX = (selectionMidpoint.dx + globalEditableRegion.left).clamp( _kArrowScreenPadding + mediaQueryPadding.left, MediaQuery.sizeOf(context).width - mediaQueryPadding.right - _kArrowScreenPadding, ); final Offset anchorAbove = Offset( anchorX, endpoints.first.point.dy - textLineHeight + globalEditableRegion.top, ); final Offset anchorBelow = Offset( anchorX, endpoints.last.point.dy + globalEditableRegion.top, ); return CupertinoTextSelectionToolbar( anchorAbove: anchorAbove, anchorBelow: anchorBelow, children: <Widget>[ CupertinoTextSelectionToolbarButton( onPressed: () {}, child: const Text('Custom button'), ), ], ); } } class TestBox extends SizedBox { const TestBox({super.key}) : super(width: itemWidth, height: itemHeight); static const double itemHeight = 44.0; static const double itemWidth = 100.0; } const CupertinoDynamicColor _kToolbarTextColor = CupertinoDynamicColor.withBrightness( color: CupertinoColors.black, darkColor: CupertinoColors.white, ); void main() { TestWidgetsFlutterBinding.ensureInitialized(); // Find by a runtimeType String, including private types. Finder findPrivate(String type) { return find.descendant( of: find.byType(CupertinoApp), matching: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == type), ); } // Finding CupertinoTextSelectionToolbar won't give you the position as the user sees // it because it's a full-sized Stack at the top level. This method finds the // visible part of the toolbar for use in measurements. Finder findToolbar() => findPrivate('_CupertinoTextSelectionToolbarContent'); // Check if the middle point of the chevron is pointing left or right. // // Offset.dx: a right or left margin (_kToolbarChevronSize / 4 => 2.5) to center the icon horizontally // Offset.dy: always in the exact vertical center (_kToolbarChevronSize / 2 => 5) PaintPattern overflowNextPaintPattern() => paints ..line(p1: const Offset(2.5, 0), p2: const Offset(7.5, 5)) ..line(p1: const Offset(7.5, 5), p2: const Offset(2.5, 10)); PaintPattern overflowBackPaintPattern() => paints ..line(p1: const Offset(7.5, 0), p2: const Offset(2.5, 5)) ..line(p1: const Offset(2.5, 5), p2: const Offset(7.5, 10)); Finder findOverflowNextButton() { return find.byWidgetPredicate((Widget widget) => widget is CustomPaint && '${widget.painter?.runtimeType}' == '_RightCupertinoChevronPainter', ); } Finder findOverflowBackButton() { return find.byWidgetPredicate((Widget widget) => widget is CustomPaint && '${widget.painter?.runtimeType}' == '_LeftCupertinoChevronPainter', ); } testWidgets('chevrons point to the correct side', (WidgetTester tester) async { // Add enough TestBoxes to need 3 pages. final List<Widget> children = List<Widget>.generate(15, (int i) => const TestBox()); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextSelectionToolbar( anchorAbove: const Offset(50.0, 100.0), anchorBelow: const Offset(50.0, 200.0), children: children, ), ), ), ); expect(findOverflowBackButton(), findsNothing); expect(findOverflowNextButton(), findsOneWidget); expect(findOverflowNextButton(), overflowNextPaintPattern()); // Tap the overflow next button to show the next page of children. await tester.tapAt(tester.getCenter(findOverflowNextButton())); await tester.pumpAndSettle(); expect(findOverflowBackButton(), findsOneWidget); expect(findOverflowNextButton(), findsOneWidget); expect(findOverflowBackButton(), overflowBackPaintPattern()); expect(findOverflowNextButton(), overflowNextPaintPattern()); // Tap the overflow next button to show the last page of children. await tester.tapAt(tester.getCenter(findOverflowNextButton())); await tester.pumpAndSettle(); expect(findOverflowBackButton(), findsOneWidget); expect(findOverflowNextButton(), findsNothing); expect(findOverflowBackButton(), overflowBackPaintPattern()); }, skip: kIsWeb); // Path.combine is not implemented in the HTML backend https://github.com/flutter/flutter/issues/44572 testWidgets('paginates children if they overflow', (WidgetTester tester) async { late StateSetter setState; final List<Widget> children = List<Widget>.generate(7, (int i) => const TestBox()); await tester.pumpWidget( CupertinoApp( home: Center( child: StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; return CupertinoTextSelectionToolbar( anchorAbove: const Offset(50.0, 100.0), anchorBelow: const Offset(50.0, 200.0), children: children, ); }, ), ), ), ); // All children fit on the screen, so they are all rendered. expect(find.byType(TestBox), findsNWidgets(children.length)); expect(findOverflowNextButton(), findsNothing); expect(findOverflowBackButton(), findsNothing); // Adding one more child makes the children overflow. setState(() { children.add( const TestBox(), ); }); await tester.pumpAndSettle(); expect(find.byType(TestBox), findsNWidgets(children.length - 1)); expect(findOverflowNextButton(), findsOneWidget); expect(findOverflowBackButton(), findsNothing); // Tap the overflow next button to show the next page of children. // The next button is hidden as there's no next page. await tester.tapAt(tester.getCenter(findOverflowNextButton())); await tester.pumpAndSettle(); expect(find.byType(TestBox), findsNWidgets(1)); expect(findOverflowNextButton(), findsNothing); expect(findOverflowBackButton(), findsOneWidget); // Tap the overflow back button to go back to the first page. await tester.tapAt(tester.getCenter(findOverflowBackButton())); await tester.pumpAndSettle(); expect(find.byType(TestBox), findsNWidgets(7)); expect(findOverflowNextButton(), findsOneWidget); expect(findOverflowBackButton(), findsNothing); // Adding 7 more children overflows onto a third page. setState(() { children.add(const TestBox()); children.add(const TestBox()); children.add(const TestBox()); children.add(const TestBox()); children.add(const TestBox()); children.add(const TestBox()); }); await tester.pumpAndSettle(); expect(find.byType(TestBox), findsNWidgets(7)); expect(findOverflowNextButton(), findsOneWidget); expect(findOverflowBackButton(), findsNothing); // Tap the overflow next button to show the second page of children. await tester.tapAt(tester.getCenter(findOverflowNextButton())); await tester.pumpAndSettle(); // With the back button, only six children fit on this page. expect(find.byType(TestBox), findsNWidgets(6)); expect(findOverflowNextButton(), findsOneWidget); expect(findOverflowBackButton(), findsOneWidget); // Tap the overflow next button again to show the third page of children. await tester.tapAt(tester.getCenter(findOverflowNextButton())); await tester.pumpAndSettle(); expect(find.byType(TestBox), findsNWidgets(1)); expect(findOverflowNextButton(), findsNothing); expect(findOverflowBackButton(), findsOneWidget); // Tap the overflow back button to go back to the second page. await tester.tapAt(tester.getCenter(findOverflowBackButton())); await tester.pumpAndSettle(); expect(find.byType(TestBox), findsNWidgets(6)); expect(findOverflowNextButton(), findsOneWidget); expect(findOverflowBackButton(), findsOneWidget); // Tap the overflow back button to go back to the first page. await tester.tapAt(tester.getCenter(findOverflowBackButton())); await tester.pumpAndSettle(); expect(find.byType(TestBox), findsNWidgets(7)); expect(findOverflowNextButton(), findsOneWidget); expect(findOverflowBackButton(), findsNothing); }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web. testWidgets('does not paginate if children fit with zero margin', (WidgetTester tester) async { final List<Widget> children = List<Widget>.generate(7, (int i) => const TestBox()); final double spacerWidth = 1.0 / tester.view.devicePixelRatio; final double dividerWidth = 1.0 / tester.view.devicePixelRatio; const double borderRadius = 8.0; // Should match _kToolbarBorderRadius final double width = 7 * TestBox.itemWidth + 6 * (dividerWidth + 2 * spacerWidth) + 2 * borderRadius; await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( width: width, child: CupertinoTextSelectionToolbar( anchorAbove: const Offset(50.0, 100.0), anchorBelow: const Offset(50.0, 200.0), children: children, ), ), ), ), ); // All children fit on the screen, so they are all rendered. expect(find.byType(TestBox), findsNWidgets(children.length)); expect(findOverflowNextButton(), findsNothing); expect(findOverflowBackButton(), findsNothing); }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web. testWidgets('correctly sizes large toolbar buttons', (WidgetTester tester) async { final GlobalKey firstBoxKey = GlobalKey(); final GlobalKey secondBoxKey = GlobalKey(); final GlobalKey thirdBoxKey = GlobalKey(); final GlobalKey fourthBoxKey = GlobalKey(); await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( width: 420, child: CupertinoTextSelectionToolbar( anchorAbove: const Offset(50.0, 100.0), anchorBelow: const Offset(50.0, 200.0), children: <Widget>[ SizedBox(key: firstBoxKey, width: 100), SizedBox(key: secondBoxKey, width: 300), SizedBox(key: thirdBoxKey, width: 100), SizedBox(key: fourthBoxKey, width: 100), ], ), ), ), ), ); // The first page isn't wide enough to show the second button. expect(find.byKey(firstBoxKey), findsOneWidget); expect(find.byKey(secondBoxKey), findsNothing); expect(find.byKey(thirdBoxKey), findsNothing); expect(find.byKey(fourthBoxKey), findsNothing); // Show the next page. await tester.tapAt(tester.getCenter(findOverflowNextButton())); await tester.pumpAndSettle(); // The second page should show only the second button. expect(find.byKey(firstBoxKey), findsNothing); expect(find.byKey(secondBoxKey), findsOneWidget); expect(find.byKey(thirdBoxKey), findsNothing); expect(find.byKey(fourthBoxKey), findsNothing); // The button's width shouldn't be limited by the first page's width. expect(tester.getSize(find.byKey(secondBoxKey)).width, 300); // Show the next page. await tester.tapAt(tester.getCenter(findOverflowNextButton())); await tester.pumpAndSettle(); // The third page should show the last two items. expect(find.byKey(firstBoxKey), findsNothing); expect(find.byKey(secondBoxKey), findsNothing); expect(find.byKey(thirdBoxKey), findsOneWidget); expect(find.byKey(fourthBoxKey), findsOneWidget); }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web. testWidgets('positions itself at anchorAbove if it fits', (WidgetTester tester) async { late StateSetter setState; const double height = 50.0; const double anchorBelowY = 500.0; double anchorAboveY = 0.0; const double paddingAbove = 12.0; await tester.pumpWidget( CupertinoApp( home: Center( child: StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; final MediaQueryData data = MediaQuery.of(context); // Add some custom vertical padding to make this test more strict. // By default in the testing environment, _kToolbarContentDistance // and the built-in padding from CupertinoApp can end up canceling // each other out. return MediaQuery( data: data.copyWith( padding: data.viewPadding.copyWith( top: paddingAbove, ), ), child: CupertinoTextSelectionToolbar( anchorAbove: Offset(50.0, anchorAboveY), anchorBelow: const Offset(50.0, anchorBelowY), children: <Widget>[ Container(color: const Color(0xffff0000), width: 50.0, height: height), Container(color: const Color(0xff00ff00), width: 50.0, height: height), Container(color: const Color(0xff0000ff), width: 50.0, height: height), ], ), ); }, ), ), ), ); // When the toolbar doesn't fit above aboveAnchor, it positions itself below // belowAnchor. double toolbarY = tester.getTopLeft(findToolbar()).dy; expect(toolbarY, equals(anchorBelowY + _kToolbarContentDistance)); expect(find.byType(CustomSingleChildLayout), findsOneWidget); final CustomSingleChildLayout layout = tester.widget(find.byType(CustomSingleChildLayout)); final TextSelectionToolbarLayoutDelegate delegate = layout.delegate as TextSelectionToolbarLayoutDelegate; expect(delegate.anchorBelow.dy, anchorBelowY - paddingAbove); // Even when it barely doesn't fit. setState(() { anchorAboveY = 70.0; }); await tester.pump(); toolbarY = tester.getTopLeft(findToolbar()).dy; expect(toolbarY, equals(anchorBelowY + _kToolbarContentDistance)); // When it does fit above aboveAnchor, it positions itself there. setState(() { anchorAboveY = 80.0; }); await tester.pump(); toolbarY = tester.getTopLeft(findToolbar()).dy; expect(toolbarY, equals(anchorAboveY - height + _kToolbarArrowSize.height - _kToolbarContentDistance)); }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web. testWidgets('can create and use a custom toolbar', (WidgetTester tester) async { final TextEditingController controller = TextEditingController( text: 'Select me custom menu', ); addTearDown(controller.dispose); await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoTextField( controller: controller, selectionControls: _CustomCupertinoTextSelectionControls(), ), ), ), ); // The selection menu is not initially shown. expect(find.text('Custom button'), findsNothing); // Long press on "custom" to select it. final Offset customPos = textOffsetToPosition(tester, 11); final TestGesture gesture = await tester.startGesture(customPos, pointer: 7); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); // The custom selection menu is shown. expect(find.text('Custom button'), findsOneWidget); expect(find.text('Cut'), findsNothing); expect(find.text('Copy'), findsNothing); expect(find.text('Paste'), findsNothing); expect(find.text('Select all'), findsNothing); }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web. for (final Brightness? themeBrightness in <Brightness?>[...Brightness.values, null]) { for (final Brightness? mediaBrightness in <Brightness?>[...Brightness.values, null]) { testWidgets('draws dark buttons in dark mode and light button in light mode when theme is $themeBrightness and MediaQuery is $mediaBrightness', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( theme: CupertinoThemeData( brightness: themeBrightness, ), home: Center( child: Builder( builder: (BuildContext context) { return MediaQuery( data: MediaQuery.of(context).copyWith(platformBrightness: mediaBrightness), child: CupertinoTextSelectionToolbar( anchorAbove: const Offset(100.0, 0.0), anchorBelow: const Offset(100.0, 0.0), children: <Widget>[ CupertinoTextSelectionToolbarButton.text( onPressed: () {}, text: 'Button', ), ], ), ); }, ), ), ), ); final Finder buttonFinder = find.byType(CupertinoButton); expect(buttonFinder, findsOneWidget); final Finder textFinder = find.descendant( of: find.byType(CupertinoButton), matching: find.byType(Text) ); expect(textFinder, findsOneWidget); final Text text = tester.widget(textFinder); // Theme brightness is preferred, otherwise MediaQuery brightness is // used. If both are null, defaults to light. final Brightness effectiveBrightness = themeBrightness ?? mediaBrightness ?? Brightness.light; expect( text.style!.color!.value, effectiveBrightness == Brightness.dark ? _kToolbarTextColor.darkColor.value : _kToolbarTextColor.color.value, ); }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web. } } testWidgets('draws a shadow below the toolbar in light mode', (WidgetTester tester) async { late StateSetter setState; const double height = 50.0; double anchorAboveY = 0.0; await tester.pumpWidget( CupertinoApp( theme: const CupertinoThemeData( brightness: Brightness.light, ), home: Center( child: StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; final MediaQueryData data = MediaQuery.of(context); // Add some custom vertical padding to make this test more strict. // By default in the testing environment, _kToolbarContentDistance // and the built-in padding from CupertinoApp can end up canceling // each other out. return MediaQuery( data: data.copyWith( padding: data.viewPadding.copyWith( top: 12.0, ), ), child: CupertinoTextSelectionToolbar( anchorAbove: Offset(50.0, anchorAboveY), anchorBelow: const Offset(50.0, 500.0), children: <Widget>[ Container(color: const Color(0xffff0000), width: 50.0, height: height), Container(color: const Color(0xff00ff00), width: 50.0, height: height), Container(color: const Color(0xff0000ff), width: 50.0, height: height), ], ), ); }, ), ), ), ); final double dividerWidth = 1.0 / tester.view.devicePixelRatio; expect( find.byType(CupertinoTextSelectionToolbar), paints..rrect( rrect: RRect.fromLTRBR(8.0, 515.0, 158.0 + 2 * dividerWidth, 558.0, const Radius.circular(8.0)), color: const Color(0x33000000), ), ); // When the toolbar is above the content, the shadow sits around the arrow // with no offset. setState(() { anchorAboveY = 80.0; }); await tester.pump(); expect( find.byType(CupertinoTextSelectionToolbar), paints..rrect( rrect: RRect.fromLTRBR(8.0, 29.0, 158.0 + 2 * dividerWidth, 72.0, const Radius.circular(8.0)), color: const Color(0x33000000), ), ); }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web. testWidgets('Basic golden tests', (WidgetTester tester) async { final Key key = UniqueKey(); Widget buildToolbar(Brightness brightness, Offset offset) { final Widget toolbar = CupertinoTextSelectionToolbar( anchorAbove: offset, anchorBelow: offset, children: <Widget>[ CupertinoTextSelectionToolbarButton.text(onPressed: () {}, text: 'Lorem ipsum'), CupertinoTextSelectionToolbarButton.text(onPressed: () {}, text: 'dolor sit amet'), CupertinoTextSelectionToolbarButton.text(onPressed: () {}, text: 'Lorem ipsum \ndolor sit amet'), CupertinoTextSelectionToolbarButton.buttonItem(buttonItem: ContextMenuButtonItem(onPressed: () {}, type: ContextMenuButtonType.copy)), ], ); return CupertinoApp( theme: CupertinoThemeData(brightness: brightness), home: Center( child: SizedBox( height: 200, child: RepaintBoundary(key: key, child: toolbar), ), ), ); } // The String describes the location of the toolbar in relation to the // content the arrow points to. const List<(String, Offset)> toolbarLocation = <(String, Offset)>[ ('BottomRight', Offset.zero), ('BottomLeft', Offset(100000, 0)), ('TopRight', Offset(0, 100)), ('TopLeft', Offset(100000, 100)), ]; debugDisableShadows = false; addTearDown(() => debugDisableShadows = true); for (final Brightness brightness in Brightness.values) { for (final (String location, Offset offset) in toolbarLocation) { await tester.pumpWidget(buildToolbar(brightness, offset)); await expectLater( find.byKey(key), matchesGoldenFile('cupertino_selection_toolbar.$location.$brightness.png'), ); } } debugDisableShadows = true; }, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web. }
flutter/packages/flutter/test/cupertino/text_selection_toolbar_test.dart/0
{ "file_path": "flutter/packages/flutter/test/cupertino/text_selection_toolbar_test.dart", "repo_id": "flutter", "token_count": 9332 }
660
// 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 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; int yieldCount = 0; Iterable<int> range(int start, int end) sync* { assert(yieldCount == 0); for (int index = start; index <= end; index += 1) { yieldCount += 1; yield index; } } void main() { setUp(() { yieldCount = 0; }); test('The Caching Iterable: length caches', () { final Iterable<int> i = CachingIterable<int>(range(1, 5).iterator); expect(yieldCount, equals(0)); expect(i.length, equals(5)); expect(yieldCount, equals(5)); expect(i.length, equals(5)); expect(yieldCount, equals(5)); expect(i.last, equals(5)); expect(yieldCount, equals(5)); expect(i, equals(<int>[1, 2, 3, 4, 5])); expect(yieldCount, equals(5)); }); test('The Caching Iterable: laziness', () { final Iterable<int> i = CachingIterable<int>(range(1, 5).iterator); expect(yieldCount, equals(0)); expect(i.first, equals(1)); expect(yieldCount, equals(1)); expect(i.firstWhere((int i) => i == 3), equals(3)); expect(yieldCount, equals(3)); expect(i.last, equals(5)); expect(yieldCount, equals(5)); }); test('The Caching Iterable: where and map', () { final Iterable<int> integers = CachingIterable<int>(range(1, 5).iterator); expect(yieldCount, equals(0)); final Iterable<int> evens = integers.where((int i) => i.isEven); expect(yieldCount, equals(0)); expect(evens.first, equals(2)); expect(yieldCount, equals(2)); expect(integers.first, equals(1)); expect(yieldCount, equals(2)); expect(evens.map<int>((int i) => i + 1), equals(<int>[3, 5])); expect(yieldCount, equals(5)); expect(evens, equals(<int>[2, 4])); expect(yieldCount, equals(5)); expect(integers, equals(<int>[1, 2, 3, 4, 5])); expect(yieldCount, equals(5)); }); test('The Caching Iterable: take and skip', () { final Iterable<int> integers = CachingIterable<int>(range(1, 5).iterator); expect(yieldCount, equals(0)); final Iterable<int> secondTwo = integers.skip(1).take(2); expect(yieldCount, equals(0)); expect(secondTwo, equals(<int>[2, 3])); expect(yieldCount, equals(3)); final Iterable<int> result = integers.takeWhile((int i) => i < 4).skipWhile((int i) => i < 3); expect(result, equals(<int>[3])); expect(yieldCount, equals(4)); expect(integers, equals(<int>[1, 2, 3, 4, 5])); expect(yieldCount, equals(5)); }); test('The Caching Iterable: expand', () { final Iterable<int> integers = CachingIterable<int>(range(1, 5).iterator); expect(yieldCount, equals(0)); final Iterable<int> expanded1 = integers.expand<int>((int i) => <int>[i, i]); expect(yieldCount, equals(0)); expect(expanded1, equals(<int>[1, 1, 2, 2, 3, 3, 4, 4, 5, 5])); expect(yieldCount, equals(5)); final Iterable<int> expanded2 = integers.expand<int>((int i) => <int>[i, i]); expect(yieldCount, equals(5)); expect(expanded2, equals(<int>[1, 1, 2, 2, 3, 3, 4, 4, 5, 5])); expect(yieldCount, equals(5)); }); }
flutter/packages/flutter/test/foundation/caching_iterable_test.dart/0
{ "file_path": "flutter/packages/flutter/test/foundation/caching_iterable_test.dart", "repo_id": "flutter", "token_count": 1269 }
661
// 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 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('ObserverList', () async { final ObserverList<int> list = ObserverList<int>(); for (int i = 0; i < 10; ++i) { list.add(i); } final Iterator<int> iterator = list.iterator; for (int i = 0; i < 10 && iterator.moveNext(); ++i) { expect(iterator.current, equals(i)); } for (int i = 9; i >= 0; --i) { expect(list.remove(i), isTrue); final Iterator<int> iterator = list.iterator; for (int j = 0; j < i && iterator.moveNext(); ++j) { expect(iterator.current, equals(j)); } } }); test('HashedObserverList', () async { final HashedObserverList<int> list = HashedObserverList<int>(); for (int i = 0; i < 10; ++i) { list.add(i); } Iterator<int> iterator = list.iterator; for (int i = 0; i < 10 && iterator.moveNext(); ++i) { expect(iterator.current, equals(i)); } for (int i = 9; i >= 0; --i) { expect(list.remove(i), isTrue); iterator = list.iterator; for (int j = 0; j < i && iterator.moveNext(); ++j) { expect(iterator.current, equals(j)); } } list.add(0); for (int i = 0; i < 10; ++i) { list.add(1); } list.add(2); iterator = list.iterator; for (int i = 0; iterator.moveNext(); ++i) { expect(iterator.current, equals(i)); expect(i, lessThan(3)); } for (int i = 2; i >= 0; --i) { expect(list.remove(i), isTrue); iterator = list.iterator; for (int j = 0; iterator.moveNext(); ++j) { expect(iterator.current, equals(i != 0 ? j : 1)); expect(j, lessThan(3)); } } iterator = list.iterator; for (int j = 0; iterator.moveNext(); ++j) { expect(iterator.current, equals(1)); expect(j, equals(0)); } expect(list.isEmpty, isFalse); iterator = list.iterator; iterator.moveNext(); expect(iterator.current, equals(1)); for (int i = 0; i < 9; ++i) { expect(list.remove(1), isTrue); } expect(list.isEmpty, isTrue); }); }
flutter/packages/flutter/test/foundation/observer_list_test.dart/0
{ "file_path": "flutter/packages/flutter/test/foundation/observer_list_test.dart", "repo_id": "flutter", "token_count": 974 }
662
// 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:ui' as ui; import 'package:flutter/gestures.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('PointerEvent resampling on a widget', (WidgetTester tester) async { Duration currentTestFrameTime() => Duration( milliseconds: TestWidgetsFlutterBinding.instance.clock.now().millisecondsSinceEpoch, ); void requestFrame() => SchedulerBinding.instance.scheduleFrameCallback((_) {}); final Duration epoch = currentTestFrameTime(); final ui.PointerDataPacket packet = ui.PointerDataPacket( data: <ui.PointerData>[ ui.PointerData( viewId: tester.view.viewId, change: ui.PointerChange.add, timeStamp: epoch, ), ui.PointerData( viewId: tester.view.viewId, change: ui.PointerChange.down, timeStamp: epoch, ), ui.PointerData( viewId: tester.view.viewId, change: ui.PointerChange.move, physicalX: 15.0, timeStamp: epoch + const Duration(milliseconds: 10), ), ui.PointerData( viewId: tester.view.viewId, change: ui.PointerChange.move, physicalX: 30.0, timeStamp: epoch + const Duration(milliseconds: 20), ), ui.PointerData( viewId: tester.view.viewId, change: ui.PointerChange.move, physicalX: 45.0, timeStamp: epoch + const Duration(milliseconds: 30), ), ui.PointerData( viewId: tester.view.viewId, change: ui.PointerChange.move, physicalX: 50.0, timeStamp: epoch + const Duration(milliseconds: 40), ), ui.PointerData( viewId: tester.view.viewId, change: ui.PointerChange.up, physicalX: 60.0, timeStamp: epoch + const Duration(milliseconds: 40), ), ui.PointerData( viewId: tester.view.viewId, change: ui.PointerChange.remove, physicalX: 60.0, timeStamp: epoch + const Duration(milliseconds: 40), ), ], ); final List<PointerEvent> events = <PointerEvent>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Listener( onPointerDown: (PointerDownEvent event) => events.add(event), onPointerMove: (PointerMoveEvent event) => events.add(event), onPointerUp: (PointerUpEvent event) => events.add(event), child: const Text('test'), ), ), ); GestureBinding.instance.resamplingEnabled = true; const Duration kSamplingOffset = Duration(milliseconds: -5); GestureBinding.instance.samplingOffset = kSamplingOffset; GestureBinding.instance.platformDispatcher.onPointerDataPacket!(packet); expect(events.length, 0); requestFrame(); await tester.pump(const Duration(milliseconds: 10)); expect(events.length, 1); expect(events[0], isA<PointerDownEvent>()); expect(events[0].timeStamp, currentTestFrameTime() + kSamplingOffset); expect(events[0].position, Offset(7.5 / tester.view.devicePixelRatio, 0.0)); // Now the system time is epoch + 20ms requestFrame(); await tester.pump(const Duration(milliseconds: 10)); expect(events.length, 2); expect(events[1].timeStamp, currentTestFrameTime() + kSamplingOffset); expect(events[1], isA<PointerMoveEvent>()); expect(events[1].position, Offset(22.5 / tester.view.devicePixelRatio, 0.0)); expect(events[1].delta, Offset(15.0 / tester.view.devicePixelRatio, 0.0)); // Now the system time is epoch + 30ms requestFrame(); await tester.pump(const Duration(milliseconds: 10)); expect(events.length, 4); expect(events[2].timeStamp, currentTestFrameTime() + kSamplingOffset); expect(events[2], isA<PointerMoveEvent>()); expect(events[2].position, Offset(37.5 / tester.view.devicePixelRatio, 0.0)); expect(events[2].delta, Offset(15.0 / tester.view.devicePixelRatio, 0.0)); expect(events[3].timeStamp, currentTestFrameTime() + kSamplingOffset); expect(events[3], isA<PointerUpEvent>()); }); testWidgets('Timer should be canceled when resampling stopped', (WidgetTester tester) async { // A timer will be started when event's timeStamp is larger than sampleTime. final ui.PointerDataPacket packet = ui.PointerDataPacket( data: <ui.PointerData>[ ui.PointerData( timeStamp: Duration(microseconds: DateTime.now().microsecondsSinceEpoch), ), ], ); GestureBinding.instance.resamplingEnabled = true; GestureBinding.instance.platformDispatcher.onPointerDataPacket!(packet); // Expected to stop resampling, but the timer keeps active if _timer?.cancel() not be called. GestureBinding.instance.resamplingEnabled = false; }); }
flutter/packages/flutter/test/gestures/gesture_binding_resample_event_on_widget_test.dart/0
{ "file_path": "flutter/packages/flutter/test/gestures/gesture_binding_resample_event_on_widget_test.dart", "repo_id": "flutter", "token_count": 2133 }
663
// 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 'package:flutter/gestures.dart'; import 'package:flutter_test/flutter_test.dart'; import 'gesture_tester.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); testGesture('Should recognize scale gestures', (GestureTester tester) { final ScaleGestureRecognizer scale = ScaleGestureRecognizer(); final TapGestureRecognizer tap = TapGestureRecognizer(); bool didStartScale = false; Offset? updatedFocalPoint; int? updatedPointerCount; scale.onStart = (ScaleStartDetails details) { didStartScale = true; updatedFocalPoint = details.focalPoint; updatedPointerCount = details.pointerCount; }; double? updatedScale; double? updatedHorizontalScale; double? updatedVerticalScale; Offset? updatedDelta; scale.onUpdate = (ScaleUpdateDetails details) { updatedScale = details.scale; updatedHorizontalScale = details.horizontalScale; updatedVerticalScale = details.verticalScale; updatedFocalPoint = details.focalPoint; updatedDelta = details.focalPointDelta; updatedPointerCount = details.pointerCount; }; bool didEndScale = false; scale.onEnd = (ScaleEndDetails details) { didEndScale = true; }; bool didTap = false; tap.onTap = () { didTap = true; }; final TestPointer pointer1 = TestPointer(); final PointerDownEvent down = pointer1.down(Offset.zero); scale.addPointer(down); tap.addPointer(down); tester.closeArena(1); expect(didStartScale, isFalse); expect(updatedScale, isNull); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(updatedPointerCount, isNull); expect(didEndScale, isFalse); expect(didTap, isFalse); // One-finger panning tester.route(down); expect(didStartScale, isFalse); expect(updatedScale, isNull); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(updatedPointerCount, isNull); expect(didEndScale, isFalse); expect(didTap, isFalse); tester.route(pointer1.move(const Offset(20.0, 30.0))); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, const Offset(20.0, 30.0)); updatedFocalPoint = null; expect(updatedScale, 1.0); updatedScale = null; expect(updatedDelta, const Offset(20.0, 30.0)); updatedDelta = null; expect(updatedPointerCount, 1); updatedPointerCount = null; expect(didEndScale, isFalse); expect(didTap, isFalse); // Two-finger scaling final TestPointer pointer2 = TestPointer(2); final PointerDownEvent down2 = pointer2.down(const Offset(10.0, 20.0)); scale.addPointer(down2); tap.addPointer(down2); tester.closeArena(2); tester.route(down2); expect(didEndScale, isTrue); didEndScale = false; expect(updatedScale, isNull); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(updatedPointerCount, isNull); expect(didStartScale, isFalse); // Zoom in tester.route(pointer2.move(const Offset(0.0, 10.0))); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, const Offset(10.0, 20.0)); updatedFocalPoint = null; expect(updatedScale, 2.0); expect(updatedHorizontalScale, 2.0); expect(updatedVerticalScale, 2.0); expect(updatedDelta, const Offset(-5.0, -5.0)); expect(updatedPointerCount, 2); updatedScale = null; updatedHorizontalScale = null; updatedVerticalScale = null; updatedDelta = null; updatedPointerCount = null; expect(didEndScale, isFalse); expect(didTap, isFalse); // Zoom out tester.route(pointer2.move(const Offset(15.0, 25.0))); expect(updatedFocalPoint, const Offset(17.5, 27.5)); expect(updatedScale, 0.5); expect(updatedHorizontalScale, 0.5); expect(updatedVerticalScale, 0.5); expect(updatedDelta, const Offset(7.5, 7.5)); expect(updatedPointerCount, 2); expect(didTap, isFalse); // Horizontal scaling tester.route(pointer2.move(const Offset(0.0, 20.0))); expect(updatedHorizontalScale, 2.0); expect(updatedVerticalScale, 1.0); expect(updatedPointerCount, 2); // Vertical scaling tester.route(pointer2.move(const Offset(10.0, 10.0))); expect(updatedHorizontalScale, 1.0); expect(updatedVerticalScale, 2.0); expect(updatedDelta, const Offset(5.0, -5.0)); expect(updatedPointerCount, 2); tester.route(pointer2.move(const Offset(15.0, 25.0))); updatedFocalPoint = null; updatedScale = null; updatedDelta = null; updatedPointerCount = null; // Three-finger scaling final TestPointer pointer3 = TestPointer(3); final PointerDownEvent down3 = pointer3.down(const Offset(25.0, 35.0)); scale.addPointer(down3); tap.addPointer(down3); tester.closeArena(3); tester.route(down3); expect(didEndScale, isTrue); didEndScale = false; expect(updatedScale, isNull); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(updatedPointerCount, isNull); expect(didStartScale, isFalse); // Zoom in tester.route(pointer3.move(const Offset(55.0, 65.0))); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, const Offset(30.0, 40.0)); updatedFocalPoint = null; expect(updatedScale, 5.0); updatedScale = null; expect(updatedDelta, const Offset(10.0, 10.0)); updatedDelta = null; expect(updatedPointerCount, 3); updatedPointerCount = null; expect(didEndScale, isFalse); expect(didTap, isFalse); // Return to original positions but with different fingers tester.route(pointer1.move(const Offset(25.0, 35.0))); tester.route(pointer2.move(const Offset(20.0, 30.0))); tester.route(pointer3.move(const Offset(15.0, 25.0))); expect(didStartScale, isFalse); expect(updatedFocalPoint, const Offset(20.0, 30.0)); updatedFocalPoint = null; expect(updatedScale, 1.0); updatedScale = null; expect(updatedDelta!.dx, closeTo(-13.3, 0.1)); expect(updatedDelta!.dy, closeTo(-13.3, 0.1)); updatedDelta = null; expect(updatedPointerCount, 3); updatedPointerCount = null; expect(didEndScale, isFalse); expect(didTap, isFalse); tester.route(pointer1.up()); expect(didStartScale, isFalse); expect(updatedFocalPoint, isNull); expect(updatedScale, isNull); expect(updatedDelta, isNull); expect(didEndScale, isTrue); didEndScale = false; expect(didTap, isFalse); // Continue scaling with two fingers tester.route(pointer3.move(const Offset(10.0, 20.0))); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, const Offset(15.0, 25.0)); updatedFocalPoint = null; expect(updatedScale, 2.0); updatedScale = null; expect(updatedDelta, const Offset(-2.5, -2.5)); updatedDelta = null; expect(updatedPointerCount, 2); updatedPointerCount = null; // Continue rotating with two fingers tester.route(pointer3.move(const Offset(30.0, 40.0))); expect(updatedFocalPoint, const Offset(25.0, 35.0)); updatedFocalPoint = null; expect(updatedScale, 2.0); updatedScale = null; expect(updatedDelta, const Offset(10.0, 10.0)); updatedDelta = null; tester.route(pointer3.move(const Offset(10.0, 20.0))); expect(updatedFocalPoint, const Offset(15.0, 25.0)); updatedFocalPoint = null; expect(updatedScale, 2.0); updatedScale = null; expect(updatedDelta, const Offset(-10.0, -10.0)); updatedDelta = null; expect(updatedPointerCount, 2); updatedPointerCount = null; tester.route(pointer2.up()); expect(didStartScale, isFalse); expect(updatedFocalPoint, isNull); expect(updatedScale, isNull); expect(updatedDelta, isNull); expect(didEndScale, isTrue); didEndScale = false; expect(didTap, isFalse); // Continue panning with one finger tester.route(pointer3.move(Offset.zero)); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, Offset.zero); updatedFocalPoint = null; expect(updatedScale, 1.0); updatedScale = null; expect(updatedDelta, const Offset(-10.0, -20.0)); updatedDelta = null; expect(updatedPointerCount, 1); updatedPointerCount = null; // We are done tester.route(pointer3.up()); expect(didStartScale, isFalse); expect(updatedFocalPoint, isNull); expect(updatedScale, isNull); expect(updatedDelta, isNull); expect(updatedPointerCount, isNull); expect(didEndScale, isTrue); didEndScale = false; expect(didTap, isFalse); scale.dispose(); tap.dispose(); }); testGesture('Rejects scale gestures from unallowed device kinds', (GestureTester tester) { final ScaleGestureRecognizer scale = ScaleGestureRecognizer( supportedDevices: <PointerDeviceKind>{ PointerDeviceKind.touch }, ); bool didStartScale = false; scale.onStart = (ScaleStartDetails details) { didStartScale = true; }; double? updatedScale; scale.onUpdate = (ScaleUpdateDetails details) { updatedScale = details.scale; }; final TestPointer mousePointer = TestPointer(1, PointerDeviceKind.mouse); final PointerDownEvent down = mousePointer.down(Offset.zero); scale.addPointer(down); tester.closeArena(1); // One-finger panning tester.route(down); expect(didStartScale, isFalse); expect(updatedScale, isNull); // Using a mouse, the scale gesture shouldn't even start. tester.route(mousePointer.move(const Offset(20.0, 30.0))); expect(didStartScale, isFalse); expect(updatedScale, isNull); scale.dispose(); }); testGesture('Scale gestures starting from allowed device kinds cannot be ended from unallowed devices', (GestureTester tester) { final ScaleGestureRecognizer scale = ScaleGestureRecognizer( supportedDevices: <PointerDeviceKind>{ PointerDeviceKind.touch }, ); bool didStartScale = false; Offset? updatedFocalPoint; scale.onStart = (ScaleStartDetails details) { didStartScale = true; updatedFocalPoint = details.focalPoint; }; double? updatedScale; scale.onUpdate = (ScaleUpdateDetails details) { updatedScale = details.scale; updatedFocalPoint = details.focalPoint; }; bool didEndScale = false; scale.onEnd = (ScaleEndDetails details) { didEndScale = true; }; final TestPointer touchPointer = TestPointer(); final PointerDownEvent down = touchPointer.down(Offset.zero); scale.addPointer(down); tester.closeArena(1); // One-finger panning tester.route(down); expect(didStartScale, isTrue); didStartScale = false; expect(updatedScale, isNull); expect(updatedFocalPoint, Offset.zero); expect(didEndScale, isFalse); // The gesture can start using one touch finger. tester.route(touchPointer.move(const Offset(20.0, 30.0))); expect(updatedFocalPoint, const Offset(20.0, 30.0)); updatedFocalPoint = null; expect(updatedScale, 1.0); updatedScale = null; expect(didEndScale, isFalse); // Two-finger scaling final TestPointer mousePointer = TestPointer(2, PointerDeviceKind.mouse); final PointerDownEvent down2 = mousePointer.down(const Offset(10.0, 20.0)); scale.addPointer(down2); tester.closeArena(2); tester.route(down2); // Mouse-generated events are ignored. expect(didEndScale, isFalse); expect(updatedScale, isNull); expect(didStartScale, isFalse); // Zoom in using a mouse doesn't work either. tester.route(mousePointer.move(const Offset(0.0, 10.0))); expect(updatedScale, isNull); expect(didEndScale, isFalse); scale.dispose(); }); testGesture('Scale gesture competes with drag', (GestureTester tester) { final ScaleGestureRecognizer scale = ScaleGestureRecognizer(); final HorizontalDragGestureRecognizer drag = HorizontalDragGestureRecognizer(); final List<String> log = <String>[]; scale.onStart = (ScaleStartDetails details) { log.add('scale-start'); }; scale.onUpdate = (ScaleUpdateDetails details) { log.add('scale-update'); }; scale.onEnd = (ScaleEndDetails details) { log.add('scale-end'); }; drag.onStart = (DragStartDetails details) { log.add('drag-start'); }; drag.onEnd = (DragEndDetails details) { log.add('drag-end'); }; final TestPointer pointer1 = TestPointer(); final PointerDownEvent down = pointer1.down(const Offset(10.0, 10.0)); scale.addPointer(down); drag.addPointer(down); tester.closeArena(1); expect(log, isEmpty); // Vertical moves are scales. tester.route(down); expect(log, isEmpty); // Scale will win if focal point delta exceeds 18.0*2. tester.route(pointer1.move(const Offset(10.0, 50.0))); // Delta of 40.0 exceeds 18.0*2. expect(log, equals(<String>['scale-start', 'scale-update'])); log.clear(); final TestPointer pointer2 = TestPointer(2); final PointerDownEvent down2 = pointer2.down(const Offset(10.0, 20.0)); scale.addPointer(down2); drag.addPointer(down2); tester.closeArena(2); expect(log, isEmpty); // Second pointer joins scale even though it moves horizontally. tester.route(down2); expect(log, <String>['scale-end']); log.clear(); tester.route(pointer2.move(const Offset(30.0, 20.0))); expect(log, equals(<String>['scale-start', 'scale-update'])); log.clear(); tester.route(pointer1.up()); expect(log, equals(<String>['scale-end'])); log.clear(); tester.route(pointer2.up()); expect(log, isEmpty); log.clear(); // Horizontal moves are either drags or scales, depending on which wins first. // TODO(ianh): https://github.com/flutter/flutter/issues/11384 // In this case, we move fast, so that the scale wins. If we moved slowly, // the horizontal drag would win, since it was added first. final TestPointer pointer3 = TestPointer(3); final PointerDownEvent down3 = pointer3.down(const Offset(30.0, 30.0)); scale.addPointer(down3); drag.addPointer(down3); tester.closeArena(3); tester.route(down3); expect(log, isEmpty); tester.route(pointer3.move(const Offset(100.0, 30.0))); expect(log, equals(<String>['scale-start', 'scale-update'])); log.clear(); tester.route(pointer3.up()); expect(log, equals(<String>['scale-end'])); log.clear(); scale.dispose(); drag.dispose(); }); testGesture('Should recognize rotation gestures', (GestureTester tester) { final ScaleGestureRecognizer scale = ScaleGestureRecognizer(); final TapGestureRecognizer tap = TapGestureRecognizer(); bool didStartScale = false; Offset? updatedFocalPoint; int? updatedPointerCount; scale.onStart = (ScaleStartDetails details) { didStartScale = true; updatedFocalPoint = details.focalPoint; updatedPointerCount = details.pointerCount; }; double? updatedRotation; Offset? updatedDelta; scale.onUpdate = (ScaleUpdateDetails details) { updatedRotation = details.rotation; updatedFocalPoint = details.focalPoint; updatedDelta = details.focalPointDelta; updatedPointerCount = details.pointerCount; }; bool didEndScale = false; scale.onEnd = (ScaleEndDetails details) { didEndScale = true; }; bool didTap = false; tap.onTap = () { didTap = true; }; final TestPointer pointer1 = TestPointer(); final PointerDownEvent down = pointer1.down(Offset.zero); scale.addPointer(down); tap.addPointer(down); tester.closeArena(1); expect(didStartScale, isFalse); expect(updatedRotation, isNull); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(didEndScale, isFalse); expect(didTap, isFalse); tester.route(down); tester.route(pointer1.move(const Offset(20.0, 30.0))); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, const Offset(20.0, 30.0)); updatedFocalPoint = null; expect(updatedDelta, const Offset(20.0, 30.0)); updatedDelta = null; expect(updatedRotation, 0.0); updatedRotation = null; expect(updatedPointerCount, 1); updatedPointerCount = null; expect(didEndScale, isFalse); expect(didTap, isFalse); // Two-finger scaling final TestPointer pointer2 = TestPointer(2); final PointerDownEvent down2 = pointer2.down(const Offset(30.0, 40.0)); scale.addPointer(down2); tap.addPointer(down2); tester.closeArena(2); tester.route(down2); expect(didEndScale, isTrue); didEndScale = false; expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(updatedRotation, isNull); expect(updatedPointerCount, isNull); expect(didStartScale, isFalse); // Zoom in tester.route(pointer2.move(const Offset(40.0, 50.0))); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, const Offset(30.0, 40.0)); updatedFocalPoint = null; expect(updatedDelta, const Offset(5.0, 5.0)); updatedDelta = null; expect(updatedRotation, 0.0); updatedRotation = null; expect(updatedPointerCount, 2); updatedPointerCount = null; expect(didEndScale, isFalse); expect(didTap, isFalse); // Rotation tester.route(pointer2.move(const Offset(0.0, 10.0))); expect(updatedFocalPoint, const Offset(10.0, 20.0)); updatedFocalPoint = null; expect(updatedDelta, const Offset(-20.0, -20.0)); updatedDelta = null; expect(updatedRotation, math.pi); updatedRotation = null; expect(updatedPointerCount, 2); updatedPointerCount = null; expect(didEndScale, isFalse); expect(didTap, isFalse); // Three-finger scaling final TestPointer pointer3 = TestPointer(3); final PointerDownEvent down3 = pointer3.down(const Offset(25.0, 35.0)); scale.addPointer(down3); tap.addPointer(down3); tester.closeArena(3); tester.route(down3); expect(didEndScale, isTrue); didEndScale = false; expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(updatedRotation, isNull); expect(updatedPointerCount, isNull); expect(didStartScale, isFalse); // Zoom in tester.route(pointer3.move(const Offset(55.0, 65.0))); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, const Offset(25.0, 35.0)); updatedFocalPoint = null; expect(updatedDelta, const Offset(10.0, 10.0)); updatedDelta = null; expect(updatedRotation, 0.0); updatedRotation = null; expect(updatedPointerCount, 3); updatedPointerCount = null; expect(didEndScale, isFalse); expect(didTap, isFalse); // Return to original positions but with different fingers tester.route(pointer1.move(const Offset(25.0, 35.0))); tester.route(pointer2.move(const Offset(20.0, 30.0))); tester.route(pointer3.move(const Offset(15.0, 25.0))); expect(didStartScale, isFalse); expect(updatedFocalPoint, const Offset(20.0, 30.0)); updatedFocalPoint = null; expect(updatedDelta!.dx, closeTo(-13.3, 0.1)); expect(updatedDelta!.dy, closeTo(-13.3, 0.1)); updatedDelta = null; expect(updatedRotation, 0.0); updatedRotation = null; expect(updatedPointerCount, 3); updatedPointerCount = null; expect(didEndScale, isFalse); expect(didTap, isFalse); tester.route(pointer1.up()); expect(didStartScale, isFalse); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(updatedRotation, isNull); expect(didEndScale, isTrue); didEndScale = false; expect(didTap, isFalse); // Continue scaling with two fingers tester.route(pointer3.move(const Offset(10.0, 20.0))); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, const Offset(15.0, 25.0)); updatedFocalPoint = null; expect(updatedDelta, const Offset(-2.5, -2.5)); updatedDelta = null; expect(updatedRotation, 0.0); updatedRotation = null; expect(updatedPointerCount, 2); updatedPointerCount = null; // Continue rotating with two fingers tester.route(pointer3.move(const Offset(30.0, 40.0))); expect(updatedFocalPoint, const Offset(25.0, 35.0)); updatedFocalPoint = null; expect(updatedDelta, const Offset(10.0, 10.0)); updatedDelta = null; expect(updatedRotation, - math.pi); updatedRotation = null; expect(updatedPointerCount, 2); updatedPointerCount = null; tester.route(pointer3.move(const Offset(10.0, 20.0))); expect(updatedFocalPoint, const Offset(15.0, 25.0)); updatedFocalPoint = null; expect(updatedDelta, const Offset(-10.0, -10.0)); updatedDelta = null; expect(updatedRotation, 0.0); updatedRotation = null; expect(updatedPointerCount, 2); updatedPointerCount = null; tester.route(pointer2.up()); expect(didStartScale, isFalse); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(updatedRotation, isNull); expect(updatedPointerCount, isNull); expect(didEndScale, isTrue); didEndScale = false; expect(didTap, isFalse); // We are done tester.route(pointer3.up()); expect(didStartScale, isFalse); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(updatedRotation, isNull); expect(updatedPointerCount, isNull); expect(didEndScale, isFalse); didEndScale = false; expect(didTap, isFalse); scale.dispose(); tap.dispose(); }); // Regressing test for https://github.com/flutter/flutter/issues/78941 testGesture('First rotation test', (GestureTester tester) { final ScaleGestureRecognizer scale = ScaleGestureRecognizer(); addTearDown(scale.dispose); double? updatedRotation; scale.onUpdate = (ScaleUpdateDetails details) { updatedRotation = details.rotation; }; final TestPointer pointer1 = TestPointer(); final PointerDownEvent down = pointer1.down(Offset.zero); scale.addPointer(down); tester.closeArena(1); tester.route(down); final TestPointer pointer2 = TestPointer(2); final PointerDownEvent down2 = pointer2.down(const Offset(10.0, 10.0)); scale.addPointer(down2); tester.closeArena(2); tester.route(down2); expect(updatedRotation, isNull); // Rotation 45°. tester.route(pointer2.move(const Offset(0.0, 10.0))); expect(updatedRotation, math.pi / 4.0); }); testGesture('Scale gestures pointer count test', (GestureTester tester) { final ScaleGestureRecognizer scale = ScaleGestureRecognizer(); int pointerCountOfStart = 0; scale.onStart = (ScaleStartDetails details) => pointerCountOfStart = details.pointerCount; int pointerCountOfUpdate = 0; scale.onUpdate = (ScaleUpdateDetails details) => pointerCountOfUpdate = details.pointerCount; int pointerCountOfEnd = 0; scale.onEnd = (ScaleEndDetails details) => pointerCountOfEnd = details.pointerCount; final TestPointer pointer1 = TestPointer(); final PointerDownEvent down = pointer1.down(Offset.zero); scale.addPointer(down); tester.closeArena(1); // One-finger panning tester.route(down); // One pointer in contact with the screen now. expect(pointerCountOfStart, 1); tester.route(pointer1.move(const Offset(20.0, 30.0))); expect(pointerCountOfUpdate, 1); // Two-finger scaling final TestPointer pointer2 = TestPointer(2); final PointerDownEvent down2 = pointer2.down(const Offset(10.0, 20.0)); scale.addPointer(down2); tester.closeArena(2); tester.route(down2); // Two pointers in contact with the screen now. expect(pointerCountOfEnd, 2); // Additional pointer down will trigger an end event. tester.route(pointer2.move(const Offset(0.0, 10.0))); expect(pointerCountOfStart, 2); // The new pointer move will trigger a start event. expect(pointerCountOfUpdate, 2); tester.route(pointer1.up()); // One pointer in contact with the screen now. expect(pointerCountOfEnd, 1); tester.route(pointer2.move(const Offset(0.0, 10.0))); expect(pointerCountOfStart, 1); expect(pointerCountOfUpdate, 1); tester.route(pointer2.up()); // No pointer in contact with the screen now. expect(pointerCountOfEnd, 0); scale.dispose(); }); testGesture('Should recognize scale gestures from pointer pan/zoom events', (GestureTester tester) { final ScaleGestureRecognizer scale = ScaleGestureRecognizer(); addTearDown(scale.dispose); final HorizontalDragGestureRecognizer drag = HorizontalDragGestureRecognizer(); addTearDown(drag.dispose); bool didStartScale = false; Offset? updatedFocalPoint; int? updatedPointerCount; scale.onStart = (ScaleStartDetails details) { didStartScale = true; updatedFocalPoint = details.focalPoint; updatedPointerCount = details.pointerCount; }; double? updatedScale; double? updatedHorizontalScale; double? updatedVerticalScale; Offset? updatedDelta; scale.onUpdate = (ScaleUpdateDetails details) { updatedScale = details.scale; updatedHorizontalScale = details.horizontalScale; updatedVerticalScale = details.verticalScale; updatedFocalPoint = details.focalPoint; updatedDelta = details.focalPointDelta; updatedPointerCount = details.pointerCount; }; bool didEndScale = false; scale.onEnd = (ScaleEndDetails details) { didEndScale = true; }; final TestPointer pointer1 = TestPointer(2, PointerDeviceKind.trackpad); final PointerPanZoomStartEvent start = pointer1.panZoomStart(Offset.zero); scale.addPointerPanZoom(start); drag.addPointerPanZoom(start); tester.closeArena(2); expect(didStartScale, isFalse); expect(updatedScale, isNull); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(updatedPointerCount, isNull); expect(didEndScale, isFalse); // Panning. tester.route(start); expect(didStartScale, isFalse); expect(updatedScale, isNull); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(updatedPointerCount, isNull); expect(didEndScale, isFalse); tester.route(pointer1.panZoomUpdate(Offset.zero, pan: const Offset(20.0, 30.0))); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, const Offset(20.0, 30.0)); updatedFocalPoint = null; expect(updatedScale, 1.0); updatedScale = null; expect(updatedDelta, const Offset(20.0, 30.0)); updatedDelta = null; expect(updatedPointerCount, 2); updatedPointerCount = null; expect(didEndScale, isFalse); // Zoom in. tester.route(pointer1.panZoomUpdate(Offset.zero, pan: const Offset(20.0, 30.0), scale: 2.0)); expect(updatedFocalPoint, const Offset(20.0, 30.0)); updatedFocalPoint = null; expect(updatedScale, 2.0); expect(updatedHorizontalScale, 2.0); expect(updatedVerticalScale, 2.0); expect(updatedDelta, Offset.zero); expect(updatedPointerCount, 2); updatedScale = null; updatedHorizontalScale = null; updatedVerticalScale = null; updatedDelta = null; updatedPointerCount = null; expect(didEndScale, isFalse); // Zoom out. tester.route(pointer1.panZoomUpdate(Offset.zero, pan: const Offset(20.0, 30.0))); expect(updatedFocalPoint, const Offset(20.0, 30.0)); updatedFocalPoint = null; expect(updatedScale, 1.0); expect(updatedHorizontalScale, 1.0); expect(updatedVerticalScale, 1.0); expect(updatedDelta, Offset.zero); expect(updatedPointerCount, 2); updatedScale = null; updatedHorizontalScale = null; updatedVerticalScale = null; updatedDelta = null; updatedPointerCount = null; expect(didEndScale, isFalse); // We are done. tester.route(pointer1.panZoomEnd()); expect(didStartScale, isFalse); expect(updatedFocalPoint, isNull); expect(updatedScale, isNull); expect(updatedDelta, isNull); expect(updatedPointerCount, isNull); expect(didEndScale, isTrue); didEndScale = false; scale.dispose(); }); testGesture('Pointer pan/zooms should work alongside touches', (GestureTester tester) { final ScaleGestureRecognizer scale = ScaleGestureRecognizer(); addTearDown(scale.dispose); final HorizontalDragGestureRecognizer drag = HorizontalDragGestureRecognizer(); addTearDown(drag.dispose); bool didStartScale = false; Offset? updatedFocalPoint; int? updatedPointerCount; scale.onStart = (ScaleStartDetails details) { didStartScale = true; updatedFocalPoint = details.focalPoint; updatedPointerCount = details.pointerCount; }; double? updatedScale; double? updatedHorizontalScale; double? updatedVerticalScale; Offset? updatedDelta; double? updatedRotation; scale.onUpdate = (ScaleUpdateDetails details) { updatedScale = details.scale; updatedHorizontalScale = details.horizontalScale; updatedVerticalScale = details.verticalScale; updatedFocalPoint = details.focalPoint; updatedDelta = details.focalPointDelta; updatedRotation = details.rotation; updatedPointerCount = details.pointerCount; }; bool didEndScale = false; scale.onEnd = (ScaleEndDetails details) { didEndScale = true; }; final TestPointer touchPointer1 = TestPointer(2); final TestPointer touchPointer2 = TestPointer(3); final TestPointer panZoomPointer = TestPointer(4, PointerDeviceKind.trackpad); final PointerPanZoomStartEvent panZoomStart = panZoomPointer.panZoomStart(Offset.zero); scale.addPointerPanZoom(panZoomStart); drag.addPointerPanZoom(panZoomStart); tester.closeArena(4); expect(didStartScale, isFalse); expect(updatedScale, isNull); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(updatedPointerCount, isNull); expect(didEndScale, isFalse); // Panning starting with trackpad. tester.route(panZoomStart); expect(didStartScale, isFalse); expect(updatedScale, isNull); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(updatedPointerCount, isNull); expect(didEndScale, isFalse); tester.route(panZoomPointer.panZoomUpdate(Offset.zero, pan: const Offset(40, 40))); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, const Offset(40.0, 40.0)); updatedFocalPoint = null; expect(updatedScale, 1.0); updatedScale = null; expect(updatedDelta, const Offset(40.0, 40.0)); updatedDelta = null; expect(updatedPointerCount, 2); updatedPointerCount = null; expect(didEndScale, isFalse); // Add a touch pointer. final PointerDownEvent touchStart1 = touchPointer1.down(const Offset(40, 40)); scale.addPointer(touchStart1); drag.addPointer(touchStart1); tester.closeArena(2); tester.route(touchStart1); expect(didEndScale, isTrue); didEndScale = false; tester.route(touchPointer1.move(const Offset(10, 10))); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, const Offset(25, 25)); updatedFocalPoint = null; // 1 down pointer + pointer pan/zoom should not scale, only pan. expect(updatedScale, 1.0); updatedScale = null; expect(updatedDelta, const Offset(-15, -15)); updatedDelta = null; expect(updatedPointerCount, 3); updatedPointerCount = null; expect(didEndScale, isFalse); // Add a second touch pointer. final PointerDownEvent touchStart2 = touchPointer2.down(const Offset(10, 40)); scale.addPointer(touchStart2); drag.addPointer(touchStart2); tester.closeArena(3); tester.route(touchStart2); expect(didEndScale, isTrue); didEndScale = false; // Move the second pointer to cause pan, zoom, and rotation. tester.route(touchPointer2.move(const Offset(40, 40))); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, const Offset(30, 30)); updatedFocalPoint = null; expect(updatedScale, math.sqrt(2)); updatedScale = null; expect(updatedHorizontalScale, 1.0); updatedHorizontalScale = null; expect(updatedVerticalScale, 1.0); updatedVerticalScale = null; expect(updatedDelta, const Offset(10, 0)); updatedDelta = null; expect(updatedRotation, -math.pi / 4); updatedRotation = null; expect(updatedPointerCount, 4); updatedPointerCount = null; expect(didEndScale, isFalse); // Change the scale and angle of the pan/zoom to test combining. // Scale should be multiplied together. // Rotation angle should be added together. tester.route(panZoomPointer.panZoomUpdate(Offset.zero, pan: const Offset(40, 40), scale: math.sqrt(2), rotation: math.pi / 3)); expect(didStartScale, isFalse); expect(updatedFocalPoint, const Offset(30, 30)); updatedFocalPoint = null; expect(updatedScale, closeTo(2, 0.0001)); updatedScale = null; expect(updatedHorizontalScale, math.sqrt(2)); updatedHorizontalScale = null; expect(updatedVerticalScale, math.sqrt(2)); updatedVerticalScale = null; expect(updatedDelta, Offset.zero); updatedDelta = null; expect(updatedRotation, closeTo(math.pi / 12, 0.0001)); updatedRotation = null; expect(updatedPointerCount, 4); updatedPointerCount = null; expect(didEndScale, isFalse); // Move the pan/zoom origin to test combining. tester.route(panZoomPointer.panZoomUpdate(const Offset(15, 15), pan: const Offset(55, 55), scale: math.sqrt(2), rotation: math.pi / 3)); expect(didStartScale, isFalse); expect(updatedFocalPoint, const Offset(40, 40)); updatedFocalPoint = null; expect(updatedScale, closeTo(2, 0.0001)); updatedScale = null; expect(updatedDelta, const Offset(10, 10)); updatedDelta = null; expect(updatedRotation, closeTo(math.pi / 12, 0.0001)); updatedRotation = null; expect(updatedPointerCount, 4); updatedPointerCount = null; expect(didEndScale, isFalse); // We are done. tester.route(panZoomPointer.panZoomEnd()); expect(updatedFocalPoint, isNull); expect(didEndScale, isTrue); didEndScale = false; expect(updatedScale, isNull); expect(updatedDelta, isNull); expect(updatedPointerCount, isNull); expect(didStartScale, isFalse); tester.route(touchPointer1.up()); expect(updatedFocalPoint, isNull); expect(didEndScale, isFalse); expect(updatedScale, isNull); expect(updatedDelta, isNull); expect(updatedPointerCount, isNull); expect(didStartScale, isFalse); tester.route(touchPointer2.up()); expect(didEndScale, isFalse); expect(updatedFocalPoint, isNull); expect(updatedScale, isNull); expect(updatedDelta, isNull); expect(updatedPointerCount, isNull); expect(didStartScale, isFalse); scale.dispose(); }); testGesture('Scale gesture competes with drag for trackpad gesture', (GestureTester tester) { final ScaleGestureRecognizer scale = ScaleGestureRecognizer(); final HorizontalDragGestureRecognizer drag = HorizontalDragGestureRecognizer(); final List<String> log = <String>[]; scale.onStart = (ScaleStartDetails details) { log.add('scale-start'); }; scale.onUpdate = (ScaleUpdateDetails details) { log.add('scale-update'); }; scale.onEnd = (ScaleEndDetails details) { log.add('scale-end'); }; drag.onStart = (DragStartDetails details) { log.add('drag-start'); }; drag.onEnd = (DragEndDetails details) { log.add('drag-end'); }; final TestPointer pointer1 = TestPointer(2, PointerDeviceKind.trackpad); final PointerPanZoomStartEvent down = pointer1.panZoomStart(const Offset(10.0, 10.0)); scale.addPointerPanZoom(down); drag.addPointerPanZoom(down); tester.closeArena(2); expect(log, isEmpty); // Vertical moves are scales. tester.route(down); expect(log, isEmpty); // Scale will win if focal point delta exceeds 18.0*2. tester.route(pointer1.panZoomUpdate(const Offset(10.0, 10.0), pan: const Offset(10.0, 40.0))); // delta of 40.0 exceeds 18.0*2. expect(log, equals(<String>['scale-start', 'scale-update'])); log.clear(); final TestPointer pointer2 = TestPointer(3, PointerDeviceKind.trackpad); final PointerPanZoomStartEvent down2 = pointer2.panZoomStart(const Offset(10.0, 20.0)); scale.addPointerPanZoom(down2); drag.addPointerPanZoom(down2); tester.closeArena(3); expect(log, isEmpty); // Second pointer joins scale even though it moves horizontally. tester.route(down2); expect(log, <String>['scale-end']); log.clear(); tester.route(pointer2.panZoomUpdate(const Offset(10.0, 20.0), pan: const Offset(20.0, 0.0))); expect(log, equals(<String>['scale-start', 'scale-update'])); log.clear(); tester.route(pointer1.panZoomEnd()); expect(log, equals(<String>['scale-end'])); log.clear(); tester.route(pointer2.panZoomEnd()); expect(log, isEmpty); log.clear(); // Horizontal moves are either drags or scales, depending on which wins first. // TODO(ianh): https://github.com/flutter/flutter/issues/11384 // In this case, we move fast, so that the scale wins. If we moved slowly, // the horizontal drag would win, since it was added first. final TestPointer pointer3 = TestPointer(4, PointerDeviceKind.trackpad); final PointerPanZoomStartEvent down3 = pointer3.panZoomStart(const Offset(30.0, 30.0)); scale.addPointerPanZoom(down3); drag.addPointerPanZoom(down3); tester.closeArena(4); tester.route(down3); expect(log, isEmpty); tester.route(pointer3.panZoomUpdate(const Offset(30.0, 30.0), pan: const Offset(70.0, 0.0))); expect(log, equals(<String>['scale-start', 'scale-update'])); log.clear(); tester.route(pointer3.panZoomEnd()); expect(log, equals(<String>['scale-end'])); log.clear(); scale.dispose(); drag.dispose(); }); testGesture('Scale gesture from pan/zoom events properly handles DragStartBehavior.start', (GestureTester tester) { final ScaleGestureRecognizer scale = ScaleGestureRecognizer(dragStartBehavior: DragStartBehavior.start); addTearDown(scale.dispose); final HorizontalDragGestureRecognizer drag = HorizontalDragGestureRecognizer(); addTearDown(drag.dispose); bool didStartScale = false; Offset? updatedFocalPoint; scale.onStart = (ScaleStartDetails details) { didStartScale = true; updatedFocalPoint = details.focalPoint; }; double? updatedScale; double? updatedHorizontalScale; double? updatedVerticalScale; double? updatedRotation; Offset? updatedDelta; scale.onUpdate = (ScaleUpdateDetails details) { updatedScale = details.scale; updatedHorizontalScale = details.horizontalScale; updatedVerticalScale = details.verticalScale; updatedFocalPoint = details.focalPoint; updatedRotation = details.rotation; updatedDelta = details.focalPointDelta; }; bool didEndScale = false; scale.onEnd = (ScaleEndDetails details) { didEndScale = true; }; final TestPointer pointer1 = TestPointer(2, PointerDeviceKind.trackpad); final PointerPanZoomStartEvent start = pointer1.panZoomStart(Offset.zero); scale.addPointerPanZoom(start); drag.addPointerPanZoom(start); tester.closeArena(2); expect(didStartScale, isFalse); expect(updatedScale, isNull); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(didEndScale, isFalse); tester.route(start); expect(didStartScale, isFalse); expect(updatedScale, isNull); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(didEndScale, isFalse); // Zoom enough to win the gesture. tester.route(pointer1.panZoomUpdate(Offset.zero, scale: 1.1, rotation: 1)); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, Offset.zero); updatedFocalPoint = null; expect(updatedScale, 1.0); updatedScale = null; expect(updatedDelta, Offset.zero); updatedDelta = null; expect(didEndScale, isFalse); // Zoom in - should be relative to 1.1. tester.route(pointer1.panZoomUpdate(Offset.zero, scale: 1.21, rotation: 1.5)); expect(updatedFocalPoint, Offset.zero); updatedFocalPoint = null; expect(updatedScale, closeTo(1.1, 0.0001)); expect(updatedHorizontalScale, closeTo(1.1, 0.0001)); expect(updatedVerticalScale, closeTo(1.1, 0.0001)); expect(updatedRotation, 0.5); expect(updatedDelta, Offset.zero); updatedScale = null; updatedHorizontalScale = null; updatedVerticalScale = null; updatedRotation = null; updatedDelta = null; expect(didEndScale, isFalse); // Zoom out - should be relative to 1.1. tester.route(pointer1.panZoomUpdate(Offset.zero, scale: 0.99, rotation: 1.0)); expect(updatedFocalPoint, Offset.zero); updatedFocalPoint = null; expect(updatedScale, closeTo(0.9, 0.0001)); expect(updatedHorizontalScale, closeTo(0.9, 0.0001)); expect(updatedVerticalScale, closeTo(0.9, 0.0001)); expect(updatedRotation, 0.0); expect(updatedDelta, Offset.zero); updatedScale = null; updatedHorizontalScale = null; updatedVerticalScale = null; updatedDelta = null; expect(didEndScale, isFalse); // We are done. tester.route(pointer1.panZoomEnd()); expect(didStartScale, isFalse); expect(updatedFocalPoint, isNull); expect(updatedScale, isNull); expect(updatedDelta, isNull); expect(didEndScale, isTrue); didEndScale = false; }); testGesture('scale trackpadScrollCausesScale', (GestureTester tester) { final ScaleGestureRecognizer scale = ScaleGestureRecognizer( dragStartBehavior: DragStartBehavior.start, trackpadScrollCausesScale: true ); bool didStartScale = false; Offset? updatedFocalPoint; int? updatedPointerCount; scale.onStart = (ScaleStartDetails details) { didStartScale = true; updatedFocalPoint = details.focalPoint; updatedPointerCount = details.pointerCount; }; double? updatedScale; Offset? updatedDelta; scale.onUpdate = (ScaleUpdateDetails details) { updatedScale = details.scale; updatedFocalPoint = details.focalPoint; updatedDelta = details.focalPointDelta; updatedPointerCount = details.pointerCount; }; bool didEndScale = false; scale.onEnd = (ScaleEndDetails details) { didEndScale = true; }; final TestPointer pointer1 = TestPointer(2, PointerDeviceKind.trackpad); final PointerPanZoomStartEvent start = pointer1.panZoomStart(Offset.zero); scale.addPointerPanZoom(start); tester.closeArena(2); expect(didStartScale, isFalse); expect(updatedScale, isNull); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(updatedPointerCount, isNull); expect(didEndScale, isFalse); tester.route(start); expect(didStartScale, isTrue); didStartScale = false; expect(updatedScale, isNull); expect(updatedFocalPoint, Offset.zero); updatedFocalPoint = null; expect(updatedDelta, isNull); expect(updatedPointerCount, 2); updatedPointerCount = null; expect(didEndScale, isFalse); // Zoom in by scrolling up. tester.route(pointer1.panZoomUpdate(Offset.zero, pan: const Offset(0, -200))); expect(didStartScale, isFalse); expect(updatedFocalPoint, Offset.zero); updatedFocalPoint = null; expect(updatedScale, math.e); updatedScale = null; expect(updatedDelta, Offset.zero); updatedDelta = null; expect(updatedPointerCount, 2); updatedPointerCount = null; expect(didEndScale, isFalse); // A horizontal scroll should do nothing. tester.route(pointer1.panZoomUpdate(Offset.zero, pan: const Offset(200, -200))); expect(didStartScale, isFalse); expect(updatedFocalPoint, Offset.zero); updatedFocalPoint = null; expect(updatedScale, math.e); updatedScale = null; expect(updatedDelta, Offset.zero); updatedDelta = null; expect(updatedPointerCount, 2); updatedPointerCount = null; expect(didEndScale, isFalse); // End. tester.route(pointer1.panZoomEnd()); expect(didStartScale, isFalse); expect(updatedFocalPoint, isNull); expect(updatedScale, isNull); expect(updatedDelta, isNull); expect(updatedPointerCount, isNull); expect(didEndScale, isTrue); didEndScale = false; // Try with a different trackpadScrollToScaleFactor scale.trackpadScrollToScaleFactor = const Offset(1/125, 0); final PointerPanZoomStartEvent start2 = pointer1.panZoomStart(Offset.zero); scale.addPointerPanZoom(start2); tester.closeArena(2); expect(didStartScale, isFalse); expect(updatedScale, isNull); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(updatedPointerCount, isNull); expect(didEndScale, isFalse); tester.route(start2); expect(didStartScale, isTrue); didStartScale = false; expect(updatedScale, isNull); expect(updatedFocalPoint, Offset.zero); updatedFocalPoint = null; expect(updatedDelta, isNull); expect(updatedPointerCount, 2); updatedPointerCount = null; expect(didEndScale, isFalse); // Zoom in by scrolling left. tester.route(pointer1.panZoomUpdate(Offset.zero, pan: const Offset(125, 0))); expect(didStartScale, isFalse); didStartScale = false; expect(updatedFocalPoint, Offset.zero); updatedFocalPoint = null; expect(updatedScale, math.e); updatedScale = null; expect(updatedDelta, Offset.zero); updatedDelta = null; expect(updatedPointerCount, 2); updatedPointerCount = null; expect(didEndScale, isFalse); // A vertical scroll should do nothing. tester.route(pointer1.panZoomUpdate(Offset.zero, pan: const Offset(125, 125))); expect(didStartScale, isFalse); expect(updatedFocalPoint, Offset.zero); updatedFocalPoint = null; expect(updatedScale, math.e); updatedScale = null; expect(updatedDelta, Offset.zero); updatedDelta = null; expect(updatedPointerCount, 2); updatedPointerCount = null; expect(didEndScale, isFalse); // End. tester.route(pointer1.panZoomEnd()); expect(didStartScale, isFalse); expect(updatedFocalPoint, isNull); expect(updatedScale, isNull); expect(updatedDelta, isNull); expect(updatedPointerCount, isNull); expect(didEndScale, isTrue); didEndScale = false; scale.dispose(); }); testGesture('scale ending velocity', (GestureTester tester) { final ScaleGestureRecognizer scale = ScaleGestureRecognizer( dragStartBehavior: DragStartBehavior.start, trackpadScrollCausesScale: true ); bool didStartScale = false; Offset? updatedFocalPoint; scale.onStart = (ScaleStartDetails details) { didStartScale = true; updatedFocalPoint = details.focalPoint; }; bool didEndScale = false; double? scaleEndVelocity; scale.onEnd = (ScaleEndDetails details) { didEndScale = true; scaleEndVelocity = details.scaleVelocity; }; final TestPointer pointer1 = TestPointer(2, PointerDeviceKind.trackpad); final PointerPanZoomStartEvent start = pointer1.panZoomStart(Offset.zero); scale.addPointerPanZoom(start); tester.closeArena(2); expect(didStartScale, isFalse); expect(updatedFocalPoint, isNull); expect(didEndScale, isFalse); tester.route(start); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, Offset.zero); updatedFocalPoint = null; expect(didEndScale, isFalse); // Zoom in by scrolling up. for (int i = 0; i < 100; i++) { tester.route(pointer1.panZoomUpdate( Offset.zero, pan: Offset(0, i * -10), timeStamp: Duration(milliseconds: i * 25) )); } // End. tester.route(pointer1.panZoomEnd(timeStamp: const Duration(milliseconds: 2500))); expect(didStartScale, isFalse); expect(updatedFocalPoint, isNull); expect(didEndScale, isTrue); didEndScale = false; expect(scaleEndVelocity, moreOrLessEquals(281.41454098027765)); scale.dispose(); }); testGesture('ScaleStartDetails and ScaleUpdateDetails callbacks should contain their event.timestamp', (GestureTester tester) { final ScaleGestureRecognizer scale = ScaleGestureRecognizer(); final TapGestureRecognizer tap = TapGestureRecognizer(); bool didStartScale = false; Offset? updatedFocalPoint; Duration? initialSourceTimestamp; scale.onStart = (ScaleStartDetails details) { didStartScale = true; updatedFocalPoint = details.focalPoint; initialSourceTimestamp = details.sourceTimeStamp; }; double? updatedScale; double? updatedHorizontalScale; double? updatedVerticalScale; Offset? updatedDelta; Duration? updatedSourceTimestamp; scale.onUpdate = (ScaleUpdateDetails details) { updatedScale = details.scale; updatedHorizontalScale = details.horizontalScale; updatedVerticalScale = details.verticalScale; updatedFocalPoint = details.focalPoint; updatedDelta = details.focalPointDelta; updatedSourceTimestamp = details.sourceTimeStamp; }; bool didEndScale = false; scale.onEnd = (ScaleEndDetails details) { didEndScale = true; }; bool didTap = false; tap.onTap = () { didTap = true; }; final TestPointer pointer1 = TestPointer(); final PointerDownEvent down = pointer1.down(Offset.zero, timeStamp: const Duration(milliseconds: 10)); scale.addPointer(down); tap.addPointer(down); tester.closeArena(1); expect(didStartScale, isFalse); expect(updatedScale, isNull); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(updatedSourceTimestamp, isNull); expect(didEndScale, isFalse); expect(didTap, isFalse); expect(initialSourceTimestamp, isNull); // One-finger panning. tester.route(down); expect(didStartScale, isFalse); expect(updatedScale, isNull); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(didEndScale, isFalse); expect(didTap, isFalse); expect(initialSourceTimestamp, isNull); tester.route(pointer1.move(const Offset(20.0, 30.0), timeStamp: const Duration(milliseconds: 20))); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, const Offset(20.0, 30.0)); updatedFocalPoint = null; expect(updatedScale, 1.0); updatedScale = null; expect(updatedDelta, const Offset(20.0, 30.0)); updatedDelta = null; expect(updatedSourceTimestamp, const Duration(milliseconds: 20)); updatedSourceTimestamp = null; expect(initialSourceTimestamp, const Duration(milliseconds: 10)); initialSourceTimestamp = null; expect(didEndScale, isFalse); expect(didTap, isFalse); expect(scale.pointerCount, 1); // Two-finger scaling. final TestPointer pointer2 = TestPointer(2); final PointerDownEvent down2 = pointer2.down(const Offset(10.0, 20.0, ), timeStamp: const Duration(milliseconds: 30)); scale.addPointer(down2); tap.addPointer(down2); tester.closeArena(2); tester.route(down2); expect(scale.pointerCount, 2); expect(didEndScale, isTrue); didEndScale = false; expect(updatedScale, isNull); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(updatedSourceTimestamp, isNull); expect(didStartScale, isFalse); expect(initialSourceTimestamp, isNull); // Zoom in. tester.route(pointer2.move(const Offset(0.0, 10.0), timeStamp: const Duration(milliseconds: 40))); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, const Offset(10.0, 20.0)); updatedFocalPoint = null; expect(updatedScale, 2.0); expect(updatedHorizontalScale, 2.0); expect(updatedVerticalScale, 2.0); expect(updatedDelta, const Offset(-5.0, -5.0)); expect(updatedSourceTimestamp, const Duration(milliseconds: 40)); expect(initialSourceTimestamp, const Duration(milliseconds: 40)); updatedScale = null; updatedHorizontalScale = null; updatedVerticalScale = null; updatedDelta = null; updatedSourceTimestamp = null; initialSourceTimestamp = null; expect(didEndScale, isFalse); expect(didTap, isFalse); // Zoom out. tester.route(pointer2.move(const Offset(15.0, 25.0), timeStamp: const Duration(milliseconds: 50))); expect(updatedFocalPoint, const Offset(17.5, 27.5)); expect(updatedScale, 0.5); expect(updatedHorizontalScale, 0.5); expect(updatedVerticalScale, 0.5); expect(updatedDelta, const Offset(7.5, 7.5)); expect(updatedSourceTimestamp, const Duration(milliseconds: 50)); expect(didTap, isFalse); expect(initialSourceTimestamp, isNull); // Horizontal scaling. tester.route(pointer2.move(const Offset(0.0, 20.0), timeStamp: const Duration(milliseconds: 60))); expect(updatedHorizontalScale, 2.0); expect(updatedVerticalScale, 1.0); expect(updatedSourceTimestamp, const Duration(milliseconds: 60)); expect(initialSourceTimestamp, isNull); // Vertical scaling. tester.route(pointer2.move(const Offset(10.0, 10.0), timeStamp: const Duration(milliseconds: 70))); expect(updatedHorizontalScale, 1.0); expect(updatedVerticalScale, 2.0); expect(updatedDelta, const Offset(5.0, -5.0)); expect(updatedSourceTimestamp, const Duration(milliseconds: 70)); expect(initialSourceTimestamp, isNull); tester.route(pointer2.move(const Offset(15.0, 25.0))); updatedFocalPoint = null; updatedScale = null; updatedDelta = null; updatedSourceTimestamp = null; // Three-finger scaling. final TestPointer pointer3 = TestPointer(3); final PointerDownEvent down3 = pointer3.down(const Offset(25.0, 35.0), timeStamp: const Duration(milliseconds: 80)); scale.addPointer(down3); tap.addPointer(down3); tester.closeArena(3); tester.route(down3); expect(didEndScale, isTrue); didEndScale = false; expect(updatedScale, isNull); expect(updatedFocalPoint, isNull); expect(updatedDelta, isNull); expect(didStartScale, isFalse); expect(initialSourceTimestamp, isNull); // Zoom in. tester.route(pointer3.move(const Offset(55.0, 65.0), timeStamp: const Duration(milliseconds: 90))); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, const Offset(30.0, 40.0)); updatedFocalPoint = null; expect(updatedScale, 5.0); updatedScale = null; expect(updatedDelta, const Offset(10.0, 10.0)); updatedDelta = null; expect(updatedSourceTimestamp, const Duration(milliseconds: 90)); updatedSourceTimestamp = null; expect(initialSourceTimestamp, const Duration(milliseconds: 90)); initialSourceTimestamp = null; expect(didEndScale, isFalse); expect(didTap, isFalse); // Return to original positions but with different fingers. tester.route(pointer1.move(const Offset(25.0, 35.0), timeStamp: const Duration(milliseconds: 100))); tester.route(pointer2.move(const Offset(20.0, 30.0), timeStamp: const Duration(milliseconds: 110))); tester.route(pointer3.move(const Offset(15.0, 25.0), timeStamp: const Duration(milliseconds: 120))); expect(didStartScale, isFalse); expect(updatedFocalPoint, const Offset(20.0, 30.0)); updatedFocalPoint = null; expect(updatedScale, 1.0); updatedScale = null; expect(updatedDelta!.dx, closeTo(-13.3, 0.1)); expect(updatedDelta!.dy, closeTo(-13.3, 0.1)); updatedDelta = null; expect(didEndScale, isFalse); expect(didTap, isFalse); expect(updatedSourceTimestamp, const Duration(milliseconds: 120)); updatedSourceTimestamp = null; expect(initialSourceTimestamp, isNull); tester.route(pointer1.up()); expect(didStartScale, isFalse); expect(updatedFocalPoint, isNull); expect(updatedScale, isNull); expect(updatedDelta, isNull); expect(didEndScale, isTrue); expect(updatedSourceTimestamp, isNull); expect(initialSourceTimestamp, isNull); didEndScale = false; expect(didTap, isFalse); // Continue scaling with two fingers. tester.route(pointer3.move(const Offset(10.0, 20.0), timeStamp: const Duration(milliseconds: 130))); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, const Offset(15.0, 25.0)); updatedFocalPoint = null; expect(updatedScale, 2.0); updatedScale = null; expect(updatedDelta, const Offset(-2.5, -2.5)); updatedDelta = null; expect(updatedSourceTimestamp, const Duration(milliseconds: 130)); updatedSourceTimestamp = null; expect(initialSourceTimestamp, const Duration(milliseconds: 130)); initialSourceTimestamp = null; // Continue rotating with two fingers. tester.route(pointer3.move(const Offset(30.0, 40.0), timeStamp: const Duration(milliseconds: 140))); expect(updatedFocalPoint, const Offset(25.0, 35.0)); updatedFocalPoint = null; expect(updatedScale, 2.0); updatedScale = null; expect(updatedDelta, const Offset(10.0, 10.0)); updatedDelta = null; expect(updatedSourceTimestamp, const Duration(milliseconds: 140)); updatedSourceTimestamp = null; expect(initialSourceTimestamp, isNull); tester.route(pointer3.move(const Offset(10.0, 20.0), timeStamp: const Duration(milliseconds: 140))); expect(updatedFocalPoint, const Offset(15.0, 25.0)); updatedFocalPoint = null; expect(updatedScale, 2.0); updatedScale = null; expect(updatedDelta, const Offset(-10.0, -10.0)); updatedDelta = null; expect(updatedSourceTimestamp, const Duration(milliseconds: 140)); updatedSourceTimestamp = null; expect(initialSourceTimestamp, isNull); tester.route(pointer2.up()); expect(didStartScale, isFalse); expect(updatedFocalPoint, isNull); expect(updatedScale, isNull); expect(updatedDelta, isNull); expect(updatedSourceTimestamp, isNull); expect(initialSourceTimestamp, isNull); expect(didEndScale, isTrue); didEndScale = false; expect(didTap, isFalse); // Continue panning with one finger. tester.route(pointer3.move(Offset.zero, timeStamp: const Duration(milliseconds: 150))); expect(didStartScale, isTrue); didStartScale = false; expect(updatedFocalPoint, Offset.zero); updatedFocalPoint = null; expect(updatedScale, 1.0); updatedScale = null; expect(updatedDelta, const Offset(-10.0, -20.0)); updatedDelta = null; expect(updatedSourceTimestamp, const Duration(milliseconds: 150)); updatedSourceTimestamp = null; expect(initialSourceTimestamp, const Duration(milliseconds: 150)); initialSourceTimestamp = null; // We are done. tester.route(pointer3.up()); expect(didStartScale, isFalse); expect(updatedFocalPoint, isNull); expect(updatedScale, isNull); expect(updatedDelta, isNull); expect(didEndScale, isTrue); expect(updatedSourceTimestamp, isNull); expect(initialSourceTimestamp, isNull); didEndScale = false; expect(didTap, isFalse); scale.dispose(); tap.dispose(); }); }
flutter/packages/flutter/test/gestures/scale_test.dart/0
{ "file_path": "flutter/packages/flutter/test/gestures/scale_test.dart", "repo_id": "flutter", "token_count": 22155 }
664
// 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 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; /// Adds the basic requirements for a Chip. Widget wrapForChip({ required Widget child, TextDirection textDirection = TextDirection.ltr, TextScaler textScaler = TextScaler.noScaling, Brightness brightness = Brightness.light, }) { return MaterialApp( theme: ThemeData(brightness: brightness), home: Directionality( textDirection: textDirection, child: MediaQuery( data: MediaQueryData(textScaler: textScaler), child: Material(child: child), ), ), ); } RenderBox getMaterialBox(WidgetTester tester, Finder type) { return tester.firstRenderObject<RenderBox>( find.descendant( of: type, matching: find.byType(CustomPaint), ), ); } Material getMaterial(WidgetTester tester) { return tester.widget<Material>( find.descendant( of: find.byType(ActionChip), matching: find.byType(Material), ), ); } IconThemeData getIconData(WidgetTester tester) { final IconTheme iconTheme = tester.firstWidget( find.descendant( of: find.byType(RawChip), matching: find.byType(IconTheme), ), ); return iconTheme.data; } DefaultTextStyle getLabelStyle(WidgetTester tester, String labelText) { return tester.widget( find.ancestor( of: find.text(labelText), matching: find.byType(DefaultTextStyle), ).first, ); } void checkChipMaterialClipBehavior(WidgetTester tester, Clip clipBehavior) { final Iterable<Material> materials = tester.widgetList<Material>(find.byType(Material)); // There should be two Material widgets, first Material is from the "_wrapForChip" and // last Material is from the "RawChip". expect(materials.length, 2); // The last Material from `RawChip` should have the clip behavior. expect(materials.last.clipBehavior, clipBehavior); } void main() { testWidgets('Material2 - ActionChip defaults', (WidgetTester tester) async { final ThemeData theme = ThemeData(useMaterial3: false); const String label = 'action chip'; // Test enabled ActionChip defaults. await tester.pumpWidget( MaterialApp( theme: theme, home: Material( child: Center( child: ActionChip( onPressed: () {}, label: const Text(label), ), ), ), ), ); // Test default chip size. expect(tester.getSize(find.byType(ActionChip)), const Size(178.0, 48.0)); // Test default label style. expect( getLabelStyle(tester, label).style.color, theme.textTheme.bodyLarge!.color!.withAlpha(0xde), ); Material chipMaterial = getMaterial(tester); expect(chipMaterial.elevation, 0); expect(chipMaterial.shadowColor, Colors.black); expect(chipMaterial.shape, const StadiumBorder()); ShapeDecoration decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration; expect(decoration.color, Colors.black.withAlpha(0x1f)); // Test disabled ActionChip defaults. await tester.pumpWidget( MaterialApp( theme: theme, home: const Material( child: ActionChip( label: Text(label), ), ), ), ); await tester.pumpAndSettle(); chipMaterial = getMaterial(tester); expect(chipMaterial.elevation, 0); expect(chipMaterial.shadowColor, Colors.black); expect(chipMaterial.shape, const StadiumBorder()); decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration; expect(decoration.color, Colors.black38); }); testWidgets('Material3 - ActionChip defaults', (WidgetTester tester) async { final ThemeData theme = ThemeData(); const String label = 'action chip'; // Test enabled ActionChip defaults. await tester.pumpWidget( MaterialApp( theme: theme, home: Material( child: Center( child: ActionChip( onPressed: () {}, label: const Text(label), ), ), ), ), ); // Test default chip size. expect( tester.getSize(find.byType(ActionChip)), within<Size>(distance: 0.01, from: const Size(189.1, 48.0)), ); // Test default label style. expect( getLabelStyle(tester, label).style.color!.value, theme.colorScheme.onSurface.value, ); Material chipMaterial = getMaterial(tester); expect(chipMaterial.elevation, 0); expect(chipMaterial.shadowColor, Colors.transparent); expect(chipMaterial.surfaceTintColor, Colors.transparent); expect( chipMaterial.shape, RoundedRectangleBorder( borderRadius: const BorderRadius.all(Radius.circular(8.0)), side: BorderSide(color: theme.colorScheme.outline), ), ); ShapeDecoration decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration; expect(decoration.color, null); // Test disabled ActionChip defaults. await tester.pumpWidget( MaterialApp( theme: theme, home: const Material( child: ActionChip( label: Text(label), ), ), ), ); await tester.pumpAndSettle(); chipMaterial = getMaterial(tester); expect(chipMaterial.elevation, 0); expect(chipMaterial.shadowColor, Colors.transparent); expect(chipMaterial.surfaceTintColor, Colors.transparent); expect( chipMaterial.shape, RoundedRectangleBorder( borderRadius: const BorderRadius.all(Radius.circular(8.0)), side: BorderSide(color: theme.colorScheme.onSurface.withOpacity(0.12)), ), ); decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration; expect(decoration.color, null); }); testWidgets('Material3 - ActionChip.elevated defaults', (WidgetTester tester) async { final ThemeData theme = ThemeData(); const String label = 'action chip'; // Test enabled ActionChip defaults. await tester.pumpWidget( MaterialApp( theme: theme, home: Material( child: Center( child: ActionChip.elevated( onPressed: () {}, label: const Text(label), ), ), ), ), ); // Test default chip size. expect( tester.getSize(find.byType(ActionChip)), within<Size>(distance: 0.01, from: const Size(189.1, 48.0)), ); // Test default label style. expect( getLabelStyle(tester, label).style.color!.value, theme.colorScheme.onSurface.value, ); Material chipMaterial = getMaterial(tester); expect(chipMaterial.elevation, 1); expect(chipMaterial.shadowColor, theme.colorScheme.shadow); expect(chipMaterial.surfaceTintColor, Colors.transparent); expect( chipMaterial.shape, const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(8.0)), side: BorderSide(color: Colors.transparent), ), ); ShapeDecoration decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration; expect(decoration.color, theme.colorScheme.surfaceContainerLow); // Test disabled ActionChip.elevated defaults. await tester.pumpWidget( MaterialApp( theme: theme, home: const Material( child: ActionChip.elevated( label: Text(label), ), ), ), ); await tester.pumpAndSettle(); chipMaterial = getMaterial(tester); expect(chipMaterial.elevation, 0); expect(chipMaterial.shadowColor, theme.colorScheme.shadow); expect(chipMaterial.surfaceTintColor, Colors.transparent); expect( chipMaterial.shape, const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(8.0)), side: BorderSide(color: Colors.transparent), ), ); decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration; expect(decoration.color, theme.colorScheme.onSurface.withOpacity(0.12)); }); testWidgets('ActionChip.color resolves material states', (WidgetTester tester) async { const Color disabledColor = Color(0xff00ff00); const Color backgroundColor = Color(0xff0000ff); final MaterialStateProperty<Color?> color = MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return disabledColor; } return backgroundColor; }); Widget buildApp({ required bool enabled, required bool selected }) { return wrapForChip( child: Column( children: <Widget>[ ActionChip( onPressed: enabled ? () { } : null, color: color, label: const Text('ActionChip'), ), ActionChip.elevated( onPressed: enabled ? () { } : null, color: color, label: const Text('ActionChip.elevated'), ), ], ), ); } // Test enabled state. await tester.pumpWidget(buildApp(enabled: true, selected: false)); // Enabled ActionChip should have the provided backgroundColor. expect( getMaterialBox(tester, find.byType(RawChip).first), paints..rrect(color: backgroundColor), ); // Enabled elevated ActionChip should have the provided backgroundColor. expect( getMaterialBox(tester, find.byType(RawChip).last), paints..rrect(color: backgroundColor), ); // Test disabled state. await tester.pumpWidget(buildApp(enabled: false, selected: false)); await tester.pumpAndSettle(); // Disabled ActionChip should have the provided disabledColor. expect( getMaterialBox(tester, find.byType(RawChip).first), paints..rrect(color: disabledColor), ); // Disabled elevated ActionChip should have the provided disabledColor. expect( getMaterialBox(tester, find.byType(RawChip).last), paints..rrect(color: disabledColor), ); }); testWidgets('ActionChip uses provided state color properties', (WidgetTester tester) async { const Color disabledColor = Color(0xff00ff00); const Color backgroundColor = Color(0xff0000ff); Widget buildApp({ required bool enabled, required bool selected }) { return wrapForChip( child: Column( children: <Widget>[ ActionChip( onPressed: enabled ? () { } : null, disabledColor: disabledColor, backgroundColor: backgroundColor, label: const Text('ActionChip'), ), ActionChip.elevated( onPressed: enabled ? () { } : null, disabledColor: disabledColor, backgroundColor: backgroundColor, label: const Text('ActionChip.elevated'), ), ], ), ); } // Test enabled state. await tester.pumpWidget(buildApp(enabled: true, selected: false)); // Enabled ActionChip should have the provided backgroundColor. expect( getMaterialBox(tester, find.byType(RawChip).first), paints..rrect(color: backgroundColor), ); // Enabled elevated ActionChip should have the provided backgroundColor. expect( getMaterialBox(tester, find.byType(RawChip).last), paints..rrect(color: backgroundColor), ); // Test disabled state. await tester.pumpWidget(buildApp(enabled: false, selected: false)); await tester.pumpAndSettle(); // Disabled ActionChip should have the provided disabledColor. expect( getMaterialBox(tester, find.byType(RawChip).first), paints..rrect(color: disabledColor), ); // Disabled elevated ActionChip should have the provided disabledColor. expect( getMaterialBox(tester, find.byType(RawChip).last), paints..rrect(color: disabledColor), ); }); testWidgets('ActionChip can be tapped', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Material( child: ActionChip( onPressed: () { }, label: const Text('action chip'), ), ), ), ); await tester.tap(find.byType(ActionChip)); expect(tester.takeException(), null); }); testWidgets('ActionChip clipBehavior properly passes through to the Material', (WidgetTester tester) async { const Text label = Text('label'); await tester.pumpWidget(wrapForChip(child: ActionChip(label: label, onPressed: () { }))); checkChipMaterialClipBehavior(tester, Clip.none); await tester.pumpWidget(wrapForChip(child: ActionChip(label: label, clipBehavior: Clip.antiAlias, onPressed: () { }))); checkChipMaterialClipBehavior(tester, Clip.antiAlias); }); testWidgets('ActionChip uses provided iconTheme', (WidgetTester tester) async { Widget buildChip({ IconThemeData? iconTheme }) { return MaterialApp( home: Material( child: ActionChip( iconTheme: iconTheme, avatar: const Icon(Icons.add), onPressed: () { }, label: const Text('action chip'), ), ), ); } // Test default icon theme. await tester.pumpWidget(buildChip()); expect(getIconData(tester).color, ThemeData().colorScheme.primary); // Test provided icon theme. await tester.pumpWidget(buildChip(iconTheme: const IconThemeData(color: Color(0xff00ff00)))); expect(getIconData(tester).color, const Color(0xff00ff00)); }); testWidgets('ActionChip avatar layout constraints can be customized', (WidgetTester tester) async { const double border = 1.0; const double iconSize = 18.0; const double labelPadding = 8.0; const double padding = 8.0; const Size labelSize = Size(100, 100); Widget buildChip({BoxConstraints? avatarBoxConstraints}) { return wrapForChip( child: Center( child: ActionChip( avatarBoxConstraints: avatarBoxConstraints, avatar: const Icon(Icons.favorite), label: Container( width: labelSize.width, height: labelSize.width, color: const Color(0xFFFF0000), ), ), ), ); } // Test default avatar layout constraints. await tester.pumpWidget(buildChip()); expect(tester.getSize(find.byType(ActionChip)).width, equals(234.0)); expect(tester.getSize(find.byType(ActionChip)).height, equals(118.0)); // Calculate the distance between avatar and chip edges. Offset chipTopLeft = tester.getTopLeft(find.byWidget(getMaterial(tester))); final Offset avatarCenter = tester.getCenter(find.byIcon(Icons.favorite)); expect(chipTopLeft.dx, avatarCenter.dx - (labelSize.width / 2) - padding - border); expect(chipTopLeft.dy, avatarCenter.dy - (labelSize.width / 2) - padding - border); // Calculate the distance between avatar and label. Offset labelTopLeft = tester.getTopLeft(find.byType(Container)); expect(labelTopLeft.dx, avatarCenter.dx + (labelSize.width / 2) + labelPadding); // Test custom avatar layout constraints. await tester.pumpWidget(buildChip(avatarBoxConstraints: const BoxConstraints.tightForFinite())); await tester.pump(); expect(tester.getSize(find.byType(ActionChip)).width, equals(152.0)); expect(tester.getSize(find.byType(ActionChip)).height, equals(118.0)); // Calculate the distance between avatar and chip edges. chipTopLeft = tester.getTopLeft(find.byWidget(getMaterial(tester))); expect(chipTopLeft.dx, avatarCenter.dx - (iconSize / 2) - padding - border); expect(chipTopLeft.dy, avatarCenter.dy - (labelSize.width / 2) - padding - border); // Calculate the distance between avatar and label. labelTopLeft = tester.getTopLeft(find.byType(Container)); expect(labelTopLeft.dx, avatarCenter.dx + (iconSize / 2) + labelPadding); }); }
flutter/packages/flutter/test/material/action_chip_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/action_chip_test.dart", "repo_id": "flutter", "token_count": 6260 }
665
// 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 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('MaterialBannerThemeData copyWith, ==, hashCode basics', () { expect(const MaterialBannerThemeData(), const MaterialBannerThemeData().copyWith()); expect(const MaterialBannerThemeData().hashCode, const MaterialBannerThemeData().copyWith().hashCode); }); test('MaterialBannerThemeData null fields by default', () { const MaterialBannerThemeData bannerTheme = MaterialBannerThemeData(); expect(bannerTheme.backgroundColor, null); expect(bannerTheme.surfaceTintColor, null); expect(bannerTheme.shadowColor, null); expect(bannerTheme.dividerColor, null); expect(bannerTheme.contentTextStyle, null); expect(bannerTheme.elevation, null); expect(bannerTheme.padding, null); expect(bannerTheme.leadingPadding, null); }); testWidgets('Default MaterialBannerThemeData debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const MaterialBannerThemeData().debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description, <String>[]); }); testWidgets('MaterialBannerThemeData implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const MaterialBannerThemeData( backgroundColor: Color(0xfffffff0), surfaceTintColor: Color(0xfffffff1), shadowColor: Color(0xfffffff2), dividerColor: Color(0xfffffff3), contentTextStyle: TextStyle(color: Color(0xfffffff4)), elevation: 4.0, padding: EdgeInsets.all(20.0), leadingPadding: EdgeInsets.only(left: 8.0), ).debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description, <String>[ 'backgroundColor: Color(0xfffffff0)', 'surfaceTintColor: Color(0xfffffff1)', 'shadowColor: Color(0xfffffff2)', 'dividerColor: Color(0xfffffff3)', 'contentTextStyle: TextStyle(inherit: true, color: Color(0xfffffff4))', 'elevation: 4.0', 'padding: EdgeInsets.all(20.0)', 'leadingPadding: EdgeInsets(8.0, 0.0, 0.0, 0.0)', ]); }); testWidgets('Material3 - Passing no MaterialBannerThemeData returns defaults', (WidgetTester tester) async { const String contentText = 'Content'; final ThemeData theme = ThemeData(useMaterial3: true); late final ThemeData localizedTheme; await tester.pumpWidget(MaterialApp( theme: theme, builder:(BuildContext context, Widget? child) { localizedTheme = Theme.of(context); return child!; }, home: Scaffold( body: MaterialBanner( content: const Text(contentText), leading: const Icon(Icons.umbrella), actions: <Widget>[ TextButton( child: const Text('Action'), onPressed: () { }, ), ], ), ), )); final Material material = _getMaterialFromText(tester, contentText); expect(material.color, theme.colorScheme.surfaceContainerLow); expect(material.surfaceTintColor, Colors.transparent); expect(material.shadowColor, null); expect(material.elevation, 0.0); final RenderParagraph content = _getTextRenderObjectFromDialog(tester, contentText); expect( content.text.style, localizedTheme.textTheme.bodyMedium, ); final Offset rowTopLeft = tester.getTopLeft(find.byType(Row)); final Offset materialTopLeft = tester.getTopLeft(_materialFinder()); final Offset leadingTopLeft = tester.getTopLeft(find.byIcon(Icons.umbrella)); expect(rowTopLeft.dy - materialTopLeft.dy, 2.0); // Default single line top padding. expect(rowTopLeft.dx - materialTopLeft.dx, 16.0); // Default single line start padding. expect(leadingTopLeft.dy - materialTopLeft.dy, 16); // Default leading padding. expect(leadingTopLeft.dx - materialTopLeft.dx, 16); // Default leading padding. final Divider divider = tester.widget<Divider>(find.byType(Divider)); expect(divider.color, theme.colorScheme.outlineVariant); }); testWidgets('Material3 - Passing no MaterialBannerThemeData returns defaults when presented by ScaffoldMessenger', (WidgetTester tester) async { const String contentText = 'Content'; const Key tapTarget = Key('tap-target'); final ThemeData theme = ThemeData(useMaterial3: true); late final ThemeData localizedTheme; await tester.pumpWidget(MaterialApp( theme: theme, home: Scaffold( body: Builder( builder: (BuildContext context) { localizedTheme = Theme.of(context); return GestureDetector( key: tapTarget, onTap: () { ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner( content: const Text(contentText), leading: const Icon(Icons.umbrella), actions: <Widget>[ TextButton( child: const Text('Action'), onPressed: () { }, ), ], )); }, behavior: HitTestBehavior.opaque, child: const SizedBox( height: 100.0, width: 100.0, ), ); }, ), ), )); await tester.tap(find.byKey(tapTarget)); await tester.pumpAndSettle(); final Material material = _getMaterialFromText(tester, contentText); expect(material.color, theme.colorScheme.surfaceContainerLow); expect(material.surfaceTintColor, Colors.transparent); expect(material.shadowColor, null); expect(material.elevation, 0.0); final RenderParagraph content = _getTextRenderObjectFromDialog(tester, contentText); expect( content.text.style, localizedTheme.textTheme.bodyMedium, ); final Offset rowTopLeft = tester.getTopLeft(find.byType(Row)); final Offset materialTopLeft = tester.getTopLeft(_materialFinder()); final Offset leadingTopLeft = tester.getTopLeft(find.byIcon(Icons.umbrella)); expect(rowTopLeft.dy - materialTopLeft.dy, 2.0); // Default single line top padding. expect(rowTopLeft.dx - materialTopLeft.dx, 16.0); // Default single line start padding. expect(leadingTopLeft.dy - materialTopLeft.dy, 16); // Default leading padding. expect(leadingTopLeft.dx - materialTopLeft.dx, 16); // Default leading padding. final Divider divider = tester.widget<Divider>(find.byType(Divider)); expect(divider.color, theme.colorScheme.outlineVariant); }); testWidgets('MaterialBanner uses values from MaterialBannerThemeData', (WidgetTester tester) async { final MaterialBannerThemeData bannerTheme = _bannerTheme(); const String contentText = 'Content'; await tester.pumpWidget(MaterialApp( theme: ThemeData(bannerTheme: bannerTheme), home: Scaffold( body: MaterialBanner( leading: const Icon(Icons.ac_unit), content: const Text(contentText), actions: <Widget>[ TextButton( child: const Text('Action'), onPressed: () { }, ), ], ), ), )); final Material material = _getMaterialFromText(tester, contentText); expect(material.color, bannerTheme.backgroundColor); expect(material.surfaceTintColor, bannerTheme.surfaceTintColor); expect(material.shadowColor, bannerTheme.shadowColor); expect(material.elevation, bannerTheme.elevation); final RenderParagraph content = _getTextRenderObjectFromDialog(tester, contentText); expect(content.text.style, bannerTheme.contentTextStyle); final Offset contentTopLeft = tester.getTopLeft(_textFinder(contentText)); final Offset materialTopLeft = tester.getTopLeft(_materialFinder()); final Offset leadingTopLeft = tester.getTopLeft(find.byIcon(Icons.ac_unit)); expect(contentTopLeft.dy - materialTopLeft.dy, 24); expect(contentTopLeft.dx - materialTopLeft.dx, 41); expect(leadingTopLeft.dy - materialTopLeft.dy, 19); expect(leadingTopLeft.dx - materialTopLeft.dx, 11); expect(find.byType(Divider), findsNothing); }); testWidgets('MaterialBanner uses values from MaterialBannerThemeData when presented by ScaffoldMessenger', (WidgetTester tester) async { final MaterialBannerThemeData bannerTheme = _bannerTheme(); const String contentText = 'Content'; const Key tapTarget = Key('tap-target'); await tester.pumpWidget(MaterialApp( theme: ThemeData(bannerTheme: bannerTheme), home: Scaffold( body: Builder( builder: (BuildContext context) { return GestureDetector( key: tapTarget, onTap: () { ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner( leading: const Icon(Icons.ac_unit), content: const Text(contentText), actions: <Widget>[ TextButton( child: const Text('Action'), onPressed: () { }, ), ], )); }, behavior: HitTestBehavior.opaque, child: const SizedBox( height: 100.0, width: 100.0, ), ); }, ), ), )); await tester.tap(find.byKey(tapTarget)); await tester.pumpAndSettle(); final Material material = _getMaterialFromText(tester, contentText); expect(material.color, bannerTheme.backgroundColor); expect(material.surfaceTintColor, bannerTheme.surfaceTintColor); expect(material.shadowColor, bannerTheme.shadowColor); expect(material.elevation, bannerTheme.elevation); final RenderParagraph content = _getTextRenderObjectFromDialog(tester, contentText); expect(content.text.style, bannerTheme.contentTextStyle); final Offset contentTopLeft = tester.getTopLeft(_textFinder(contentText)); final Offset materialTopLeft = tester.getTopLeft(_materialFinder()); final Offset leadingTopLeft = tester.getTopLeft(find.byIcon(Icons.ac_unit)); expect(contentTopLeft.dy - materialTopLeft.dy, 24); expect(contentTopLeft.dx - materialTopLeft.dx, 41); expect(leadingTopLeft.dy - materialTopLeft.dy, 19); expect(leadingTopLeft.dx - materialTopLeft.dx, 11); expect(find.byType(Divider), findsNothing); }); testWidgets('MaterialBanner widget properties take priority over theme', (WidgetTester tester) async { const Color backgroundColor = Colors.purple; const Color surfaceTintColor = Colors.red; const Color shadowColor = Colors.orange; const TextStyle textStyle = TextStyle(color: Colors.green); final MaterialBannerThemeData bannerTheme = _bannerTheme(); const String contentText = 'Content'; await tester.pumpWidget(MaterialApp( theme: ThemeData(bannerTheme: bannerTheme), home: Scaffold( body: MaterialBanner( backgroundColor: backgroundColor, surfaceTintColor: surfaceTintColor, shadowColor: shadowColor, elevation: 6.0, leading: const Icon(Icons.ac_unit), contentTextStyle: textStyle, content: const Text(contentText), padding: const EdgeInsets.all(10), leadingPadding: const EdgeInsets.all(12), actions: <Widget>[ TextButton( child: const Text('Action'), onPressed: () { }, ), ], ), ), )); final Material material = _getMaterialFromText(tester, contentText); expect(material.color, backgroundColor); expect(material.surfaceTintColor, surfaceTintColor); expect(material.shadowColor, shadowColor); expect(material.elevation, 6.0); final RenderParagraph content = _getTextRenderObjectFromDialog(tester, contentText); expect(content.text.style, textStyle); final Offset contentTopLeft = tester.getTopLeft(_textFinder(contentText)); final Offset materialTopLeft = tester.getTopLeft(_materialFinder()); final Offset leadingTopLeft = tester.getTopLeft(find.byIcon(Icons.ac_unit)); expect(contentTopLeft.dy - materialTopLeft.dy, 29); expect(contentTopLeft.dx - materialTopLeft.dx, 58); expect(leadingTopLeft.dy - materialTopLeft.dy, 24); expect(leadingTopLeft.dx - materialTopLeft.dx, 22); expect(find.byType(Divider), findsNothing); }); testWidgets('MaterialBanner widget properties take priority over theme when presented by ScaffoldMessenger', (WidgetTester tester) async { const Color backgroundColor = Colors.purple; const double elevation = 6.0; const TextStyle textStyle = TextStyle(color: Colors.green); final MaterialBannerThemeData bannerTheme = _bannerTheme(); const String contentText = 'Content'; const Key tapTarget = Key('tap-target'); await tester.pumpWidget(MaterialApp( theme: ThemeData(bannerTheme: bannerTheme), home: Scaffold( body: Builder( builder: (BuildContext context) { return GestureDetector( key: tapTarget, onTap: () { ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner( backgroundColor: backgroundColor, elevation: elevation, leading: const Icon(Icons.ac_unit), contentTextStyle: textStyle, content: const Text(contentText), padding: const EdgeInsets.all(10), leadingPadding: const EdgeInsets.all(12), actions: <Widget>[ TextButton( child: const Text('Action'), onPressed: () { }, ), ], )); }, behavior: HitTestBehavior.opaque, child: const SizedBox( height: 100.0, width: 100.0, ), ); }, ), ), )); await tester.tap(find.byKey(tapTarget)); await tester.pumpAndSettle(); final Material material = _getMaterialFromText(tester, contentText); expect(material.color, backgroundColor); expect(material.elevation, elevation); final RenderParagraph content = _getTextRenderObjectFromDialog(tester, contentText); expect(content.text.style, textStyle); final Offset contentTopLeft = tester.getTopLeft(_textFinder(contentText)); final Offset materialTopLeft = tester.getTopLeft(_materialFinder()); final Offset leadingTopLeft = tester.getTopLeft(find.byIcon(Icons.ac_unit)); expect(contentTopLeft.dy - materialTopLeft.dy, 29); expect(contentTopLeft.dx - materialTopLeft.dx, 58); expect(leadingTopLeft.dy - materialTopLeft.dy, 24); expect(leadingTopLeft.dx - materialTopLeft.dx, 22); expect(find.byType(Divider), findsNothing); }); testWidgets('MaterialBanner uses color scheme when necessary', (WidgetTester tester) async { final ColorScheme colorScheme = const ColorScheme.light().copyWith(surface: Colors.purple); const String contentText = 'Content'; await tester.pumpWidget(MaterialApp( theme: ThemeData(colorScheme: colorScheme), home: Scaffold( body: MaterialBanner( content: const Text(contentText), actions: <Widget>[ TextButton( child: const Text('Action'), onPressed: () { }, ), ], ), ), )); final Material material = _getMaterialFromText(tester, contentText); expect(material.color, colorScheme.surfaceContainerLow); }); testWidgets('MaterialBanner uses color scheme when necessary when presented by ScaffoldMessenger', (WidgetTester tester) async { final ColorScheme colorScheme = const ColorScheme.light().copyWith(surface: Colors.purple); const String contentText = 'Content'; const Key tapTarget = Key('tap-target'); await tester.pumpWidget(MaterialApp( theme: ThemeData(colorScheme: colorScheme), home: Scaffold( body: Builder( builder: (BuildContext context) { return GestureDetector( key: tapTarget, onTap: () { ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner( content: const Text(contentText), actions: <Widget>[ TextButton( child: const Text('Action'), onPressed: () { }, ), ], )); }, behavior: HitTestBehavior.opaque, child: const SizedBox( height: 100.0, width: 100.0, ), ); }, ), ), )); await tester.tap(find.byKey(tapTarget)); await tester.pumpAndSettle(); final Material material = _getMaterialFromText(tester, contentText); expect(material.color, colorScheme.surfaceContainerLow); }); group('Material 2', () { // These tests are only relevant for Material 2. Once Material 2 // support is deprecated and the APIs are removed, these tests // can be deleted. testWidgets('Material2 - Passing no MaterialBannerThemeData returns defaults', (WidgetTester tester) async { const String contentText = 'Content'; await tester.pumpWidget(MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: MaterialBanner( content: const Text(contentText), leading: const Icon(Icons.umbrella), actions: <Widget>[ TextButton( child: const Text('Action'), onPressed: () { }, ), ], ), ), )); final Material material = _getMaterialFromText(tester, contentText); expect(material.color, const Color(0xffffffff)); expect(material.surfaceTintColor, null); expect(material.shadowColor, null); expect(material.elevation, 0.0); final RenderParagraph content = _getTextRenderObjectFromDialog(tester, contentText); // Default value for ThemeData.typography is Typography.material2014() expect( content.text.style, Typography.material2014().englishLike.bodyText2!.merge( Typography.material2014().black.bodyText2, ), ); final Offset rowTopLeft = tester.getTopLeft(find.byType(Row)); final Offset materialTopLeft = tester.getTopLeft(_materialFinder()); final Offset leadingTopLeft = tester.getTopLeft(find.byIcon(Icons.umbrella)); expect(rowTopLeft.dy - materialTopLeft.dy, 2.0); // Default single line top padding. expect(rowTopLeft.dx - materialTopLeft.dx, 16.0); // Default single line start padding. expect(leadingTopLeft.dy - materialTopLeft.dy, 16); // Default leading padding. expect(leadingTopLeft.dx - materialTopLeft.dx, 16); // Default leading padding. final Divider divider = tester.widget<Divider>(find.byType(Divider)); expect(divider.color, null); }); testWidgets('Material2 - Passing no MaterialBannerThemeData returns defaults when presented by ScaffoldMessenger', (WidgetTester tester) async { const String contentText = 'Content'; const Key tapTarget = Key('tap-target'); await tester.pumpWidget(MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: Builder( builder: (BuildContext context) { return GestureDetector( key: tapTarget, onTap: () { ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner( content: const Text(contentText), leading: const Icon(Icons.umbrella), actions: <Widget>[ TextButton( child: const Text('Action'), onPressed: () { }, ), ], )); }, behavior: HitTestBehavior.opaque, child: const SizedBox( height: 100.0, width: 100.0, ), ); }, ), ), )); await tester.tap(find.byKey(tapTarget)); await tester.pumpAndSettle(); final Material material = _getMaterialFromText(tester, contentText); expect(material.color, const Color(0xffffffff)); expect(material.surfaceTintColor, null); expect(material.shadowColor, null); expect(material.elevation, 0.0); final RenderParagraph content = _getTextRenderObjectFromDialog(tester, contentText); // Default value for ThemeData.typography is Typography.material2014() expect( content.text.style, Typography.material2014().englishLike.bodyText2!.merge( Typography.material2014().black.bodyText2, ), ); final Offset rowTopLeft = tester.getTopLeft(find.byType(Row)); final Offset materialTopLeft = tester.getTopLeft(_materialFinder()); final Offset leadingTopLeft = tester.getTopLeft(find.byIcon(Icons.umbrella)); expect(rowTopLeft.dy - materialTopLeft.dy, 2.0); // Default single line top padding. expect(rowTopLeft.dx - materialTopLeft.dx, 16.0); // Default single line start padding. expect(leadingTopLeft.dy - materialTopLeft.dy, 16); // Default leading padding. expect(leadingTopLeft.dx - materialTopLeft.dx, 16); // Default leading padding. final Divider divider = tester.widget<Divider>(find.byType(Divider)); expect(divider.color, null); }); }); } MaterialBannerThemeData _bannerTheme() { return const MaterialBannerThemeData( backgroundColor: Colors.orange, surfaceTintColor: Colors.yellow, shadowColor: Colors.red, dividerColor: Colors.green, contentTextStyle: TextStyle(color: Colors.pink), elevation: 4.0, padding: EdgeInsets.all(5), leadingPadding: EdgeInsets.all(6), ); } Material _getMaterialFromText(WidgetTester tester, String text) { return tester.widget<Material>(find.widgetWithText(Material, text).first); } Finder _materialFinder() { return find.descendant(of: find.byType(MaterialBanner), matching: find.byType(Material)).first; } RenderParagraph _getTextRenderObjectFromDialog(WidgetTester tester, String text) { return tester.element<StatelessElement>(_textFinder(text)).renderObject! as RenderParagraph; } Finder _textFinder(String text) { return find.descendant(of: find.byType(MaterialBanner), matching: find.text(text)); }
flutter/packages/flutter/test/material/banner_theme_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/banner_theme_test.dart", "repo_id": "flutter", "token_count": 9458 }
666
// 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 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('CheckboxThemeData copyWith, ==, hashCode basics', () { expect(const CheckboxThemeData(), const CheckboxThemeData().copyWith()); expect(const CheckboxThemeData().hashCode, const CheckboxThemeData().copyWith().hashCode); }); test('CheckboxThemeData lerp special cases', () { expect(CheckboxThemeData.lerp(null, null, 0), const CheckboxThemeData()); const CheckboxThemeData data = CheckboxThemeData(); expect(identical(CheckboxThemeData.lerp(data, data, 0.5), data), true); }); test('CheckboxThemeData defaults', () { const CheckboxThemeData themeData = CheckboxThemeData(); expect(themeData.mouseCursor, null); expect(themeData.fillColor, null); expect(themeData.checkColor, null); expect(themeData.overlayColor, null); expect(themeData.splashRadius, null); expect(themeData.materialTapTargetSize, null); expect(themeData.visualDensity, null); const CheckboxTheme theme = CheckboxTheme(data: CheckboxThemeData(), child: SizedBox()); expect(theme.data.mouseCursor, null); expect(theme.data.fillColor, null); expect(theme.data.checkColor, null); expect(theme.data.overlayColor, null); expect(theme.data.splashRadius, null); expect(theme.data.materialTapTargetSize, null); expect(theme.data.visualDensity, null); }); testWidgets('Default CheckboxThemeData debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const CheckboxThemeData().debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description, <String>[]); }); testWidgets('CheckboxThemeData implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const CheckboxThemeData( mouseCursor: MaterialStatePropertyAll<MouseCursor?>(SystemMouseCursors.click), fillColor: MaterialStatePropertyAll<Color>(Color(0xfffffff0)), checkColor: MaterialStatePropertyAll<Color>(Color(0xfffffff1)), overlayColor: MaterialStatePropertyAll<Color>(Color(0xfffffff2)), splashRadius: 1.0, materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, visualDensity: VisualDensity.standard, ).debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect( description, equalsIgnoringHashCodes(<String>[ 'mouseCursor: WidgetStatePropertyAll(SystemMouseCursor(click))', 'fillColor: WidgetStatePropertyAll(Color(0xfffffff0))', 'checkColor: WidgetStatePropertyAll(Color(0xfffffff1))', 'overlayColor: WidgetStatePropertyAll(Color(0xfffffff2))', 'splashRadius: 1.0', 'materialTapTargetSize: MaterialTapTargetSize.shrinkWrap', 'visualDensity: VisualDensity#00000(h: 0.0, v: 0.0)', ]), ); }); testWidgets('Checkbox is themeable', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; const MouseCursor mouseCursor = SystemMouseCursors.text; const Color defaultFillColor = Color(0xfffffff0); const Color selectedFillColor = Color(0xfffffff1); const Color defaultCheckColor = Color(0xfffffff2); const Color focusedCheckColor = Color(0xfffffff3); const Color focusOverlayColor = Color(0xfffffff4); const Color hoverOverlayColor = Color(0xfffffff5); const double splashRadius = 1.0; const MaterialTapTargetSize materialTapTargetSize = MaterialTapTargetSize.shrinkWrap; const VisualDensity visualDensity = VisualDensity(vertical: 1.0, horizontal: 1.0); Widget buildCheckbox({bool selected = false, bool autofocus = false}) { return MaterialApp( theme: ThemeData( checkboxTheme: CheckboxThemeData( mouseCursor: const MaterialStatePropertyAll<MouseCursor?>(mouseCursor), fillColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return selectedFillColor; } return defaultFillColor; }), checkColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.focused)) { return focusedCheckColor; } return defaultCheckColor; }), overlayColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.focused)) { return focusOverlayColor; } if (states.contains(MaterialState.hovered)) { return hoverOverlayColor; } return null; }), splashRadius: splashRadius, materialTapTargetSize: materialTapTargetSize, visualDensity: visualDensity, ), ), home: Scaffold( body: Checkbox( onChanged: (bool? value) {}, value: selected, autofocus: autofocus, ), ), ); } // Checkbox. await tester.pumpWidget(buildCheckbox()); await tester.pumpAndSettle(); expect(_getCheckboxMaterial(tester), paints..path(color: defaultFillColor)); // Size from MaterialTapTargetSize.shrinkWrap with added VisualDensity. expect(tester.getSize(find.byType(Checkbox)), const Size(40.0, 40.0) + visualDensity.baseSizeAdjustment); // Selected checkbox. await tester.pumpWidget(buildCheckbox(selected: true)); await tester.pumpAndSettle(); expect(_getCheckboxMaterial(tester), paints..path(color: selectedFillColor)); expect(_getCheckboxMaterial(tester), paints..path(color: selectedFillColor)..path(color: defaultCheckColor)); // Checkbox with hover. await tester.pumpWidget(buildCheckbox()); await _pointGestureToCheckbox(tester); await tester.pumpAndSettle(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); expect(_getCheckboxMaterial(tester), paints..circle(color: hoverOverlayColor)); // Checkbox with focus. await tester.pumpWidget(buildCheckbox(autofocus: true, selected: true)); await tester.pumpAndSettle(); expect(_getCheckboxMaterial(tester), paints..circle(color: focusOverlayColor, radius: splashRadius)); expect(_getCheckboxMaterial(tester), paints..path(color: selectedFillColor)..path(color: focusedCheckColor)); }); testWidgets('Checkbox properties are taken over the theme values', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; const MouseCursor themeMouseCursor = SystemMouseCursors.click; const Color themeDefaultFillColor = Color(0xfffffff0); const Color themeSelectedFillColor = Color(0xfffffff1); const Color themeCheckColor = Color(0xfffffff2); const Color themeFocusOverlayColor = Color(0xfffffff3); const Color themeHoverOverlayColor = Color(0xfffffff4); const double themeSplashRadius = 1.0; const MaterialTapTargetSize themeMaterialTapTargetSize = MaterialTapTargetSize.padded; const VisualDensity themeVisualDensity = VisualDensity.standard; const MouseCursor mouseCursor = SystemMouseCursors.text; const Color defaultFillColor = Color(0xfffffff5); const Color selectedFillColor = Color(0xfffffff6); const Color checkColor = Color(0xfffffff7); const Color focusColor = Color(0xfffffff8); const Color hoverColor = Color(0xfffffff9); const double splashRadius = 2.0; const MaterialTapTargetSize materialTapTargetSize = MaterialTapTargetSize.shrinkWrap; const VisualDensity visualDensity = VisualDensity.standard; Widget buildCheckbox({bool selected = false, bool autofocus = false}) { return MaterialApp( theme: ThemeData( checkboxTheme: CheckboxThemeData( mouseCursor: const MaterialStatePropertyAll<MouseCursor?>(themeMouseCursor), fillColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return themeSelectedFillColor; } return themeDefaultFillColor; }), checkColor: const MaterialStatePropertyAll<Color?>(themeCheckColor), overlayColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.focused)) { return themeFocusOverlayColor; } if (states.contains(MaterialState.hovered)) { return themeHoverOverlayColor; } return null; }), splashRadius: themeSplashRadius, materialTapTargetSize: themeMaterialTapTargetSize, visualDensity: themeVisualDensity, ), ), home: Scaffold( body: Checkbox( onChanged: (bool? value) { }, value: selected, autofocus: autofocus, mouseCursor: mouseCursor, fillColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return selectedFillColor; } return defaultFillColor; }), checkColor: checkColor, focusColor: focusColor, hoverColor: hoverColor, splashRadius: splashRadius, materialTapTargetSize: materialTapTargetSize, visualDensity: visualDensity, ), ), ); } // Checkbox. await tester.pumpWidget(buildCheckbox()); await tester.pumpAndSettle(); expect(_getCheckboxMaterial(tester), paints..path(color: defaultFillColor)); // Size from MaterialTapTargetSize.shrinkWrap with added VisualDensity. expect(tester.getSize(find.byType(Checkbox)), const Size(40.0, 40.0) + visualDensity.baseSizeAdjustment); // Selected checkbox. await tester.pumpWidget(buildCheckbox(selected: true)); await tester.pumpAndSettle(); expect(_getCheckboxMaterial(tester), paints..path(color: selectedFillColor)); expect(_getCheckboxMaterial(tester), paints..path(color: selectedFillColor)..path(color: checkColor)); // Checkbox with hover. await tester.pumpWidget(buildCheckbox()); await _pointGestureToCheckbox(tester); await tester.pumpAndSettle(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); expect(_getCheckboxMaterial(tester), paints..circle(color: hoverColor)); // Checkbox with focus. await tester.pumpWidget(buildCheckbox(autofocus: true)); await tester.pumpAndSettle(); expect(_getCheckboxMaterial(tester), paints..circle(color: focusColor, radius: splashRadius)); }); testWidgets('Checkbox activeColor property is taken over the theme', (WidgetTester tester) async { const Color themeSelectedFillColor = Color(0xfffffff1); const Color themeDefaultFillColor = Color(0xfffffff0); const Color selectedFillColor = Color(0xfffffff6); Widget buildCheckbox({bool selected = false}) { return MaterialApp( theme: ThemeData( checkboxTheme: CheckboxThemeData( fillColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return themeSelectedFillColor; } return themeDefaultFillColor; }), ), ), home: Scaffold( body: Checkbox( onChanged: (bool? value) { }, value: selected, activeColor: selectedFillColor, ), ), ); } // Unselected checkbox. await tester.pumpWidget(buildCheckbox()); await tester.pumpAndSettle(); expect(_getCheckboxMaterial(tester), paints..path(color: themeDefaultFillColor)); // Selected checkbox. await tester.pumpWidget(buildCheckbox(selected: true)); await tester.pumpAndSettle(); expect(_getCheckboxMaterial(tester), paints..path(color: selectedFillColor)); }); testWidgets('Checkbox theme overlay color resolves in active/pressed states', (WidgetTester tester) async { const Color activePressedOverlayColor = Color(0xFF000001); const Color inactivePressedOverlayColor = Color(0xFF000002); Color? getOverlayColor(Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { if (states.contains(MaterialState.selected)) { return activePressedOverlayColor; } return inactivePressedOverlayColor; } return null; } const double splashRadius = 24.0; Widget buildCheckbox({required bool active}) { return MaterialApp( theme: ThemeData( checkboxTheme: CheckboxThemeData( overlayColor: MaterialStateProperty.resolveWith(getOverlayColor), splashRadius: splashRadius, ), ), home: Scaffold( body: Checkbox( value: active, onChanged: (_) { }, ), ), ); } await tester.pumpWidget(buildCheckbox(active: false)); final TestGesture gesture1 = await tester.startGesture(tester.getCenter(find.byType(Checkbox))); await tester.pumpAndSettle(); expect( _getCheckboxMaterial(tester), paints ..circle( color: inactivePressedOverlayColor, radius: splashRadius, ), reason: 'Inactive pressed Checkbox should have overlay color: $inactivePressedOverlayColor', ); await tester.pumpWidget(buildCheckbox(active: true)); final TestGesture gesture2 = await tester.startGesture(tester.getCenter(find.byType(Checkbox))); await tester.pumpAndSettle(); expect( _getCheckboxMaterial(tester), paints ..circle( color: activePressedOverlayColor, radius: splashRadius, ), reason: 'Active pressed Checkbox should have overlay color: $activePressedOverlayColor', ); // Finish gesture to release resources. await gesture1.up(); await gesture2.up(); await tester.pumpAndSettle(); }); testWidgets('Local CheckboxTheme can override global CheckboxTheme', (WidgetTester tester) async { const Color globalThemeFillColor = Color(0xfffffff1); const Color globalThemeCheckColor = Color(0xff000000); const Color localThemeFillColor = Color(0xffff0000); const Color localThemeCheckColor = Color(0xffffffff); Widget buildCheckbox({required bool active}) { return MaterialApp( theme: ThemeData( checkboxTheme: const CheckboxThemeData( checkColor: MaterialStatePropertyAll<Color>(globalThemeCheckColor), fillColor: MaterialStatePropertyAll<Color>(globalThemeFillColor), ), ), home: Scaffold( body: CheckboxTheme( data: const CheckboxThemeData( fillColor: MaterialStatePropertyAll<Color>(localThemeFillColor), checkColor: MaterialStatePropertyAll<Color>(localThemeCheckColor), ), child: Checkbox( value: active, onChanged: (_) { }, ), ), ), ); } await tester.pumpWidget(buildCheckbox(active: true)); await tester.pumpAndSettle(); expect(_getCheckboxMaterial(tester), paints..path(color: localThemeFillColor)); expect(_getCheckboxMaterial(tester), paints..path(color: localThemeFillColor)..path(color: localThemeCheckColor)); }); test('CheckboxThemeData lerp with null parameters', () { final CheckboxThemeData lerped = CheckboxThemeData.lerp(null, null, 0.25); expect(lerped.mouseCursor, null); expect(lerped.fillColor, null); expect(lerped.checkColor, null); expect(lerped.overlayColor, null); expect(lerped.splashRadius, null); expect(lerped.materialTapTargetSize, null); expect(lerped.visualDensity, null); expect(lerped.shape, null); expect(lerped.side, null); }); test('CheckboxThemeData lerp from populated to null parameters', () { final CheckboxThemeData theme = CheckboxThemeData( fillColor: MaterialStateProperty.all(const Color(0xfffffff0)), checkColor: MaterialStateProperty.all(const Color(0xfffffff1)), overlayColor: MaterialStateProperty.all(const Color(0xfffffff2)), splashRadius: 3.0, materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, visualDensity: const VisualDensity(vertical: 1.0, horizontal: 1.0), shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))), side: const BorderSide(width: 4.0), ); final CheckboxThemeData lerped = CheckboxThemeData.lerp(theme, null, 0.5); expect(lerped.fillColor!.resolve(<MaterialState>{}), const Color(0x80fffff0)); expect(lerped.checkColor!.resolve(<MaterialState>{}), const Color(0x80fffff1)); expect(lerped.overlayColor!.resolve(<MaterialState>{}), const Color(0x80fffff2)); expect(lerped.splashRadius, 1.5); expect(lerped.materialTapTargetSize, null); expect(lerped.visualDensity, null); expect(lerped.shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2.0)))); // Returns null if either lerp value is null. expect(lerped.side, null); }); test('CheckboxThemeData lerp from populated parameters', () { final CheckboxThemeData themeA = CheckboxThemeData( fillColor: MaterialStateProperty.all(const Color(0xfffffff0)), checkColor: MaterialStateProperty.all(const Color(0xfffffff1)), overlayColor: MaterialStateProperty.all(const Color(0xfffffff2)), splashRadius: 3.0, materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, visualDensity: const VisualDensity(vertical: 1.0, horizontal: 1.0), shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))), side: const BorderSide(width: 4.0), ); final CheckboxThemeData themeB = CheckboxThemeData( fillColor: MaterialStateProperty.all(const Color(0xfffffff3)), checkColor: MaterialStateProperty.all(const Color(0xfffffff4)), overlayColor: MaterialStateProperty.all(const Color(0xfffffff5)), splashRadius: 9.0, materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, visualDensity: const VisualDensity(vertical: 2.0, horizontal: 2.0), shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(1.0))), side: const BorderSide(width: 3.0), ); final CheckboxThemeData lerped = CheckboxThemeData.lerp(themeA, themeB, 0.5); expect(lerped.fillColor!.resolve(<MaterialState>{}), const Color(0xfffffff1)); expect(lerped.checkColor!.resolve(<MaterialState>{}), const Color(0xfffffff2)); expect(lerped.overlayColor!.resolve(<MaterialState>{}), const Color(0xfffffff3)); expect(lerped.splashRadius, 6); expect(lerped.materialTapTargetSize, MaterialTapTargetSize.shrinkWrap); expect(lerped.visualDensity, const VisualDensity(vertical: 2.0, horizontal: 2.0)); expect(lerped.shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2.5)))); expect(lerped.side, const BorderSide(width: 3.5)); }); } Future<void> _pointGestureToCheckbox(WidgetTester tester) async { final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); addTearDown(gesture.removePointer); await gesture.moveTo(tester.getCenter(find.byType(Checkbox))); } MaterialInkController? _getCheckboxMaterial(WidgetTester tester) { return Material.of(tester.element(find.byType(Checkbox))); }
flutter/packages/flutter/test/material/checkbox_theme_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/checkbox_theme_test.dart", "repo_id": "flutter", "token_count": 7952 }
667
// 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:ui'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import '../widgets/semantics_tester.dart'; MaterialApp _buildAppWithDialog( Widget dialog, { ThemeData? theme, double textScaleFactor = 1.0, TraversalEdgeBehavior? traversalEdgeBehavior, }) { return MaterialApp( theme: theme, home: Material( child: Builder( builder: (BuildContext context) { return Center( child: ElevatedButton( child: const Text('X'), onPressed: () { showDialog<void>( context: context, traversalEdgeBehavior: traversalEdgeBehavior, builder: (BuildContext context) { return MediaQuery.withClampedTextScaling( minScaleFactor: textScaleFactor, maxScaleFactor: textScaleFactor, child: dialog, ); }, ); }, ), ); }, ), ), ); } Material _getMaterialFromDialog(WidgetTester tester) { return tester.widget<Material>(find.descendant(of: find.byType(Dialog), matching: find.byType(Material))); } RenderParagraph _getTextRenderObjectFromDialog(WidgetTester tester, String text) { return tester.element<StatelessElement>(find.descendant(of: find.byType(Dialog), matching: find.text(text))).renderObject! as RenderParagraph; } // What was the AlertDialog's ButtonBar when many of these tests were written, // is now a Padding widget with an OverflowBar child. The Padding widget's size // and location match the original ButtonBar's size and location. Finder _findOverflowBar() { return find.ancestor(of: find.byType(OverflowBar), matching: find.byType(Padding)).first; } const ShapeBorder _defaultM2DialogShape = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))); final ShapeBorder _defaultM3DialogShape = RoundedRectangleBorder(borderRadius: BorderRadius.circular(28.0)); void main() { final ThemeData material3Theme = ThemeData(useMaterial3: true, brightness: Brightness.dark); final ThemeData material2Theme = ThemeData(useMaterial3: false, brightness: Brightness.dark); testWidgets('Dialog is scrollable', (WidgetTester tester) async { bool didPressOk = false; final AlertDialog dialog = AlertDialog( content: Container( height: 5000.0, width: 300.0, color: Colors.green[500], ), actions: <Widget>[ TextButton( onPressed: () { didPressOk = true; }, child: const Text('OK'), ), ], ); await tester.pumpWidget(_buildAppWithDialog(dialog)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); expect(didPressOk, false); await tester.tap(find.text('OK')); expect(didPressOk, true); }); testWidgets('Dialog background color from AlertDialog', (WidgetTester tester) async { const Color customColor = Colors.pink; const AlertDialog dialog = AlertDialog( backgroundColor: customColor, actions: <Widget>[ ], ); await tester.pumpWidget(_buildAppWithDialog(dialog, theme: ThemeData(brightness: Brightness.dark))); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Material materialWidget = _getMaterialFromDialog(tester); expect(materialWidget.color, customColor); }); testWidgets('Material2 - Dialog Defaults', (WidgetTester tester) async { const AlertDialog dialog = AlertDialog( title: Text('Title'), content: Text('Y'), actions: <Widget>[ ], ); await tester.pumpWidget(_buildAppWithDialog(dialog, theme: material2Theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Material materialWidget = _getMaterialFromDialog(tester); expect(materialWidget.color, Colors.grey[800]); expect(materialWidget.shape, _defaultM2DialogShape); expect(materialWidget.elevation, 24.0); final Offset bottomLeft = tester.getBottomLeft( find.descendant(of: find.byType(Dialog), matching: find.byType(Material)), ); expect(bottomLeft.dy, 360.0); }); testWidgets('Material3 - Dialog Defaults', (WidgetTester tester) async { const AlertDialog dialog = AlertDialog( title: Text('Title'), content: Text('Y'), actions: <Widget>[ ], ); await tester.pumpWidget(_buildAppWithDialog(dialog, theme: material3Theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Material material3Widget = _getMaterialFromDialog(tester); expect(material3Widget.color, material3Theme.colorScheme.surface); expect(material3Widget.shape, _defaultM3DialogShape); expect(material3Widget.elevation, 6.0); }); testWidgets('Material2 - Dialog.fullscreen Defaults', (WidgetTester tester) async { const String dialogTextM2 = 'Fullscreen Dialog - M2'; await tester.pumpWidget(_buildAppWithDialog( theme: material2Theme, const Dialog.fullscreen( child: Text(dialogTextM2), ), )); await tester.tap(find.text('X')); await tester.pumpAndSettle(); expect(find.text(dialogTextM2), findsOneWidget); final Material materialWidget = _getMaterialFromDialog(tester); expect(materialWidget.color, Colors.grey[800]); // Try to dismiss the fullscreen dialog with the escape key. await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pumpAndSettle(); expect(find.text(dialogTextM2), findsNothing); }); testWidgets('Material3 - Dialog.fullscreen Defaults', (WidgetTester tester) async { const String dialogTextM3 = 'Fullscreen Dialog - M3'; await tester.pumpWidget(_buildAppWithDialog( theme: material3Theme, const Dialog.fullscreen( child: Text(dialogTextM3), ), )); await tester.tap(find.text('X')); await tester.pumpAndSettle(); expect(find.text(dialogTextM3), findsOneWidget); final Material materialWidget = _getMaterialFromDialog(tester); expect(materialWidget.color, material3Theme.colorScheme.surface); // Try to dismiss the fullscreen dialog with the escape key. await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pumpAndSettle(); expect(find.text(dialogTextM3), findsNothing); }); testWidgets('Custom dialog elevation', (WidgetTester tester) async { const double customElevation = 12.0; const Color shadowColor = Color(0xFF000001); const Color surfaceTintColor = Color(0xFF000002); const AlertDialog dialog = AlertDialog( actions: <Widget>[ ], elevation: customElevation, shadowColor: shadowColor, surfaceTintColor: surfaceTintColor, ); await tester.pumpWidget(_buildAppWithDialog(dialog)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Material materialWidget = _getMaterialFromDialog(tester); expect(materialWidget.elevation, customElevation); expect(materialWidget.shadowColor, shadowColor); expect(materialWidget.surfaceTintColor, surfaceTintColor); }); testWidgets('Custom Title Text Style', (WidgetTester tester) async { const String titleText = 'Title'; const TextStyle titleTextStyle = TextStyle(color: Colors.pink); const AlertDialog dialog = AlertDialog( title: Text(titleText), titleTextStyle: titleTextStyle, actions: <Widget>[ ], ); await tester.pumpWidget(_buildAppWithDialog(dialog)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final RenderParagraph title = _getTextRenderObjectFromDialog(tester, titleText); expect(title.text.style, titleTextStyle); }); testWidgets('Custom Content Text Style', (WidgetTester tester) async { const String contentText = 'Content'; const TextStyle contentTextStyle = TextStyle(color: Colors.pink); const AlertDialog dialog = AlertDialog( content: Text(contentText), contentTextStyle: contentTextStyle, actions: <Widget>[ ], ); await tester.pumpWidget(_buildAppWithDialog(dialog)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final RenderParagraph content = _getTextRenderObjectFromDialog(tester, contentText); expect(content.text.style, contentTextStyle); }); testWidgets('AlertDialog custom clipBehavior', (WidgetTester tester) async { const AlertDialog dialog = AlertDialog( actions: <Widget>[], clipBehavior: Clip.antiAlias, ); await tester.pumpWidget(_buildAppWithDialog(dialog)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Material materialWidget = _getMaterialFromDialog(tester); expect(materialWidget.clipBehavior, Clip.antiAlias); }); testWidgets('SimpleDialog custom clipBehavior', (WidgetTester tester) async { const SimpleDialog dialog = SimpleDialog( clipBehavior: Clip.antiAlias, children: <Widget>[], ); await tester.pumpWidget(_buildAppWithDialog(dialog)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Material materialWidget = _getMaterialFromDialog(tester); expect(materialWidget.clipBehavior, Clip.antiAlias); }); testWidgets('Custom dialog shape', (WidgetTester tester) async { const RoundedRectangleBorder customBorder = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))); const AlertDialog dialog = AlertDialog( actions: <Widget>[ ], shape: customBorder, ); await tester.pumpWidget(_buildAppWithDialog(dialog)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Material materialWidget = _getMaterialFromDialog(tester); expect(materialWidget.shape, customBorder); }); testWidgets('Null dialog shape', (WidgetTester tester) async { final ThemeData theme = ThemeData(); const AlertDialog dialog = AlertDialog( actions: <Widget>[ ], ); await tester.pumpWidget(_buildAppWithDialog(dialog, theme: theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Material materialWidget = _getMaterialFromDialog(tester); expect(materialWidget.shape, theme.useMaterial3 ? _defaultM3DialogShape : _defaultM2DialogShape); }); testWidgets('Rectangular dialog shape', (WidgetTester tester) async { const ShapeBorder customBorder = Border(); const AlertDialog dialog = AlertDialog( actions: <Widget>[ ], shape: customBorder, ); await tester.pumpWidget(_buildAppWithDialog(dialog)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Material materialWidget = _getMaterialFromDialog(tester); expect(materialWidget.shape, customBorder); }); testWidgets('Custom dialog alignment', (WidgetTester tester) async { const AlertDialog dialog = AlertDialog( actions: <Widget>[ ], alignment: Alignment.bottomLeft, ); await tester.pumpWidget(_buildAppWithDialog(dialog)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Offset bottomLeft = tester.getBottomLeft( find.descendant(of: find.byType(Dialog), matching: find.byType(Material)), ); expect(bottomLeft.dx, 40.0); expect(bottomLeft.dy, 576.0); }); testWidgets('Simple dialog control test', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: ElevatedButton( onPressed: null, child: Text('Go'), ), ), ), ), ); final BuildContext context = tester.element(find.text('Go')); final Future<int?> result = showDialog<int>( context: context, builder: (BuildContext context) { return SimpleDialog( title: const Text('Title'), children: <Widget>[ SimpleDialogOption( onPressed: () { Navigator.pop(context, 42); }, child: const Text('First option'), ), const SimpleDialogOption( child: Text('Second option'), ), ], ); }, ); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(find.text('Title'), findsOneWidget); await tester.tap(find.text('First option')); expect(await result, equals(42)); }); testWidgets('Can show dialog using navigator global key', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); await tester.pumpWidget( MaterialApp( navigatorKey: navigator, home: const Material( child: Center( child: Text('Go'), ), ), ), ); final Future<int?> result = showDialog<int>( context: navigator.currentContext!, builder: (BuildContext context) { return SimpleDialog( title: const Text('Title'), children: <Widget>[ SimpleDialogOption( onPressed: () { Navigator.pop(context, 42); }, child: const Text('First option'), ), const SimpleDialogOption( child: Text('Second option'), ), ], ); }, ); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(find.text('Title'), findsOneWidget); await tester.tap(find.text('First option')); expect(await result, equals(42)); }); testWidgets('Custom padding on SimpleDialogOption', (WidgetTester tester) async { const EdgeInsets customPadding = EdgeInsets.fromLTRB(4, 10, 8, 6); final SimpleDialog dialog = SimpleDialog( title: const Text('Title'), children: <Widget>[ SimpleDialogOption( onPressed: () {}, padding: customPadding, child: const Text('First option'), ), ], ); await tester.pumpWidget(_buildAppWithDialog(dialog)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Rect dialogRect = tester.getRect(find.byType(SimpleDialogOption)); final Rect textRect = tester.getRect(find.text('First option')); expect(textRect.left, dialogRect.left + customPadding.left); expect(textRect.top, dialogRect.top + customPadding.top); expect(textRect.right, dialogRect.right - customPadding.right); expect(textRect.bottom, dialogRect.bottom - customPadding.bottom); }); testWidgets('Barrier dismissible', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: ElevatedButton( onPressed: null, child: Text('Go'), ), ), ), ), ); final BuildContext context = tester.element(find.text('Go')); showDialog<void>( context: context, builder: (BuildContext context) { return Container( width: 100.0, height: 100.0, alignment: Alignment.center, child: const Text('Dialog1'), ); }, ); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(find.text('Dialog1'), findsOneWidget); // Tap on the barrier. await tester.tapAt(const Offset(10.0, 10.0)); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(find.text('Dialog1'), findsNothing); showDialog<void>( context: context, barrierDismissible: false, builder: (BuildContext context) { return Container( width: 100.0, height: 100.0, alignment: Alignment.center, child: const Text('Dialog2'), ); }, ); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(find.text('Dialog2'), findsOneWidget); // Tap on the barrier, which shouldn't do anything this time. await tester.tapAt(const Offset(10.0, 10.0)); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(find.text('Dialog2'), findsOneWidget); }); testWidgets('Barrier color', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Center(child: Text('Test')), ), ); final BuildContext context = tester.element(find.text('Test')); // Test default barrier color showDialog<void>( context: context, builder: (BuildContext context) { return const Text('Dialog'); }, ); await tester.pumpAndSettle(); expect(tester.widget<ModalBarrier>(find.byType(ModalBarrier).last).color, Colors.black54); // Dismiss it and test a custom barrier color await tester.tapAt(const Offset(10.0, 10.0)); showDialog<void>( context: context, builder: (BuildContext context) { return const Text('Dialog'); }, barrierColor: Colors.pink, ); await tester.pumpAndSettle(); expect(tester.widget<ModalBarrier>(find.byType(ModalBarrier).last).color, Colors.pink); }); testWidgets('Dialog hides underlying semantics tree', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); const String buttonText = 'A button covered by dialog overlay'; await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: ElevatedButton( onPressed: null, child: Text(buttonText), ), ), ), ), ); expect(semantics, includesNodeWith(label: buttonText)); final BuildContext context = tester.element(find.text(buttonText)); const String alertText = 'A button in an overlay alert'; showDialog<void>( context: context, builder: (BuildContext context) { return const AlertDialog(title: Text(alertText)); }, ); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(semantics, includesNodeWith(label: alertText)); expect(semantics, isNot(includesNodeWith(label: buttonText))); semantics.dispose(); }); testWidgets('AlertDialog.actionsPadding defaults', (WidgetTester tester) async { final AlertDialog dialog = AlertDialog( title: const Text('title'), content: const Text('content'), actions: <Widget>[ ElevatedButton( onPressed: () {}, child: const Text('button'), ), ], ); await tester.pumpWidget( _buildAppWithDialog(dialog), ); await tester.tap(find.text('X')); await tester.pumpAndSettle(); // The [AlertDialog] is the entire screen, since it also contains the scrim. // The first [Material] child of [AlertDialog] is the actual dialog // itself. final Size dialogSize = tester.getSize( find.descendant( of: find.byType(AlertDialog), matching: find.byType(Material), ).first, ); final Size actionsSize = tester.getSize(_findOverflowBar()); expect(actionsSize.width, dialogSize.width); }); testWidgets('AlertDialog.actionsPadding surrounds actions with padding', (WidgetTester tester) async { final AlertDialog dialog = AlertDialog( title: const Text('title'), content: const Text('content'), actions: <Widget>[ ElevatedButton( onPressed: () {}, child: const Text('button'), ), ], // The OverflowBar is inset by the buttonPadding/2 + actionsPadding buttonPadding: EdgeInsets.zero, actionsPadding: const EdgeInsets.all(30.0), // custom padding value ); await tester.pumpWidget( _buildAppWithDialog(dialog), ); await tester.tap(find.text('X')); await tester.pumpAndSettle(); // The [AlertDialog] is the entire screen, since it also contains the scrim. // The first [Material] child of [AlertDialog] is the actual dialog // itself. final Size dialogSize = tester.getSize( find.descendant( of: find.byType(AlertDialog), matching: find.byType(Material), ).first, ); final Size actionsSize = tester.getSize(find.byType(OverflowBar)); expect(actionsSize.width, dialogSize.width - (30.0 * 2)); }); testWidgets('Material2 - AlertDialog.buttonPadding defaults', (WidgetTester tester) async { final GlobalKey key1 = GlobalKey(); final GlobalKey key2 = GlobalKey(); final AlertDialog dialog = AlertDialog( title: const Text('title'), content: const Text('content'), actions: <Widget>[ ElevatedButton( key: key1, onPressed: () {}, child: const Text('button 1'), ), ElevatedButton( key: key2, onPressed: () {}, child: const Text('button 2'), ), ], ); await tester.pumpWidget(_buildAppWithDialog(dialog, theme: material2Theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); // Padding between both buttons expect( tester.getBottomLeft(find.byKey(key2)).dx, tester.getBottomRight(find.byKey(key1)).dx + 8.0, ); // Padding between button and edges of the button bar // First button expect( tester.getTopRight(find.byKey(key1)).dy, tester.getTopRight(_findOverflowBar()).dy + 8.0, ); // top expect( tester.getBottomRight(find.byKey(key1)).dy, tester.getBottomRight(_findOverflowBar()).dy - 8.0, ); // bottom // Second button expect( tester.getTopRight(find.byKey(key2)).dy, tester.getTopRight(_findOverflowBar()).dy + 8.0, ); // top expect( tester.getBottomRight(find.byKey(key2)).dy, tester.getBottomRight(_findOverflowBar()).dy - 8.0, ); // bottom expect( tester.getBottomRight(find.byKey(key2)).dx, tester.getBottomRight(_findOverflowBar()).dx - 8.0, ); // right }); testWidgets('Material3 - AlertDialog.buttonPadding defaults', (WidgetTester tester) async { final GlobalKey key1 = GlobalKey(); final GlobalKey key2 = GlobalKey(); final AlertDialog dialog = AlertDialog( title: const Text('title'), content: const Text('content'), actions: <Widget>[ ElevatedButton( key: key1, onPressed: () {}, child: const Text('button 1'), ), ElevatedButton( key: key2, onPressed: () {}, child: const Text('button 2'), ), ], ); await tester.pumpWidget(_buildAppWithDialog(dialog, theme: material3Theme)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); // Padding between both buttons expect( tester.getBottomLeft(find.byKey(key2)).dx, tester.getBottomRight(find.byKey(key1)).dx + 8.0, ); // Padding between button and edges of the button bar // First button expect( tester.getTopRight(find.byKey(key1)).dy, tester.getTopRight(_findOverflowBar()).dy, ); // top expect( tester.getBottomRight(find.byKey(key1)).dy, tester.getBottomRight(_findOverflowBar()).dy - 24.0, ); // bottom // // Second button expect( tester.getTopRight(find.byKey(key2)).dy, tester.getTopRight(_findOverflowBar()).dy, ); // top expect( tester.getBottomRight(find.byKey(key2)).dy, tester.getBottomRight(_findOverflowBar()).dy - 24.0, ); // bottom expect( tester.getBottomRight(find.byKey(key2)).dx, tester.getBottomRight(_findOverflowBar()).dx - 24.0, ); // right }); testWidgets('AlertDialog.buttonPadding custom values', (WidgetTester tester) async { final GlobalKey key1 = GlobalKey(); final GlobalKey key2 = GlobalKey(); final AlertDialog dialog = AlertDialog( title: const Text('title'), content: const Text('content'), actions: <Widget>[ ElevatedButton( key: key1, onPressed: () {}, child: const Text('button 1'), ), ElevatedButton( key: key2, onPressed: () {}, child: const Text('button 2'), ), ], buttonPadding: const EdgeInsets.only( left: 10.0, right: 20.0, ), ); await tester.pumpWidget( _buildAppWithDialog(dialog, theme: ThemeData(useMaterial3: false)), ); await tester.tap(find.text('X')); await tester.pumpAndSettle(); // Padding between both buttons expect( tester.getBottomLeft(find.byKey(key2)).dx, tester.getBottomRight(find.byKey(key1)).dx + ((10.0 + 20.0) / 2), ); // Padding between button and edges of the button bar // First button expect( tester.getTopRight(find.byKey(key1)).dy, tester.getTopRight(_findOverflowBar()).dy + ((10.0 + 20.0) / 2), ); // top expect( tester.getBottomRight(find.byKey(key1)).dy, tester.getBottomRight(_findOverflowBar()).dy - ((10.0 + 20.0) / 2), ); // bottom // Second button expect( tester.getTopRight(find.byKey(key2)).dy, tester.getTopRight(_findOverflowBar()).dy + ((10.0 + 20.0) / 2), ); // top expect( tester.getBottomRight(find.byKey(key2)).dy, tester.getBottomRight(_findOverflowBar()).dy - ((10.0 + 20.0) / 2), ); // bottom expect( tester.getBottomRight(find.byKey(key2)).dx, tester.getBottomRight(_findOverflowBar()).dx - ((10.0 + 20.0) / 2), ); // right }); group('Dialog children padding is correct', () { final List<double> textScaleFactors = <double>[0.5, 1.0, 1.5, 2.0, 3.0]; final Map<double, double> paddingScaleFactors = <double, double>{ 0.5: 1.0, 1.0: 1.0, 1.5: 2.0 / 3.0, 2.0: 1.0 / 3.0, 3.0: 1.0 / 3.0, }; final GlobalKey iconKey = GlobalKey(); final GlobalKey titleKey = GlobalKey(); final GlobalKey contentKey = GlobalKey(); final GlobalKey childrenKey = GlobalKey(); final Finder dialogFinder = find.descendant(of: find.byType(Dialog), matching: find.byType(Material)).first; final Finder iconFinder = find.byKey(iconKey); final Finder titleFinder = find.byKey(titleKey); final Finder contentFinder = find.byKey(contentKey); final Finder actionsFinder = _findOverflowBar(); final Finder childrenFinder = find.byKey(childrenKey); Future<void> openDialog(WidgetTester tester, Widget dialog, double textScaleFactor, {bool isM3 = false}) async { await tester.pumpWidget( _buildAppWithDialog(dialog, textScaleFactor: textScaleFactor, theme: ThemeData(useMaterial3: isM3)), ); await tester.tap(find.text('X')); await tester.pumpAndSettle(); } void expectLeftEdgePadding( WidgetTester tester, { required Finder finder, required double textScaleFactor, required double unscaledValue, }) { expect( tester.getTopLeft(dialogFinder).dx, moreOrLessEquals(tester.getTopLeft(finder).dx - unscaledValue * paddingScaleFactors[textScaleFactor]!), ); expect( tester.getBottomLeft(dialogFinder).dx, moreOrLessEquals(tester.getBottomLeft(finder).dx - unscaledValue * paddingScaleFactors[textScaleFactor]!), ); } void expectRightEdgePadding( WidgetTester tester, { required Finder finder, required double textScaleFactor, required double unscaledValue, }) { expect( tester.getTopRight(dialogFinder).dx, moreOrLessEquals(tester.getTopRight(finder).dx + unscaledValue * paddingScaleFactors[textScaleFactor]!), ); expect( tester.getBottomRight(dialogFinder).dx, moreOrLessEquals(tester.getBottomRight(finder).dx + unscaledValue * paddingScaleFactors[textScaleFactor]!), ); } void expectTopEdgePadding( WidgetTester tester, { required Finder finder, required double textScaleFactor, required double unscaledValue, }) { expect( tester.getTopLeft(dialogFinder).dy, moreOrLessEquals(tester.getTopLeft(finder).dy - unscaledValue * paddingScaleFactors[textScaleFactor]!), ); expect( tester.getTopRight(dialogFinder).dy, moreOrLessEquals(tester.getTopRight(finder).dy - unscaledValue * paddingScaleFactors[textScaleFactor]!), ); } void expectBottomEdgePadding( WidgetTester tester, { required Finder finder, required double textScaleFactor, required double unscaledValue, }) { expect( tester.getBottomLeft(dialogFinder).dy, moreOrLessEquals(tester.getBottomRight(finder).dy + unscaledValue * paddingScaleFactors[textScaleFactor]!), ); expect( tester.getBottomRight(dialogFinder).dy, moreOrLessEquals(tester.getBottomRight(finder).dy + unscaledValue * paddingScaleFactors[textScaleFactor]!), ); } void expectVerticalInnerPadding( WidgetTester tester, { required Finder top, required Finder bottom, required double value, }) { expect( tester.getBottomLeft(top).dy, tester.getTopLeft(bottom).dy - value, ); expect( tester.getBottomRight(top).dy, tester.getTopRight(bottom).dy - value, ); } final Widget icon = Icon( Icons.ac_unit, key: iconKey, ); final Widget title = Text( 'title', key: titleKey, ); final Widget content = Text( 'content', key: contentKey, ); final List<Widget> actions = <Widget>[ ElevatedButton( onPressed: () {}, child: const Text('button'), ), ]; final List<Widget> children = <Widget>[ SimpleDialogOption( key: childrenKey, child: const Text('child'), onPressed: () { }, ), ]; for (final double textScaleFactor in textScaleFactors) { testWidgets('AlertDialog padding is correct when only icon and actions are specified [textScaleFactor]=$textScaleFactor', (WidgetTester tester) async { final AlertDialog dialog = AlertDialog( icon: icon, actions: actions, ); await openDialog(tester, dialog, textScaleFactor); expectTopEdgePadding( tester, finder: iconFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectLeftEdgePadding( tester, finder: iconFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectRightEdgePadding( tester, finder: iconFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectVerticalInnerPadding( tester, top: iconFinder, bottom: actionsFinder, value: 24.0, ); expectLeftEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); expectRightEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); expectBottomEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); }); testWidgets('AlertDialog padding is correct when only icon, title and actions are specified [textScaleFactor]=$textScaleFactor', (WidgetTester tester) async { final AlertDialog dialog = AlertDialog( icon: icon, title: title, actions: actions, ); await openDialog(tester, dialog, textScaleFactor); expectTopEdgePadding( tester, finder: iconFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectLeftEdgePadding( tester, finder: iconFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectRightEdgePadding( tester, finder: iconFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectVerticalInnerPadding( tester, top: iconFinder, bottom: titleFinder, value: 16.0, ); expectLeftEdgePadding( tester, finder: titleFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectRightEdgePadding( tester, finder: titleFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectVerticalInnerPadding( tester, top: titleFinder, bottom: actionsFinder, value: 20.0, ); expectLeftEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); expectRightEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); expectBottomEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); }); for (final bool isM3 in <bool>[true, false]) { testWidgets('AlertDialog padding is correct when only icon, content and actions are specified [textScaleFactor]=$textScaleFactor [isM3]=$isM3', (WidgetTester tester) async { final AlertDialog dialog = AlertDialog( icon: icon, content: content, actions: actions, ); await openDialog(tester, dialog, textScaleFactor, isM3: isM3); expectTopEdgePadding( tester, finder: iconFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectLeftEdgePadding( tester, finder: iconFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectRightEdgePadding( tester, finder: iconFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectVerticalInnerPadding( tester, top: iconFinder, bottom: contentFinder, value: isM3 ? 16.0 : 20.0, ); expectLeftEdgePadding( tester, finder: contentFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectRightEdgePadding( tester, finder: contentFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectVerticalInnerPadding( tester, top: contentFinder, bottom: actionsFinder, value: 24.0, ); expectLeftEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); expectRightEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); expectBottomEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); }); } testWidgets('AlertDialog padding is correct when only title and actions are specified [textScaleFactor]=$textScaleFactor', (WidgetTester tester) async { final AlertDialog dialog = AlertDialog( title: title, actions: actions, ); await openDialog(tester, dialog, textScaleFactor); expectTopEdgePadding( tester, finder: titleFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectLeftEdgePadding( tester, finder: titleFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectRightEdgePadding( tester, finder: titleFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectVerticalInnerPadding( tester, top: titleFinder, bottom: actionsFinder, value: 20.0, ); expectLeftEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); expectRightEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); expectBottomEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); }); testWidgets('AlertDialog padding is correct when only content and actions are specified [textScaleFactor]=$textScaleFactor', (WidgetTester tester) async { final AlertDialog dialog = AlertDialog( content: content, actions: actions, ); await openDialog(tester, dialog, textScaleFactor); expectTopEdgePadding( tester, finder: contentFinder, textScaleFactor: textScaleFactor, unscaledValue: 20.0, ); expectLeftEdgePadding( tester, finder: contentFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectRightEdgePadding( tester, finder: contentFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectVerticalInnerPadding( tester, top: contentFinder, bottom: actionsFinder, value: 24.0, ); expectLeftEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); expectRightEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); expectBottomEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); }); testWidgets('AlertDialog padding is correct when title, content, and actions are specified [textScaleFactor]=$textScaleFactor', (WidgetTester tester) async { final AlertDialog dialog = AlertDialog( title: title, content: content, actions: actions, ); await openDialog(tester, dialog, textScaleFactor); expectTopEdgePadding( tester, finder: titleFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectLeftEdgePadding( tester, finder: titleFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectRightEdgePadding( tester, finder: titleFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectVerticalInnerPadding( tester, top: titleFinder, bottom: contentFinder, value: 20.0, ); expectLeftEdgePadding( tester, finder: contentFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectRightEdgePadding( tester, finder: contentFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectVerticalInnerPadding( tester, top: contentFinder, bottom: actionsFinder, value: 24.0, ); expectLeftEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); expectRightEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); expectBottomEdgePadding( tester, finder: actionsFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); }); testWidgets('SimpleDialog padding is correct when only children are specified [textScaleFactor]=$textScaleFactor', (WidgetTester tester) async { final SimpleDialog dialog = SimpleDialog( children: children, ); await openDialog(tester, dialog, textScaleFactor); expectTopEdgePadding( tester, finder: childrenFinder, textScaleFactor: textScaleFactor, unscaledValue: 12.0, ); expectLeftEdgePadding( tester, finder: childrenFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); expectRightEdgePadding( tester, finder: childrenFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); expectBottomEdgePadding( tester, finder: childrenFinder, textScaleFactor: textScaleFactor, unscaledValue: 16.0, ); }); testWidgets('SimpleDialog padding is correct when title and children are specified [textScaleFactor]=$textScaleFactor', (WidgetTester tester) async { final SimpleDialog dialog = SimpleDialog( title: title, children: children, ); await openDialog(tester, dialog, textScaleFactor); expectTopEdgePadding( tester, finder: titleFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectLeftEdgePadding( tester, finder: titleFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectRightEdgePadding( tester, finder: titleFinder, textScaleFactor: textScaleFactor, unscaledValue: 24.0, ); expectVerticalInnerPadding( tester, top: titleFinder, bottom: childrenFinder, value: 12.0, ); expectLeftEdgePadding( tester, finder: childrenFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); expectRightEdgePadding( tester, finder: childrenFinder, textScaleFactor: textScaleFactor, unscaledValue: 0.0, ); expectBottomEdgePadding( tester, finder: childrenFinder, textScaleFactor: textScaleFactor, unscaledValue: 16.0, ); }); } }); testWidgets('Dialogs can set the vertical direction of overflowing actions', (WidgetTester tester) async { final GlobalKey key1 = GlobalKey(); final GlobalKey key2 = GlobalKey(); final AlertDialog dialog = AlertDialog( title: const Text('title'), content: const Text('content'), actions: <Widget>[ ElevatedButton( key: key1, onPressed: () {}, child: const Text('Looooooooooooooong button 1'), ), ElevatedButton( key: key2, onPressed: () {}, child: const Text('Looooooooooooooong button 2'), ), ], actionsOverflowDirection: VerticalDirection.up, ); await tester.pumpWidget( _buildAppWithDialog(dialog), ); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Rect buttonOneRect = tester.getRect(find.byKey(key1)); final Rect buttonTwoRect = tester.getRect(find.byKey(key2)); // Second [ElevatedButton] should appear above the first. expect(buttonTwoRect.bottom, lessThanOrEqualTo(buttonOneRect.top)); }); testWidgets('Dialogs have no spacing by default for overflowing actions', (WidgetTester tester) async { final GlobalKey key1 = GlobalKey(); final GlobalKey key2 = GlobalKey(); final AlertDialog dialog = AlertDialog( title: const Text('title'), content: const Text('content'), actions: <Widget>[ ElevatedButton( key: key1, onPressed: () {}, child: const Text('Looooooooooooooong button 1'), ), ElevatedButton( key: key2, onPressed: () {}, child: const Text('Looooooooooooooong button 2'), ), ], ); await tester.pumpWidget( _buildAppWithDialog(dialog), ); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Rect buttonOneRect = tester.getRect(find.byKey(key1)); final Rect buttonTwoRect = tester.getRect(find.byKey(key2)); expect(buttonOneRect.bottom, buttonTwoRect.top); }); testWidgets('Dialogs can set the button spacing of overflowing actions', (WidgetTester tester) async { final GlobalKey key1 = GlobalKey(); final GlobalKey key2 = GlobalKey(); final AlertDialog dialog = AlertDialog( title: const Text('title'), content: const Text('content'), actions: <Widget>[ ElevatedButton( key: key1, onPressed: () {}, child: const Text('Looooooooooooooong button 1'), ), ElevatedButton( key: key2, onPressed: () {}, child: const Text('Looooooooooooooong button 2'), ), ], actionsOverflowButtonSpacing: 10.0, ); await tester.pumpWidget( _buildAppWithDialog(dialog), ); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Rect buttonOneRect = tester.getRect(find.byKey(key1)); final Rect buttonTwoRect = tester.getRect(find.byKey(key2)); expect(buttonOneRect.bottom, buttonTwoRect.top - 10.0); }); testWidgets('Dialogs can set the alignment of the OverflowBar', (WidgetTester tester) async { final GlobalKey key1 = GlobalKey(); final GlobalKey key2 = GlobalKey(); final AlertDialog dialog = AlertDialog( title: const Text('title'), content: const Text('content'), actions: <Widget>[ ElevatedButton( key: key1, onPressed: () {}, child: const Text('Loooooooooong button 1'), ), ElevatedButton( key: key2, onPressed: () {}, child: const Text('Loooooooooooooonger button 2'), ), ], actionsOverflowAlignment: OverflowBarAlignment.center, ); await tester.pumpWidget( _buildAppWithDialog(dialog), ); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final Rect buttonOneRect = tester.getRect(find.byKey(key1)); final Rect buttonTwoRect = tester.getRect(find.byKey(key2)); expect(buttonOneRect.center.dx, buttonTwoRect.center.dx); }); testWidgets('Dialogs removes MediaQuery padding and view insets', (WidgetTester tester) async { late BuildContext outerContext; late BuildContext routeContext; late BuildContext dialogContext; await tester.pumpWidget(Localizations( locale: const Locale('en', 'US'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: MediaQuery( data: const MediaQueryData( padding: EdgeInsets.all(50.0), viewInsets: EdgeInsets.only(left: 25.0, bottom: 75.0), ), child: Navigator( onGenerateRoute: (_) { return PageRouteBuilder<void>( pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { outerContext = context; return Container(); }, ); }, ), ), )); showDialog<void>( context: outerContext, barrierDismissible: false, builder: (BuildContext context) { routeContext = context; return Dialog( child: Builder( builder: (BuildContext context) { dialogContext = context; return const Placeholder(); }, ), ); }, ); await tester.pump(); expect(MediaQuery.of(outerContext).padding, const EdgeInsets.all(50.0)); expect(MediaQuery.of(routeContext).padding, EdgeInsets.zero); expect(MediaQuery.of(dialogContext).padding, EdgeInsets.zero); expect(MediaQuery.of(outerContext).viewInsets, const EdgeInsets.only(left: 25.0, bottom: 75.0)); expect(MediaQuery.of(routeContext).viewInsets, const EdgeInsets.only(left: 25.0, bottom: 75.0)); expect(MediaQuery.of(dialogContext).viewInsets, EdgeInsets.zero); }); testWidgets('Dialog widget insets by viewInsets', (WidgetTester tester) async { await tester.pumpWidget( const MediaQuery( data: MediaQueryData( viewInsets: EdgeInsets.fromLTRB(10.0, 20.0, 30.0, 40.0), ), child: Dialog( child: Placeholder(), ), ), ); expect( tester.getRect(find.byType(Placeholder)), const Rect.fromLTRB(10.0 + 40.0, 20.0 + 24.0, 800.0 - (40.0 + 30.0), 600.0 - (24.0 + 40.0)), ); await tester.pumpWidget( const MediaQuery( data: MediaQueryData(), child: Dialog( child: Placeholder(), ), ), ); expect( // no change because this is an animation tester.getRect(find.byType(Placeholder)), const Rect.fromLTRB(10.0 + 40.0, 20.0 + 24.0, 800.0 - (40.0 + 30.0), 600.0 - (24.0 + 40.0)), ); await tester.pump(const Duration(seconds: 1)); expect( // animation finished tester.getRect(find.byType(Placeholder)), const Rect.fromLTRB(40.0, 24.0, 800.0 - 40.0, 600.0 - 24.0), ); }); testWidgets('Dialog insetPadding added to outside of dialog', (WidgetTester tester) async { // The default testing screen (800, 600) const Rect screenRect = Rect.fromLTRB(0.0, 0.0, 800.0, 600.0); // Test with no padding. await tester.pumpWidget( const MediaQuery( data: MediaQueryData(), child: Dialog( insetPadding: EdgeInsets.zero, child: Placeholder(), ), ), ); await tester.pumpAndSettle(); expect(tester.getRect(find.byType(Placeholder)), screenRect); // Test with an insetPadding. await tester.pumpWidget( const MediaQuery( data: MediaQueryData(), child: Dialog( insetPadding: EdgeInsets.fromLTRB(10.0, 20.0, 30.0, 40.0), child: Placeholder(), ), ), ); await tester.pumpAndSettle(); expect( tester.getRect(find.byType(Placeholder)), Rect.fromLTRB( screenRect.left + 10.0, screenRect.top + 20.0, screenRect.right - 30.0, screenRect.bottom - 40.0, ), ); }); // Regression test for https://github.com/flutter/flutter/issues/78229. testWidgets('AlertDialog has correct semantics for content in iOS', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.iOS), home: const AlertDialog( title: Text('title'), content: Text('content'), actions: <Widget>[ TextButton(onPressed: null, child: Text('action')) ], ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: 1, textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( id: 2, children: <TestSemantics>[ TestSemantics( id: 3, flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( id: 4, children: <TestSemantics>[ TestSemantics( id: 5, label: 'title', textDirection: TextDirection.ltr, ), // The content semantics does not merge into the semantics // node 4. TestSemantics( id: 6, label: 'content', textDirection: TextDirection.ltr, ), TestSemantics( id: 7, flags: <SemanticsFlag>[ SemanticsFlag.isButton, SemanticsFlag.hasEnabledState, ], label: 'action', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true)); semantics.dispose(); }); testWidgets('AlertDialog widget always contains alert route semantics for android', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android), home: Material( child: Builder( builder: (BuildContext context) { return Center( child: ElevatedButton( child: const Text('X'), onPressed: () { showDialog<void>( context: context, builder: (BuildContext context) { return const AlertDialog( title: Text('Title'), content: Text('Y'), actions: <Widget>[], ); }, ); }, ), ); }, ), ), ), ); expect(semantics, isNot(includesNodeWith( label: 'Title', flags: <SemanticsFlag>[SemanticsFlag.namesRoute], ))); expect(semantics, isNot(includesNodeWith( label: 'Alert', flags: <SemanticsFlag>[SemanticsFlag.namesRoute, SemanticsFlag.scopesRoute], ))); await tester.tap(find.text('X')); await tester.pumpAndSettle(); // It does not use 'Title' as route semantics expect(semantics, isNot(includesNodeWith( label: 'Title', flags: <SemanticsFlag>[SemanticsFlag.namesRoute], ))); expect(semantics, includesNodeWith( label: 'Alert', flags: <SemanticsFlag>[SemanticsFlag.namesRoute, SemanticsFlag.scopesRoute], )); semantics.dispose(); }); testWidgets('SimpleDialog does not introduce additional node', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.android), home: Material( child: Builder( builder: (BuildContext context) { return Center( child: ElevatedButton( child: const Text('X'), onPressed: () { showDialog<void>( context: context, builder: (BuildContext context) { return const SimpleDialog( title: Text('Title'), semanticLabel: 'label', ); }, ); }, ), ); }, ), ), ), ); await tester.tap(find.text('X')); await tester.pumpAndSettle(); // A scope route is not focusable in accessibility service. expect(semantics, includesNodeWith( label: 'label', flags: <SemanticsFlag>[SemanticsFlag.namesRoute, SemanticsFlag.scopesRoute], )); semantics.dispose(); }); // Regression test for https://github.com/flutter/flutter/issues/78229. testWidgets('SimpleDialog has correct semantics for title in iOS', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.iOS), home: const SimpleDialog( title: Text('title'), children: <Widget>[ Text('content'), TextButton(onPressed: null, child: Text('action')), ], ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: 1, textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( id: 2, children: <TestSemantics>[ TestSemantics( id: 3, flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( id: 4, children: <TestSemantics>[ // Title semantics does not merge into the semantics // node 4. TestSemantics( id: 5, label: 'title', textDirection: TextDirection.ltr, ), TestSemantics( id: 6, flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], children: <TestSemantics>[ TestSemantics( id: 7, label: 'content', textDirection: TextDirection.ltr, ), TestSemantics( id: 8, flags: <SemanticsFlag>[ SemanticsFlag.isButton, SemanticsFlag.hasEnabledState, ], label: 'action', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true)); semantics.dispose(); }); testWidgets('Dismissible.confirmDismiss defers to an AlertDialog', (WidgetTester tester) async { final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); final List<int> dismissedItems = <int>[]; // Dismiss is confirmed IFF confirmDismiss() returns true. Future<bool?> confirmDismiss (DismissDirection dismissDirection) async { return showDialog<bool>( context: scaffoldKey.currentContext!, builder: (BuildContext context) { return AlertDialog( actions: <Widget>[ TextButton( child: const Text('TRUE'), onPressed: () { Navigator.pop(context, true); // showDialog() returns true }, ), TextButton( child: const Text('FALSE'), onPressed: () { Navigator.pop(context, false); // showDialog() returns false }, ), ], ); }, ); } Widget buildDismissibleItem(int item, StateSetter setState) { return Dismissible( key: ValueKey<int>(item), confirmDismiss: confirmDismiss, onDismissed: (DismissDirection direction) { setState(() { expect(dismissedItems.contains(item), isFalse); dismissedItems.add(item); }); }, child: SizedBox( height: 100.0, child: Text(item.toString()), ), ); } Widget buildFrame() { return MaterialApp( home: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Scaffold( key: scaffoldKey, body: Padding( padding: const EdgeInsets.all(16.0), child: ListView( itemExtent: 100.0, children: <int>[0, 1, 2, 3, 4] .where((int i) => !dismissedItems.contains(i)) .map<Widget>((int item) => buildDismissibleItem(item, setState)).toList(), ), ), ); }, ), ); } Future<void> dismissItem(WidgetTester tester, int item) async { await tester.fling(find.text(item.toString()), const Offset(300.0, 0.0), 1000.0); // fling to the right await tester.pump(); // start the slide await tester.pump(const Duration(seconds: 1)); // finish the slide and start shrinking... await tester.pump(); // first frame of shrinking animation await tester.pump(const Duration(seconds: 1)); // finish the shrinking and call the callback... await tester.pump(); // rebuild after the callback removes the entry } // Dismiss item 0 is confirmed via the AlertDialog await tester.pumpWidget(buildFrame()); expect(dismissedItems, isEmpty); await dismissItem(tester, 0); // Causes the AlertDialog to appear per confirmDismiss await tester.pumpAndSettle(); await tester.tap(find.text('TRUE')); // AlertDialog action await tester.pumpAndSettle(); expect(find.text('TRUE'), findsNothing); // Dialog was dismissed expect(find.text('FALSE'), findsNothing); expect(dismissedItems, <int>[0]); expect(find.text('0'), findsNothing); // Dismiss item 1 is not confirmed via the AlertDialog await tester.pumpWidget(buildFrame()); expect(dismissedItems, <int>[0]); await dismissItem(tester, 1); // Causes the AlertDialog to appear per confirmDismiss await tester.pumpAndSettle(); await tester.tap(find.text('FALSE')); // AlertDialog action await tester.pumpAndSettle(); expect(find.text('TRUE'), findsNothing); // Dialog was dismissed expect(find.text('FALSE'), findsNothing); expect(dismissedItems, <int>[0]); expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); // Dismiss item 1 is not confirmed via the AlertDialog await tester.pumpWidget(buildFrame()); expect(dismissedItems, <int>[0]); await dismissItem(tester, 1); // Causes the AlertDialog to appear per confirmDismiss await tester.pumpAndSettle(); expect(find.text('FALSE'), findsOneWidget); expect(find.text('TRUE'), findsOneWidget); await tester.tapAt(Offset.zero); // Tap outside of the AlertDialog await tester.pumpAndSettle(); expect(dismissedItems, <int>[0]); expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); expect(find.text('TRUE'), findsNothing); // Dialog was dismissed expect(find.text('FALSE'), findsNothing); // Dismiss item 1 is confirmed via the AlertDialog await tester.pumpWidget(buildFrame()); expect(dismissedItems, <int>[0]); await dismissItem(tester, 1); // Causes the AlertDialog to appear per confirmDismiss await tester.pumpAndSettle(); await tester.tap(find.text('TRUE')); // AlertDialog action await tester.pumpAndSettle(); expect(find.text('TRUE'), findsNothing); // Dialog was dismissed expect(find.text('FALSE'), findsNothing); expect(dismissedItems, <int>[0, 1]); expect(find.text('0'), findsNothing); expect(find.text('1'), findsNothing); }); // Regression test for https://github.com/flutter/flutter/issues/28505. testWidgets('showDialog only gets Theme from context on the first call', (WidgetTester tester) async { Widget buildFrame(Key builderKey) { return MaterialApp( home: Center( child: Builder( key: builderKey, builder: (BuildContext outerContext) { return ElevatedButton( onPressed: () { showDialog<void>( context: outerContext, builder: (BuildContext innerContext) { return const AlertDialog(title: Text('Title')); }, ); }, child: const Text('Show Dialog'), ); }, ), ), ); } await tester.pumpWidget(buildFrame(UniqueKey())); // Open the dialog. await tester.tap(find.byType(ElevatedButton)); await tester.pumpAndSettle(); // Force the Builder to be recreated (new key) which causes outerContext to // be deactivated. If showDialog()'s implementation were to refer to // outerContext again, it would crash. await tester.pumpWidget(buildFrame(UniqueKey())); await tester.pump(); }); testWidgets('showDialog safe area', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( builder: (BuildContext context, Widget? child) { return MediaQuery( // Set up the safe area to be 20 pixels in from each side data: const MediaQueryData(padding: EdgeInsets.all(20.0)), child: child!, ); }, home: const Center(child: Text('Test')), ), ); final BuildContext context = tester.element(find.text('Test')); // By default it should honor the safe area showDialog<void>( context: context, builder: (BuildContext context) { return const Placeholder(); }, ); await tester.pumpAndSettle(); expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(20.0, 20.0)); expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(780.0, 580.0)); // Dismiss it and test with useSafeArea off await tester.tapAt(const Offset(10.0, 10.0)); showDialog<void>( context: context, builder: (BuildContext context) { return const Placeholder(); }, useSafeArea: false, ); await tester.pumpAndSettle(); // Should take up the whole screen expect(tester.getTopLeft(find.byType(Placeholder)), Offset.zero); expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(800.0, 600.0)); }); testWidgets('showDialog uses root navigator by default', (WidgetTester tester) async { final DialogObserver rootObserver = DialogObserver(); final DialogObserver nestedObserver = DialogObserver(); await tester.pumpWidget(MaterialApp( navigatorObservers: <NavigatorObserver>[rootObserver], home: Navigator( observers: <NavigatorObserver>[nestedObserver], onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<dynamic>( builder: (BuildContext context) { return ElevatedButton( onPressed: () { showDialog<void>( context: context, builder: (BuildContext innerContext) { return const AlertDialog(title: Text('Title')); }, ); }, child: const Text('Show Dialog'), ); }, ); }, ), )); // Open the dialog. await tester.tap(find.byType(ElevatedButton)); expect(rootObserver.dialogCount, 1); expect(nestedObserver.dialogCount, 0); }); testWidgets('showDialog uses nested navigator if useRootNavigator is false', (WidgetTester tester) async { final DialogObserver rootObserver = DialogObserver(); final DialogObserver nestedObserver = DialogObserver(); await tester.pumpWidget(MaterialApp( navigatorObservers: <NavigatorObserver>[rootObserver], home: Navigator( observers: <NavigatorObserver>[nestedObserver], onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<dynamic>( builder: (BuildContext context) { return ElevatedButton( onPressed: () { showDialog<void>( context: context, useRootNavigator: false, builder: (BuildContext innerContext) { return const AlertDialog(title: Text('Title')); }, ); }, child: const Text('Show Dialog'), ); }, ); }, ), )); // Open the dialog. await tester.tap(find.byType(ElevatedButton)); expect(rootObserver.dialogCount, 0); expect(nestedObserver.dialogCount, 1); }); testWidgets('showDialog throws a friendly user message when context is not active', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/12467 await tester.pumpWidget( const MaterialApp( home: Center(child: Text('Test')), ), ); final BuildContext context = tester.element(find.text('Test')); await tester.pumpWidget( const MaterialApp( home: Center(), ), ); Object? error; try { showDialog<void>( context: context, builder: (BuildContext innerContext) { return const AlertDialog(title: Text('Title')); }, ); } catch (exception) { error = exception; } expect(error, isNotNull); expect(error, isFlutterError); if (error is FlutterError) { final ErrorSummary summary = error.diagnostics.first as ErrorSummary; expect(summary.toString(), 'This BuildContext is no longer valid.'); } }); group('showDialog avoids overlapping display features', () { testWidgets('positioning with anchorPoint', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( builder: (BuildContext context, Widget? child) { return MediaQuery( // Display has a vertical hinge down the middle data: const MediaQueryData( size: Size(800, 600), displayFeatures: <DisplayFeature>[ DisplayFeature( bounds: Rect.fromLTRB(390, 0, 410, 600), type: DisplayFeatureType.hinge, state: DisplayFeatureState.unknown, ), ], ), child: child!, ); }, home: const Center(child: Text('Test')), ), ); final BuildContext context = tester.element(find.text('Test')); showDialog<void>( context: context, builder: (BuildContext context) { return const Placeholder(); }, anchorPoint: const Offset(1000, 0), ); await tester.pumpAndSettle(); // Should take the right side of the screen expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(410.0, 0.0)); expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(800.0, 600.0)); }); testWidgets('positioning with Directionality', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( builder: (BuildContext context, Widget? child) { return MediaQuery( // Display has a vertical hinge down the middle data: const MediaQueryData( size: Size(800, 600), displayFeatures: <DisplayFeature>[ DisplayFeature( bounds: Rect.fromLTRB(390, 0, 410, 600), type: DisplayFeatureType.hinge, state: DisplayFeatureState.unknown, ), ], ), child: Directionality( textDirection: TextDirection.rtl, child: child!, ), ); }, home: const Center(child: Text('Test')), ), ); final BuildContext context = tester.element(find.text('Test')); showDialog<void>( context: context, builder: (BuildContext context) { return const Placeholder(); }, ); await tester.pumpAndSettle(); // Since this is RTL, it should place the dialog on the right screen expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(410.0, 0.0)); expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(800.0, 600.0)); }); testWidgets('positioning by default', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( builder: (BuildContext context, Widget? child) { return MediaQuery( // Display has a vertical hinge down the middle data: const MediaQueryData( size: Size(800, 600), displayFeatures: <DisplayFeature>[ DisplayFeature( bounds: Rect.fromLTRB(390, 0, 410, 600), type: DisplayFeatureType.hinge, state: DisplayFeatureState.unknown, ), ], ), child: child!, ); }, home: const Center(child: Text('Test')), ), ); final BuildContext context = tester.element(find.text('Test')); showDialog<void>( context: context, builder: (BuildContext context) { return const Placeholder(); }, ); await tester.pumpAndSettle(); // By default it should place the dialog on the left screen expect(tester.getTopLeft(find.byType(Placeholder)), Offset.zero); expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(390.0, 600.0)); }); }); group('AlertDialog.scrollable: ', () { testWidgets('Title is scrollable', (WidgetTester tester) async { final Key titleKey = UniqueKey(); final AlertDialog dialog = AlertDialog( title: Container( key: titleKey, color: Colors.green, height: 1000, ), scrollable: true, ); await tester.pumpWidget(_buildAppWithDialog(dialog)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final RenderBox box = tester.renderObject(find.byKey(titleKey)); final Offset originalOffset = box.localToGlobal(Offset.zero); await tester.drag(find.byKey(titleKey), const Offset(0.0, -200.0)); expect(box.localToGlobal(Offset.zero), equals(originalOffset.translate(0.0, -200.0))); }); testWidgets('Content is scrollable', (WidgetTester tester) async { final Key contentKey = UniqueKey(); final AlertDialog dialog = AlertDialog( content: Container( key: contentKey, color: Colors.orange, height: 1000, ), scrollable: true, ); await tester.pumpWidget(_buildAppWithDialog(dialog)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final RenderBox box = tester.renderObject(find.byKey(contentKey)); final Offset originalOffset = box.localToGlobal(Offset.zero); await tester.drag(find.byKey(contentKey), const Offset(0.0, -200.0)); expect(box.localToGlobal(Offset.zero), equals(originalOffset.translate(0.0, -200.0))); }); testWidgets('Title and content are scrollable', (WidgetTester tester) async { final Key titleKey = UniqueKey(); final Key contentKey = UniqueKey(); final AlertDialog dialog = AlertDialog( title: Container( key: titleKey, color: Colors.green, height: 400, ), content: Container( key: contentKey, color: Colors.orange, height: 400, ), scrollable: true, ); await tester.pumpWidget(_buildAppWithDialog(dialog)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); final RenderBox title = tester.renderObject(find.byKey(titleKey)); final RenderBox content = tester.renderObject(find.byKey(contentKey)); final Offset titleOriginalOffset = title.localToGlobal(Offset.zero); final Offset contentOriginalOffset = content.localToGlobal(Offset.zero); // Dragging the title widget should scroll both the title // and the content widgets. await tester.drag(find.byKey(titleKey), const Offset(0.0, -200.0)); expect(title.localToGlobal(Offset.zero), equals(titleOriginalOffset.translate(0.0, -200.0))); expect(content.localToGlobal(Offset.zero), equals(contentOriginalOffset.translate(0.0, -200.0))); // Dragging the content widget should scroll both the title // and the content widgets. await tester.drag(find.byKey(contentKey), const Offset(0.0, 200.0)); expect(title.localToGlobal(Offset.zero), equals(titleOriginalOffset)); expect(content.localToGlobal(Offset.zero), equals(contentOriginalOffset)); }); }); testWidgets('Dialog with RouteSettings', (WidgetTester tester) async { late RouteSettings currentRouteSetting; await tester.pumpWidget( MaterialApp( navigatorObservers: <NavigatorObserver>[ _ClosureNavigatorObserver(onDidChange: (Route<dynamic> newRoute) { currentRouteSetting = newRoute.settings; }), ], home: const Material( child: Center( child: ElevatedButton( onPressed: null, child: Text('Go'), ), ), ), ), ); final BuildContext context = tester.element(find.text('Go')); const RouteSettings exampleSetting = RouteSettings(name: 'simple'); final Future<int?> result = showDialog<int>( context: context, builder: (BuildContext context) { return SimpleDialog( title: const Text('Title'), children: <Widget>[ SimpleDialogOption( child: const Text('X'), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, routeSettings: exampleSetting, ); await tester.pumpAndSettle(); expect(find.text('Title'), findsOneWidget); expect(currentRouteSetting, exampleSetting); await tester.tap(find.text('X')); await tester.pumpAndSettle(); expect(await result, isNull); await tester.pumpAndSettle(); expect(currentRouteSetting.name, '/'); }); testWidgets('showDialog - custom barrierLabel', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.iOS), home: Material( child: Builder( builder: (BuildContext context) { return Center( child: ElevatedButton( child: const Text('X'), onPressed: () { showDialog<void>( context: context, barrierLabel: 'Custom label', builder: (BuildContext context) { return const AlertDialog( title: Text('Title'), content: Text('Y'), actions: <Widget>[], ); }, ); }, ), ); }, ), ), ), ); expect(semantics, isNot(includesNodeWith( label: 'Custom label', flags: <SemanticsFlag>[SemanticsFlag.namesRoute], ))); semantics.dispose(); }); testWidgets('DialogRoute is state restorable', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( restorationScopeId: 'app', home: _RestorableDialogTestWidget(), ), ); expect(find.byType(AlertDialog), findsNothing); await tester.tap(find.text('X')); await tester.pumpAndSettle(); expect(find.byType(AlertDialog), findsOneWidget); final TestRestorationData restorationData = await tester.getRestorationData(); await tester.restartAndRestore(); expect(find.byType(AlertDialog), findsOneWidget); // Tap on the barrier. await tester.tapAt(const Offset(10.0, 10.0)); await tester.pumpAndSettle(); expect(find.byType(AlertDialog), findsNothing); await tester.restoreFrom(restorationData); expect(find.byType(AlertDialog), findsOneWidget); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/33615 testWidgets('AlertDialog.actionsAlignment', (WidgetTester tester) async { final Key actionKey = UniqueKey(); Widget buildFrame(MainAxisAlignment? alignment) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: AlertDialog( content: const SizedBox(width: 800), actionsAlignment: alignment, actions: <Widget>[SizedBox(key: actionKey, width: 20, height: 20)], buttonPadding: EdgeInsets.zero, insetPadding: EdgeInsets.zero, ), ), ); } // Default configuration await tester.pumpWidget(buildFrame(null)); expect(tester.getTopLeft(find.byType(AlertDialog)).dx, 0); expect(tester.getTopRight(find.byType(AlertDialog)).dx, 800); expect(tester.getSize(find.byType(OverflowBar)).width, 800); expect(tester.getTopLeft(find.byKey(actionKey)).dx, 800 - 20); expect(tester.getTopRight(find.byKey(actionKey)).dx, 800); // All possible alignment values await tester.pumpWidget(buildFrame(MainAxisAlignment.start)); expect(tester.getTopLeft(find.byKey(actionKey)).dx, 0); expect(tester.getTopRight(find.byKey(actionKey)).dx, 20); await tester.pumpWidget(buildFrame(MainAxisAlignment.center)); expect(tester.getTopLeft(find.byKey(actionKey)).dx, (800 - 20) / 2); expect(tester.getTopRight(find.byKey(actionKey)).dx, (800 - 20) / 2 + 20); await tester.pumpWidget(buildFrame(MainAxisAlignment.end)); expect(tester.getTopLeft(find.byKey(actionKey)).dx, 800 - 20); expect(tester.getTopRight(find.byKey(actionKey)).dx, 800); await tester.pumpWidget(buildFrame(MainAxisAlignment.spaceBetween)); expect(tester.getTopLeft(find.byKey(actionKey)).dx, 0); expect(tester.getTopRight(find.byKey(actionKey)).dx, 20); await tester.pumpWidget(buildFrame(MainAxisAlignment.spaceAround)); expect(tester.getTopLeft(find.byKey(actionKey)).dx, (800 - 20) / 2); expect(tester.getTopRight(find.byKey(actionKey)).dx, (800 - 20) / 2 + 20); await tester.pumpWidget(buildFrame(MainAxisAlignment.spaceEvenly)); expect(tester.getTopLeft(find.byKey(actionKey)).dx, (800 - 20) / 2); expect(tester.getTopRight(find.byKey(actionKey)).dx, (800 - 20) / 2 + 20); }); testWidgets('Uses closed loop focus traversal', (WidgetTester tester) async { final FocusNode okNode = FocusNode(); final FocusNode cancelNode = FocusNode(); Future<bool> nextFocus() async { final bool result = Actions.invoke( primaryFocus!.context!, const NextFocusIntent(), )! as bool; await tester.pump(); return result; } Future<bool> previousFocus() async { final bool result = Actions.invoke( primaryFocus!.context!, const PreviousFocusIntent(), )! as bool; await tester.pump(); return result; } final AlertDialog dialog = AlertDialog( content: const Text('Test dialog'), actions: <Widget>[ TextButton( focusNode: okNode, onPressed: () {}, child: const Text('OK'), ), TextButton( focusNode: cancelNode, onPressed: () {}, child: const Text('Cancel'), ), ], ); await tester.pumpWidget(_buildAppWithDialog(dialog)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); // Start at OK okNode.requestFocus(); await tester.pump(); expect(okNode.hasFocus, true); expect(cancelNode.hasFocus, false); // OK -> Cancel expect(await nextFocus(), true); expect(okNode.hasFocus, false); expect(cancelNode.hasFocus, true); // Cancel -> OK expect(await nextFocus(), true); expect(okNode.hasFocus, true); expect(cancelNode.hasFocus, false); // Cancel <- OK expect(await previousFocus(), true); expect(okNode.hasFocus, false); expect(cancelNode.hasFocus, true); // OK <- Cancel expect(await previousFocus(), true); expect(okNode.hasFocus, true); expect(cancelNode.hasFocus, false); cancelNode.dispose(); okNode.dispose(); }); testWidgets('Adaptive AlertDialog shows correct widget on each platform', (WidgetTester tester) async { final AlertDialog dialog = AlertDialog.adaptive( content: Container( height: 5000.0, width: 300.0, color: Colors.green[500], ), actions: <Widget>[ TextButton( onPressed: () {}, child: const Text('OK'), ), ], ); for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.iOS, TargetPlatform.macOS ]) { await tester.pumpWidget(_buildAppWithDialog(dialog, theme: ThemeData(platform: platform))); await tester.pumpAndSettle(); await tester.tap(find.text('X')); await tester.pumpAndSettle(); expect(find.byType(CupertinoAlertDialog), findsOneWidget); await tester.tapAt(const Offset(10.0, 10.0)); await tester.pumpAndSettle(); } for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows ]) { await tester.pumpWidget(_buildAppWithDialog(dialog, theme: ThemeData(platform: platform))); await tester.pumpAndSettle(); await tester.tap(find.text('X')); await tester.pumpAndSettle(); expect(find.byType(CupertinoAlertDialog), findsNothing); await tester.tapAt(const Offset(10.0, 10.0)); await tester.pumpAndSettle(); } }); testWidgets('showAdaptiveDialog should not allow dismiss on barrier on iOS by default', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(platform: TargetPlatform.iOS), home: const Material( child: Center( child: ElevatedButton( onPressed: null, child: Text('Go'), ), ), ), ), ); final BuildContext context = tester.element(find.text('Go')); showDialog<void>( context: context, builder: (BuildContext context) { return Container( width: 100.0, height: 100.0, alignment: Alignment.center, child: const Text('Dialog1'), ); }, ); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(find.text('Dialog1'), findsOneWidget); // Tap on the barrier. await tester.tapAt(const Offset(10.0, 10.0)); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(find.text('Dialog1'), findsNothing); showAdaptiveDialog<void>( context: context, builder: (BuildContext context) { return Container( width: 100.0, height: 100.0, alignment: Alignment.center, child: const Text('Dialog2'), ); }, ); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(find.text('Dialog2'), findsOneWidget); // Tap on the barrier, which shouldn't do anything this time. await tester.tapAt(const Offset(10.0, 10.0)); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(find.text('Dialog2'), findsOneWidget); }); testWidgets('Uses open focus traversal when overridden', (WidgetTester tester) async { final FocusNode okNode = FocusNode(); addTearDown(okNode.dispose); final FocusNode cancelNode = FocusNode(); addTearDown(cancelNode.dispose); Future<bool> nextFocus() async { final bool result = Actions.invoke( primaryFocus!.context!, const NextFocusIntent(), )! as bool; await tester.pump(); return result; } final AlertDialog dialog = AlertDialog( content: const Text('Test dialog'), actions: <Widget>[ TextButton( focusNode: okNode, onPressed: () {}, child: const Text('OK'), ), TextButton( focusNode: cancelNode, onPressed: () {}, child: const Text('Cancel'), ), ], ); await tester.pumpWidget(_buildAppWithDialog(dialog, traversalEdgeBehavior: TraversalEdgeBehavior.leaveFlutterView)); await tester.tap(find.text('X')); await tester.pumpAndSettle(); // Start at OK okNode.requestFocus(); await tester.pump(); expect(okNode.hasFocus, true); expect(cancelNode.hasFocus, false); // OK -> Cancel expect(await nextFocus(), true); expect(okNode.hasFocus, false); expect(cancelNode.hasFocus, true); // Cancel -> nothing expect(await nextFocus(), false); expect(okNode.hasFocus, false); expect(cancelNode.hasFocus, false); }); testWidgets('Dialog.insetPadding is nullable', (WidgetTester tester) async { const Dialog dialog = Dialog(); expect(dialog.insetPadding, isNull); }); testWidgets('AlertDialog.insetPadding is nullable', (WidgetTester tester) async { const AlertDialog alertDialog = AlertDialog(); expect(alertDialog.insetPadding, isNull); }); testWidgets('SimpleDialog.insetPadding is nullable', (WidgetTester tester) async { const SimpleDialog simpleDialog = SimpleDialog(); expect(simpleDialog.insetPadding, isNull); }); } class _RestorableDialogTestWidget extends StatelessWidget { const _RestorableDialogTestWidget(); @pragma('vm:entry-point') static Route<Object?> _materialDialogBuilder(BuildContext context, Object? arguments) { return DialogRoute<void>( context: context, builder: (BuildContext context) => const AlertDialog(title: Text('Material Alert!')), ); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: OutlinedButton( onPressed: () { Navigator.of(context).restorablePush(_materialDialogBuilder); }, child: const Text('X'), ), ), ); } } class DialogObserver extends NavigatorObserver { int dialogCount = 0; @override void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) { if (route is DialogRoute) { dialogCount++; } super.didPush(route, previousRoute); } } class _ClosureNavigatorObserver extends NavigatorObserver { _ClosureNavigatorObserver({required this.onDidChange}); final void Function(Route<dynamic> newRoute) onDidChange; @override void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) => onDidChange(route); @override void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) => onDidChange(previousRoute!); @override void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) => onDidChange(previousRoute!); @override void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) => onDidChange(newRoute!); }
flutter/packages/flutter/test/material/dialog_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/dialog_test.dart", "repo_id": "flutter", "token_count": 40759 }
668
// 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. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; class TestIcon extends StatefulWidget { const TestIcon({super.key}); @override TestIconState createState() => TestIconState(); } class TestIconState extends State<TestIcon> { late IconThemeData iconTheme; @override Widget build(BuildContext context) { iconTheme = IconTheme.of(context); return const Icon(Icons.expand_more); } } class TestText extends StatefulWidget { const TestText(this.text, {super.key}); final String text; @override TestTextState createState() => TestTextState(); } class TestTextState extends State<TestText> { late TextStyle textStyle; @override Widget build(BuildContext context) { textStyle = DefaultTextStyle.of(context).style; return Text(widget.text); } } void main() { const Color dividerColor = Color(0x1f333333); const Color foregroundColor = Colors.blueAccent; const Color unselectedWidgetColor = Colors.black54; const Color headerColor = Colors.black45; Material getMaterial(WidgetTester tester) { return tester.widget<Material>(find.descendant( of: find.byType(ExpansionTile), matching: find.byType(Material), )); } testWidgets('ExpansionTile initial state', (WidgetTester tester) async { final Key topKey = UniqueKey(); final Key tileKey = UniqueKey(); const Key expandedKey = PageStorageKey<String>('expanded'); const Key collapsedKey = PageStorageKey<String>('collapsed'); const Key defaultKey = PageStorageKey<String>('default'); await tester.pumpWidget(MaterialApp( theme: ThemeData(dividerColor: dividerColor), home: Material( child: SingleChildScrollView( child: Column( children: <Widget>[ ListTile(title: const Text('Top'), key: topKey), ExpansionTile( key: expandedKey, initiallyExpanded: true, title: const Text('Expanded'), backgroundColor: Colors.red, children: <Widget>[ ListTile( key: tileKey, title: const Text('0'), ), ], ), ExpansionTile( key: collapsedKey, title: const Text('Collapsed'), children: <Widget>[ ListTile( key: tileKey, title: const Text('0'), ), ], ), const ExpansionTile( key: defaultKey, title: Text('Default'), children: <Widget>[ ListTile(title: Text('0')), ], ), ], ), ), ), )); double getHeight(Key key) => tester.getSize(find.byKey(key)).height; DecoratedBox getDecoratedBox(Key key) => tester.firstWidget(find.descendant( of: find.byKey(key), matching: find.byType(DecoratedBox), )); expect(getHeight(topKey), getHeight(expandedKey) - getHeight(tileKey) - 2.0); expect(getHeight(topKey), getHeight(collapsedKey) - 2.0); expect(getHeight(topKey), getHeight(defaultKey) - 2.0); ShapeDecoration expandedContainerDecoration = getDecoratedBox(expandedKey).decoration as ShapeDecoration; expect(expandedContainerDecoration.color, Colors.red); expect((expandedContainerDecoration.shape as Border).top.color, dividerColor); expect((expandedContainerDecoration.shape as Border).bottom.color, dividerColor); ShapeDecoration collapsedContainerDecoration = getDecoratedBox(collapsedKey).decoration as ShapeDecoration; expect(collapsedContainerDecoration.color, Colors.transparent); expect((collapsedContainerDecoration.shape as Border).top.color, Colors.transparent); expect((collapsedContainerDecoration.shape as Border).bottom.color, Colors.transparent); await tester.tap(find.text('Expanded')); await tester.tap(find.text('Collapsed')); await tester.tap(find.text('Default')); await tester.pump(); // Pump to the middle of the animation for expansion. await tester.pump(const Duration(milliseconds: 100)); final ShapeDecoration collapsingContainerDecoration = getDecoratedBox(collapsedKey).decoration as ShapeDecoration; expect(collapsingContainerDecoration.color, Colors.transparent); expect((collapsingContainerDecoration.shape as Border).top.color, const Color(0x15222222)); expect((collapsingContainerDecoration.shape as Border).bottom.color, const Color(0x15222222)); // Pump all the way to the end now. await tester.pump(const Duration(seconds: 1)); expect(getHeight(topKey), getHeight(expandedKey) - 2.0); expect(getHeight(topKey), getHeight(collapsedKey) - getHeight(tileKey) - 2.0); expect(getHeight(topKey), getHeight(defaultKey) - getHeight(tileKey) - 2.0); // Expanded should be collapsed now. expandedContainerDecoration = getDecoratedBox(expandedKey).decoration as ShapeDecoration; expect(expandedContainerDecoration.color, Colors.transparent); expect((expandedContainerDecoration.shape as Border).top.color, Colors.transparent); expect((expandedContainerDecoration.shape as Border).bottom.color, Colors.transparent); // Collapsed should be expanded now. collapsedContainerDecoration = getDecoratedBox(collapsedKey).decoration as ShapeDecoration; expect(collapsedContainerDecoration.color, Colors.transparent); expect((collapsedContainerDecoration.shape as Border).top.color, dividerColor); expect((collapsedContainerDecoration.shape as Border).bottom.color, dividerColor); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('ExpansionTile Theme dependencies', (WidgetTester tester) async { final Key expandedTitleKey = UniqueKey(); final Key collapsedTitleKey = UniqueKey(); final Key expandedIconKey = UniqueKey(); final Key collapsedIconKey = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: ThemeData( useMaterial3: false, colorScheme: ColorScheme.fromSwatch().copyWith(primary: foregroundColor), unselectedWidgetColor: unselectedWidgetColor, textTheme: const TextTheme(titleMedium: TextStyle(color: headerColor)), ), home: Material( child: SingleChildScrollView( child: Column( children: <Widget>[ const ListTile(title: Text('Top')), ExpansionTile( initiallyExpanded: true, title: TestText('Expanded', key: expandedTitleKey), backgroundColor: Colors.red, trailing: TestIcon(key: expandedIconKey), children: const <Widget>[ListTile(title: Text('0'))], ), ExpansionTile( title: TestText('Collapsed', key: collapsedTitleKey), trailing: TestIcon(key: collapsedIconKey), children: const <Widget>[ListTile(title: Text('0'))], ), ], ), ), ), ), ); Color iconColor(Key key) => tester.state<TestIconState>(find.byKey(key)).iconTheme.color!; Color textColor(Key key) => tester.state<TestTextState>(find.byKey(key)).textStyle.color!; expect(textColor(expandedTitleKey), foregroundColor); expect(textColor(collapsedTitleKey), headerColor); expect(iconColor(expandedIconKey), foregroundColor); expect(iconColor(collapsedIconKey), unselectedWidgetColor); // Tap both tiles to change their state: collapse and extend respectively await tester.tap(find.text('Expanded')); await tester.tap(find.text('Collapsed')); await tester.pump(); await tester.pump(const Duration(seconds: 1)); await tester.pump(const Duration(seconds: 1)); expect(textColor(expandedTitleKey), headerColor); expect(textColor(collapsedTitleKey), foregroundColor); expect(iconColor(expandedIconKey), unselectedWidgetColor); expect(iconColor(collapsedIconKey), foregroundColor); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('ExpansionTile subtitle', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( body: ExpansionTile( title: Text('Title'), subtitle: Text('Subtitle'), children: <Widget>[ListTile(title: Text('0'))], ), ), ), ); expect(find.text('Subtitle'), findsOneWidget); }); testWidgets('ExpansionTile maintainState', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData( platform: TargetPlatform.iOS, dividerColor: dividerColor, ), home: const Material( child: SingleChildScrollView( child: Column( children: <Widget>[ ExpansionTile( title: Text('Tile 1'), maintainState: true, children: <Widget>[ Text('Maintaining State'), ], ), ExpansionTile( title: Text('Title 2'), children: <Widget>[ Text('Discarding State'), ], ), ], ), ), ), ), ); // This text should be offstage while ExpansionTile collapsed expect(find.text('Maintaining State', skipOffstage: false), findsOneWidget); expect(find.text('Maintaining State'), findsNothing); // This text shouldn't be there while ExpansionTile collapsed expect(find.text('Discarding State'), findsNothing); }); testWidgets('ExpansionTile padding test', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Material( child: Center( child: ExpansionTile( title: Text('Hello'), tilePadding: EdgeInsets.fromLTRB(8, 12, 4, 10), ), ), ), )); final Rect titleRect = tester.getRect(find.text('Hello')); final Rect trailingRect = tester.getRect(find.byIcon(Icons.expand_more)); final Rect listTileRect = tester.getRect(find.byType(ListTile)); final Rect tallerWidget = titleRect.height > trailingRect.height ? titleRect : trailingRect; // Check the positions of title and trailing Widgets, after padding is applied. expect(listTileRect.left, titleRect.left - 8); expect(listTileRect.right, trailingRect.right + 4); // Calculate the remaining height of ListTile from the default height. final double remainingHeight = 56 - tallerWidget.height; expect(listTileRect.top, tallerWidget.top - remainingHeight / 2 - 12); expect(listTileRect.bottom, tallerWidget.bottom + remainingHeight / 2 + 10); }); testWidgets('ExpansionTile expandedAlignment test', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Material( child: Center( child: ExpansionTile( title: Text('title'), expandedAlignment: Alignment.centerLeft, children: <Widget>[ SizedBox(height: 100, width: 100), SizedBox(height: 100, width: 80), ], ), ), ), )); await tester.tap(find.text('title')); await tester.pumpAndSettle(); final Rect columnRect = tester.getRect(find.byType(Column).last); // The expandedAlignment is used to define the alignment of the Column widget in // expanded tile, not the alignment of the children inside the Column. expect(columnRect.left, 0.0); // The width of the Column is the width of the largest child. The largest width // being 100.0, the offset of the right edge of Column from X-axis should be 100.0. expect(columnRect.right, 100.0); }); testWidgets('ExpansionTile expandedCrossAxisAlignment test', (WidgetTester tester) async { const Key child0Key = Key('child0'); const Key child1Key = Key('child1'); await tester.pumpWidget(const MaterialApp( home: Material( child: Center( child: ExpansionTile( title: Text('title'), // Set the column's alignment to Alignment.centerRight to test CrossAxisAlignment // of children widgets. This helps distinguish the effect of expandedAlignment // and expandedCrossAxisAlignment later in the test. expandedAlignment: Alignment.centerRight, expandedCrossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SizedBox(height: 100, width: 100, key: child0Key), SizedBox(height: 100, width: 80, key: child1Key), ], ), ), ), )); await tester.tap(find.text('title')); await tester.pumpAndSettle(); final Rect columnRect = tester.getRect(find.byType(Column).last); final Rect child0Rect = tester.getRect(find.byKey(child0Key)); final Rect child1Rect = tester.getRect(find.byKey(child1Key)); // Since expandedAlignment is set to Alignment.centerRight, the column of children // should be aligned to the center right of the expanded tile. This provides confirmation // that the expandedCrossAxisAlignment.start is 700.0, where columnRect.left is. expect(columnRect.right, 800.0); // The width of the Column is the width of the largest child. The largest width // being 100.0, the offset of the left edge of Column from X-axis should be 700.0. expect(columnRect.left, 700.0); // Considering the value of expandedCrossAxisAlignment is CrossAxisAlignment.start, // the offset of the left edge of both the children from X-axis should be 700.0. expect(child0Rect.left, 700.0); expect(child1Rect.left, 700.0); }); testWidgets('CrossAxisAlignment.baseline is not allowed', (WidgetTester tester) async { expect( () { MaterialApp( home: Material( child: ExpansionTile( initiallyExpanded: true, title: const Text('title'), expandedCrossAxisAlignment: CrossAxisAlignment.baseline, ), ), ); }, throwsA(isA<AssertionError>().having((AssertionError error) => error.toString(), '.toString()', contains( 'CrossAxisAlignment.baseline is not supported since the expanded' ' children are aligned in a column, not a row. Try to use another constant.', ))), ); }); testWidgets('expandedCrossAxisAlignment and expandedAlignment default values', (WidgetTester tester) async { const Key child1Key = Key('child1'); await tester.pumpWidget(const MaterialApp( home: Material( child: Center( child: ExpansionTile( title: Text('title'), children: <Widget>[ SizedBox(height: 100, width: 100), SizedBox(height: 100, width: 80, key: child1Key), ], ), ), ), )); await tester.tap(find.text('title')); await tester.pumpAndSettle(); final Rect columnRect = tester.getRect(find.byType(Column).last); final Rect child1Rect = tester.getRect(find.byKey(child1Key)); // The default viewport size is Size(800, 600). // By default the value of extendedAlignment is Alignment.center, hence the offset // of left and right edges from x axis should be equal. expect(columnRect.left, 800 - columnRect.right); // By default the value of extendedCrossAxisAlignment is CrossAxisAlignment.center, hence // the offset of left and right edges from Column should be equal. expect(child1Rect.left - columnRect.left, columnRect.right - child1Rect.right); }); testWidgets('childrenPadding default value', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: ExpansionTile( title: Text('title'), children: <Widget>[ SizedBox(height: 100, width: 100), ], ), ), ), ), ); await tester.tap(find.text('title')); await tester.pumpAndSettle(); final Rect columnRect = tester.getRect(find.byType(Column).last); final Rect paddingRect = tester.getRect(find.byType(Padding).last); // By default, the value of childrenPadding is EdgeInsets.zero, hence offset // of all the edges from x-axis and y-axis should be equal for Padding and Column. expect(columnRect.top, paddingRect.top); expect(columnRect.left, paddingRect.left); expect(columnRect.right, paddingRect.right); expect(columnRect.bottom, paddingRect.bottom); }); testWidgets('ExpansionTile childrenPadding test', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: ExpansionTile( title: Text('title'), childrenPadding: EdgeInsets.fromLTRB(10, 8, 12, 4), children: <Widget>[ SizedBox(height: 100, width: 100), ], ), ), ), ), ); await tester.tap(find.text('title')); await tester.pumpAndSettle(); final Rect columnRect = tester.getRect(find.byType(Column).last); final Rect paddingRect = tester.getRect(find.byType(Padding).last); // Check the offset of all the edges from x-axis and y-axis after childrenPadding // is applied. expect(columnRect.left, paddingRect.left + 10); expect(columnRect.top, paddingRect.top + 8); expect(columnRect.right, paddingRect.right - 12); expect(columnRect.bottom, paddingRect.bottom - 4); }); testWidgets('ExpansionTile.collapsedBackgroundColor', (WidgetTester tester) async { const Key expansionTileKey = Key('expansionTileKey'); const Color backgroundColor = Colors.red; const Color collapsedBackgroundColor = Colors.brown; await tester.pumpWidget(const MaterialApp( home: Material( child: ExpansionTile( key: expansionTileKey, title: Text('Title'), backgroundColor: backgroundColor, collapsedBackgroundColor: collapsedBackgroundColor, children: <Widget>[ SizedBox(height: 100, width: 100), ], ), ), )); ShapeDecoration shapeDecoration = tester.firstWidget<DecoratedBox>(find.descendant( of: find.byKey(expansionTileKey), matching: find.byType(DecoratedBox), )).decoration as ShapeDecoration; expect(shapeDecoration.color, collapsedBackgroundColor); await tester.tap(find.text('Title')); await tester.pumpAndSettle(); shapeDecoration = tester.firstWidget<DecoratedBox>(find.descendant( of: find.byKey(expansionTileKey), matching: find.byType(DecoratedBox), )).decoration as ShapeDecoration; expect(shapeDecoration.color, backgroundColor); }); testWidgets('ExpansionTile default iconColor, textColor', (WidgetTester tester) async { final ThemeData theme = ThemeData(useMaterial3: true); await tester.pumpWidget(MaterialApp( theme: theme, home: const Material( child: ExpansionTile( title: TestText('title'), trailing: TestIcon(), children: <Widget>[ SizedBox(height: 100, width: 100), ], ), ), )); Color getIconColor() => tester.state<TestIconState>(find.byType(TestIcon)).iconTheme.color!; Color getTextColor() => tester.state<TestTextState>(find.byType(TestText)).textStyle.color!; expect(getIconColor(), theme.colorScheme.onSurfaceVariant); expect(getTextColor(), theme.colorScheme.onSurface); await tester.tap(find.text('title')); await tester.pumpAndSettle(); expect(getIconColor(), theme.colorScheme.primary); expect(getTextColor(), theme.colorScheme.onSurface); }); testWidgets('ExpansionTile iconColor, textColor', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/pull/78281 const Color iconColor = Color(0xff00ff00); const Color collapsedIconColor = Color(0xff0000ff); const Color textColor = Color(0xff00ffff); const Color collapsedTextColor = Color(0xffff00ff); await tester.pumpWidget(const MaterialApp( home: Material( child: ExpansionTile( iconColor: iconColor, collapsedIconColor: collapsedIconColor, textColor: textColor, collapsedTextColor: collapsedTextColor, title: TestText('title'), trailing: TestIcon(), children: <Widget>[ SizedBox(height: 100, width: 100), ], ), ), )); Color getIconColor() => tester.state<TestIconState>(find.byType(TestIcon)).iconTheme.color!; Color getTextColor() => tester.state<TestTextState>(find.byType(TestText)).textStyle.color!; expect(getIconColor(), collapsedIconColor); expect(getTextColor(), collapsedTextColor); await tester.tap(find.text('title')); await tester.pumpAndSettle(); expect(getIconColor(), iconColor); expect(getTextColor(), textColor); }); testWidgets('ExpansionTile Border', (WidgetTester tester) async { const Key expansionTileKey = PageStorageKey<String>('expansionTile'); const Border collapsedShape = Border( top: BorderSide(color: Colors.blue), bottom: BorderSide(color: Colors.green) ); final Border shape = Border.all(color: Colors.red); await tester.pumpWidget(MaterialApp( home: Material( child: ExpansionTile( key: expansionTileKey, title: const Text('ExpansionTile'), collapsedShape: collapsedShape, shape: shape, children: const <Widget>[ ListTile( title: Text('0'), ), ], ), ), )); // When a custom shape is provided, ExpansionTile will use the // Material widget to draw the shape and background color // instead of a Container. Material material = getMaterial(tester); // ExpansionTile should be collapsed initially. expect(material.shape, collapsedShape); expect(material.clipBehavior, Clip.antiAlias); await tester.tap(find.text('ExpansionTile')); await tester.pumpAndSettle(); // ExpansionTile should be Expanded now. material = getMaterial(tester); expect(material.shape, shape); expect(material.clipBehavior, Clip.antiAlias); }); testWidgets('ExpansionTile platform controlAffinity test', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Material( child: ExpansionTile( title: Text('Title'), ), ), )); final ListTile listTile = tester.widget(find.byType(ListTile)); expect(listTile.leading, isNull); expect(listTile.trailing.runtimeType, RotationTransition); }); testWidgets('ExpansionTile trailing controlAffinity test', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Material( child: ExpansionTile( title: Text('Title'), controlAffinity: ListTileControlAffinity.trailing, ), ), )); final ListTile listTile = tester.widget(find.byType(ListTile)); expect(listTile.leading, isNull); expect(listTile.trailing.runtimeType, RotationTransition); }); testWidgets('ExpansionTile leading controlAffinity test', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Material( child: ExpansionTile( title: Text('Title'), controlAffinity: ListTileControlAffinity.leading, ), ), )); final ListTile listTile = tester.widget(find.byType(ListTile)); expect(listTile.leading.runtimeType, RotationTransition); expect(listTile.trailing, isNull); }); testWidgets('ExpansionTile override rotating icon test', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Material( child: ExpansionTile( title: Text('Title'), leading: Icon(Icons.info), controlAffinity: ListTileControlAffinity.leading, ), ), )); final ListTile listTile = tester.widget(find.byType(ListTile)); expect(listTile.leading.runtimeType, Icon); expect(listTile.trailing, isNull); }); testWidgets('Nested ListTile Semantics', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(const MaterialApp( home: Material( child: Column( children: <Widget>[ ExpansionTile( title: Text('First Expansion Tile'), ), ExpansionTile( initiallyExpanded: true, title: Text('Second Expansion Tile'), ), ], ), ), )); await tester.pumpAndSettle(); // Focus the first ExpansionTile. tester.binding.focusManager.primaryFocus?.nextFocus(); await tester.pumpAndSettle(); // The first list tile is focused. expect( tester.getSemantics(find.byType(ListTile).first), matchesSemantics( hasTapAction: true, hasEnabledState: true, isEnabled: true, isFocused: true, isFocusable: true, label: 'First Expansion Tile', textDirection: TextDirection.ltr, ), ); // The first list tile is not focused. expect( tester.getSemantics(find.byType(ListTile).last), matchesSemantics( hasTapAction: true, hasEnabledState: true, isEnabled: true, isFocusable: true, label: 'Second Expansion Tile', textDirection: TextDirection.ltr, ), ); handle.dispose(); }); testWidgets('ExpansionTile Semantics announcement', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); const DefaultMaterialLocalizations localizations = DefaultMaterialLocalizations(); await tester.pumpWidget( const MaterialApp( home: Material( child: ExpansionTile( title: Text('Title'), children: <Widget>[ SizedBox(height: 100, width: 100), ], ), ), ), ); // There is no semantics announcement without tap action. expect(tester.takeAnnouncements(), isEmpty); // Tap the title to expand ExpansionTile. await tester.tap(find.text('Title')); await tester.pumpAndSettle(); // The announcement should be the opposite of the current state. // The ExpansionTile is expanded, so the announcement should be // "Expanded". expect(tester.takeAnnouncements().first.message, localizations.collapsedHint); // Tap the title to collapse ExpansionTile. await tester.tap(find.text('Title')); await tester.pumpAndSettle(); // The announcement should be the opposite of the current state. // The ExpansionTile is collapsed, so the announcement should be // "Collapsed". expect(tester.takeAnnouncements().first.message, localizations.expandedHint); handle.dispose(); }); testWidgets('Semantics with the onTapHint is an ancestor of ListTile', (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/pull/121624 final SemanticsHandle handle = tester.ensureSemantics(); const DefaultMaterialLocalizations localizations = DefaultMaterialLocalizations(); await tester.pumpWidget(const MaterialApp( home: Material( child: Column( children: <Widget>[ ExpansionTile( title: Text('First Expansion Tile'), ), ExpansionTile( initiallyExpanded: true, title: Text('Second Expansion Tile'), ), ], ), ), )); SemanticsNode semantics = tester.getSemantics( find.ancestor( of: find.byType(ListTile).first, matching: find.byType(Semantics), ).first, ); expect(semantics, isNotNull); // The onTapHint is passed to semantics properties's hintOverrides. expect(semantics.hintOverrides, isNotNull); // The hint should be the opposite of the current state. // The first ExpansionTile is collapsed, so the hint should be // "double tap to expand". expect(semantics.hintOverrides!.onTapHint, localizations.expansionTileCollapsedTapHint); semantics = tester.getSemantics( find.ancestor( of: find.byType(ListTile).last, matching: find.byType(Semantics), ).first, ); expect(semantics, isNotNull); // The onTapHint is passed to semantics properties's hintOverrides. expect(semantics.hintOverrides, isNotNull); // The hint should be the opposite of the current state. // The second ExpansionTile is expanded, so the hint should be // "double tap to collapse". expect(semantics.hintOverrides!.onTapHint, localizations.expansionTileExpandedTapHint); handle.dispose(); }); testWidgets('Semantics hint for iOS and macOS', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); const DefaultMaterialLocalizations localizations = DefaultMaterialLocalizations(); await tester.pumpWidget(const MaterialApp( home: Material( child: Column( children: <Widget>[ ExpansionTile( title: Text('First Expansion Tile'), ), ExpansionTile( initiallyExpanded: true, title: Text('Second Expansion Tile'), ), ], ), ), )); SemanticsNode semantics = tester.getSemantics( find.ancestor( of: find.byType(ListTile).first, matching: find.byType(Semantics), ).first, ); expect(semantics, isNotNull); expect( semantics.hint, '${localizations.expandedHint}\n ${localizations.expansionTileCollapsedHint}', ); semantics = tester.getSemantics( find.ancestor( of: find.byType(ListTile).last, matching: find.byType(Semantics), ).first, ); expect(semantics, isNotNull); expect( semantics.hint, '${localizations.collapsedHint}\n ${localizations.expansionTileExpandedHint}', ); handle.dispose(); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('Collapsed ExpansionTile properties can be updated with setState', (WidgetTester tester) async { const Key expansionTileKey = Key('expansionTileKey'); ShapeBorder collapsedShape = const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(4)), ); Color collapsedTextColor = const Color(0xffffffff); Color collapsedBackgroundColor = const Color(0xffff0000); Color collapsedIconColor = const Color(0xffffffff); await tester.pumpWidget(MaterialApp( home: Material( child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Column( children: <Widget>[ ExpansionTile( key: expansionTileKey, collapsedShape: collapsedShape, collapsedTextColor: collapsedTextColor, collapsedBackgroundColor: collapsedBackgroundColor, collapsedIconColor: collapsedIconColor, title: const TestText('title'), trailing: const TestIcon(), children: const <Widget>[ SizedBox(height: 100, width: 100), ], ), // This button is used to update the ExpansionTile properties. FilledButton( onPressed: () { setState(() { collapsedShape = const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(16)), ); collapsedTextColor = const Color(0xff000000); collapsedBackgroundColor = const Color(0xffffff00); collapsedIconColor = const Color(0xff000000); }); }, child: const Text('Update collapsed properties'), ), ], ); } ), ), )); // When a custom shape is provided, ExpansionTile will use the // Material widget to draw the shape and background color // instead of a Container. Material material = getMaterial(tester); // Test initial ExpansionTile properties. expect(material.shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4)))); expect(material.color, const Color(0xffff0000)); expect(material.clipBehavior, Clip.antiAlias); expect(tester.state<TestIconState>(find.byType(TestIcon)).iconTheme.color, const Color(0xffffffff)); expect(tester.state<TestTextState>(find.byType(TestText)).textStyle.color, const Color(0xffffffff)); // Tap the button to update the ExpansionTile properties. await tester.tap(find.text('Update collapsed properties')); await tester.pumpAndSettle(); material = getMaterial(tester); // Test updated ExpansionTile properties. expect(material.shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16)))); expect(material.color, const Color(0xffffff00)); expect(material.clipBehavior, Clip.antiAlias); expect(tester.state<TestIconState>(find.byType(TestIcon)).iconTheme.color, const Color(0xff000000)); expect(tester.state<TestTextState>(find.byType(TestText)).textStyle.color, const Color(0xff000000)); }); testWidgets('Expanded ExpansionTile properties can be updated with setState', (WidgetTester tester) async { const Key expansionTileKey = Key('expansionTileKey'); ShapeBorder shape = const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(12)), ); Color textColor = const Color(0xff00ffff); Color backgroundColor = const Color(0xff0000ff); Color iconColor = const Color(0xff00ffff); await tester.pumpWidget(MaterialApp( home: Material( child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Column( children: <Widget>[ ExpansionTile( key: expansionTileKey, shape: shape, textColor: textColor, backgroundColor: backgroundColor, iconColor: iconColor, title: const TestText('title'), trailing: const TestIcon(), children: const <Widget>[ SizedBox(height: 100, width: 100), ], ), // This button is used to update the ExpansionTile properties. FilledButton( onPressed: () { setState(() { shape = const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(6)), ); textColor = const Color(0xffffffff); backgroundColor = const Color(0xff123456); iconColor = const Color(0xffffffff); }); }, child: const Text('Update collapsed properties'), ), ], ); } ), ), )); // Tap to expand the ExpansionTile. await tester.tap(find.text('title')); await tester.pumpAndSettle(); // When a custom shape is provided, ExpansionTile will use the // Material widget to draw the shape and background color // instead of a Container. Material material = getMaterial(tester); // Test initial ExpansionTile properties. expect(material.shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12)))); expect(material.color, const Color(0xff0000ff)); expect(material.clipBehavior, Clip.antiAlias); expect(tester.state<TestIconState>(find.byType(TestIcon)).iconTheme.color, const Color(0xff00ffff)); expect(tester.state<TestTextState>(find.byType(TestText)).textStyle.color, const Color(0xff00ffff)); // Tap the button to update the ExpansionTile properties. await tester.tap(find.text('Update collapsed properties')); await tester.pumpAndSettle(); material = getMaterial(tester); iconColor = tester.state<TestIconState>(find.byType(TestIcon)).iconTheme.color!; textColor = tester.state<TestTextState>(find.byType(TestText)).textStyle.color!; // Test updated ExpansionTile properties. expect(material.shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(6)))); expect(material.color, const Color(0xff123456)); expect(material.clipBehavior, Clip.antiAlias); expect(tester.state<TestIconState>(find.byType(TestIcon)).iconTheme.color, const Color(0xffffffff)); expect(tester.state<TestTextState>(find.byType(TestText)).textStyle.color, const Color(0xffffffff)); }); testWidgets('Override ExpansionTile animation using AnimationStyle', (WidgetTester tester) async { const Key expansionTileKey = Key('expansionTileKey'); Widget buildExpansionTile({ AnimationStyle? animationStyle }) { return MaterialApp( home: Material( child: Center( child: ExpansionTile( key: expansionTileKey, expansionAnimationStyle: animationStyle, title: const TestText('title'), children: const <Widget>[ SizedBox(height: 100, width: 100), ], ), ), ), ); } await tester.pumpWidget(buildExpansionTile()); double getHeight(Key key) => tester.getSize(find.byKey(key)).height; // Test initial ExpansionTile height. expect(getHeight(expansionTileKey), 58.0); // Test the default expansion animation. await tester.tap(find.text('title')); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); // Advance the animation by 1/4 of its duration. expect(getHeight(expansionTileKey), closeTo(67.4, 0.1)); await tester.pump(const Duration(milliseconds: 50)); // Advance the animation by 2/4 of its duration. expect(getHeight(expansionTileKey), closeTo(89.6, 0.1)); await tester.pumpAndSettle(); // Advance the animation to the end. expect(getHeight(expansionTileKey), 158.0); // Tap to collapse the ExpansionTile. await tester.tap(find.text('title')); await tester.pumpAndSettle(); // Override the animation duration. await tester.pumpWidget(buildExpansionTile(animationStyle: AnimationStyle(duration: const Duration(milliseconds: 800)))); await tester.pumpAndSettle(); // Test the overridden animation duration. await tester.tap(find.text('title')); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // Advance the animation by 1/4 of its duration. expect(getHeight(expansionTileKey), closeTo(67.4, 0.1)); await tester.pump(const Duration(milliseconds: 200)); // Advance the animation by 2/4 of its duration. expect(getHeight(expansionTileKey), closeTo(89.6, 0.1)); await tester.pumpAndSettle(); // Advance the animation to the end. expect(getHeight(expansionTileKey), 158.0); // Tap to collapse the ExpansionTile. await tester.tap(find.text('title')); await tester.pumpAndSettle(); // Override the animation curve. await tester.pumpWidget(buildExpansionTile(animationStyle: AnimationStyle(curve: Easing.emphasizedDecelerate))); await tester.pumpAndSettle(); // Test the overridden animation curve. await tester.tap(find.text('title')); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); // Advance the animation by 1/4 of its duration. expect(getHeight(expansionTileKey), closeTo(141.2, 0.1)); await tester.pump(const Duration(milliseconds: 50)); // Advance the animation by 2/4 of its duration. expect(getHeight(expansionTileKey), closeTo(153, 0.1)); await tester.pumpAndSettle(); // Advance the animation to the end. expect(getHeight(expansionTileKey), 158.0); // Tap to collapse the ExpansionTile. await tester.tap(find.text('title')); // Test no animation. await tester.pumpWidget(buildExpansionTile(animationStyle: AnimationStyle.noAnimation)); // Tap to expand the ExpansionTile. await tester.tap(find.text('title')); await tester.pump(); expect(getHeight(expansionTileKey), 158.0); }); testWidgets('Material3 - ExpansionTile draws Inkwell splash on top of background color', (WidgetTester tester) async { const Key expansionTileKey = Key('expansionTileKey'); const ShapeBorder shape = RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(16)), ); const ShapeBorder collapsedShape = RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(16)), ); const Color collapsedBackgroundColor = Color(0xff00ff00); const Color backgroundColor = Color(0xffff0000); await tester.pumpWidget(const MaterialApp( home: Material( child: Center( child: Padding( padding: EdgeInsets.symmetric(horizontal: 24.0), child: ExpansionTile( key: expansionTileKey, shape: shape, collapsedBackgroundColor: collapsedBackgroundColor, backgroundColor: backgroundColor, collapsedShape: collapsedShape, title: TestText('title'), trailing: TestIcon(), children: <Widget>[ SizedBox(height: 100, width: 100), ], ), ), ), ), )); // Tap and hold the ExpansionTile to trigger ink splash. final Offset center = tester.getCenter(find.byKey(expansionTileKey)); final TestGesture gesture = await tester.startGesture(center); await tester.pump(); // Start the splash animation. await tester.pump(const Duration(milliseconds: 100)); // Splash is underway. // Material 3 uses the InkSparkle which uses a shader, so we can't capture // the effect with paint methods. Use a golden test instead. // Check if the ink sparkle is drawn on top of the background color. await expectLater( find.byKey(expansionTileKey), matchesGoldenFile('expansion_tile.ink_splash.drawn_on_top_of_background_color.png'), ); // Finish gesture to release resources. await gesture.up(); await tester.pumpAndSettle(); }); testWidgets('Default clipBehavior when a shape is provided', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( body: ExpansionTile( title: Text('Title'), subtitle: Text('Subtitle'), shape: StadiumBorder(), children: <Widget>[ListTile(title: Text('0'))], ), ), ), ); expect(getMaterial(tester).clipBehavior, Clip.antiAlias); }); testWidgets('Can override clipBehavior when a shape is provided', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( body: ExpansionTile( title: Text('Title'), subtitle: Text('Subtitle'), shape: StadiumBorder(), clipBehavior: Clip.none, children: <Widget>[ListTile(title: Text('0'))], ), ), ), ); expect(getMaterial(tester).clipBehavior, Clip.none); }); group('Material 2', () { // These tests are only relevant for Material 2. Once Material 2 // support is deprecated and the APIs are removed, these tests // can be deleted. testWidgets('ExpansionTile default iconColor, textColor', (WidgetTester tester) async { final ThemeData theme = ThemeData(useMaterial3: false); await tester.pumpWidget(MaterialApp( theme: theme, home: const Material( child: ExpansionTile( title: TestText('title'), trailing: TestIcon(), children: <Widget>[ SizedBox(height: 100, width: 100), ], ), ), )); Color getIconColor() => tester.state<TestIconState>(find.byType(TestIcon)).iconTheme.color!; Color getTextColor() => tester.state<TestTextState>(find.byType(TestText)).textStyle.color!; expect(getIconColor(), theme.unselectedWidgetColor); expect(getTextColor(), theme.textTheme.titleMedium!.color); await tester.tap(find.text('title')); await tester.pumpAndSettle(); expect(getIconColor(), theme.colorScheme.primary); expect(getTextColor(), theme.colorScheme.primary); }); testWidgets('Material2 - ExpansionTile draws inkwell splash on top of background color', (WidgetTester tester) async { const Key expansionTileKey = Key('expansionTileKey'); final ThemeData theme = ThemeData(useMaterial3: false); const ShapeBorder shape = RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(16)), ); const ShapeBorder collapsedShape = RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(16)), ); const Color collapsedBackgroundColor = Color(0xff00ff00); const Color backgroundColor = Color(0xffff0000); await tester.pumpWidget(MaterialApp( theme: theme, home: const Material( child: Center( child: Padding( padding: EdgeInsets.symmetric(horizontal: 24.0), child: ExpansionTile( key: expansionTileKey, shape: shape, collapsedBackgroundColor: collapsedBackgroundColor, backgroundColor: backgroundColor, collapsedShape: collapsedShape, title: TestText('title'), trailing: TestIcon(), children: <Widget>[ SizedBox(height: 100, width: 100), ], ), ), ), ), )); // Tap and hold the ExpansionTile to trigger ink splash. final Offset center = tester.getCenter(find.byKey(expansionTileKey)); final TestGesture gesture = await tester.startGesture(center); await tester.pump(); // Start the splash animation. await tester.pump(const Duration(milliseconds: 100)); // Splash is underway. final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); // Check if the ink splash is drawn on top of the background color. expect(inkFeatures, paints..path(color: collapsedBackgroundColor)..circle(color: theme.splashColor)); // Finish gesture to release resources. await gesture.up(); await tester.pumpAndSettle(); }); }); testWidgets('ExpansionTileController isExpanded, expand() and collapse()', (WidgetTester tester) async { final ExpansionTileController controller = ExpansionTileController(); await tester.pumpWidget(MaterialApp( home: Material( child: ExpansionTile( controller: controller, title: const Text('Title'), children: const <Widget>[ Text('Child 0'), ], ), ), )); expect(find.text('Child 0'), findsNothing); expect(controller.isExpanded, isFalse); controller.expand(); expect(controller.isExpanded, isTrue); await tester.pumpAndSettle(); expect(find.text('Child 0'), findsOneWidget); expect(controller.isExpanded, isTrue); controller.collapse(); expect(controller.isExpanded, isFalse); await tester.pumpAndSettle(); expect(find.text('Child 0'), findsNothing); }); testWidgets('Calling ExpansionTileController.expand/collapsed has no effect if it is already expanded/collapsed', (WidgetTester tester) async { final ExpansionTileController controller = ExpansionTileController(); await tester.pumpWidget(MaterialApp( home: Material( child: ExpansionTile( controller: controller, title: const Text('Title'), initiallyExpanded: true, children: const <Widget>[ Text('Child 0'), ], ), ), )); expect(find.text('Child 0'), findsOneWidget); expect(controller.isExpanded, isTrue); controller.expand(); expect(controller.isExpanded, isTrue); await tester.pump(); expect(tester.hasRunningAnimations, isFalse); expect(find.text('Child 0'), findsOneWidget); controller.collapse(); expect(controller.isExpanded, isFalse); await tester.pump(); expect(tester.hasRunningAnimations, isTrue); await tester.pumpAndSettle(); expect(controller.isExpanded, isFalse); expect(find.text('Child 0'), findsNothing); controller.collapse(); expect(controller.isExpanded, isFalse); await tester.pump(); expect(tester.hasRunningAnimations, isFalse); }); testWidgets('Call to ExpansionTileController.of()', (WidgetTester tester) async { final GlobalKey titleKey = GlobalKey(); final GlobalKey childKey = GlobalKey(); await tester.pumpWidget(MaterialApp( home: Material( child: ExpansionTile( initiallyExpanded: true, title: Text('Title', key: titleKey), children: <Widget>[ Text('Child 0', key: childKey), ], ), ), )); final ExpansionTileController controller1 = ExpansionTileController.of(childKey.currentContext!); expect(controller1.isExpanded, isTrue); final ExpansionTileController controller2 = ExpansionTileController.of(titleKey.currentContext!); expect(controller2.isExpanded, isTrue); expect(controller1, controller2); }); testWidgets('Call to ExpansionTile.maybeOf()', (WidgetTester tester) async { final GlobalKey titleKey = GlobalKey(); final GlobalKey nonDescendantKey = GlobalKey(); await tester.pumpWidget(MaterialApp( home: Material( child: Column( children: <Widget>[ ExpansionTile( title: Text('Title', key: titleKey), children: const <Widget>[ Text('Child 0'), ], ), Text('Non descendant', key: nonDescendantKey), ], ), ), )); final ExpansionTileController? controller1 = ExpansionTileController.maybeOf(titleKey.currentContext!); expect(controller1, isNotNull); expect(controller1?.isExpanded, isFalse); final ExpansionTileController? controller2 = ExpansionTileController.maybeOf(nonDescendantKey.currentContext!); expect(controller2, isNull); }); testWidgets('Check if dense, enableFeedback, visualDensity parameter is working', (WidgetTester tester) async { final GlobalKey titleKey = GlobalKey(); final GlobalKey nonDescendantKey = GlobalKey(); const bool dense = true; const bool enableFeedback = false; const VisualDensity visualDensity = VisualDensity.compact; await tester.pumpWidget(MaterialApp( home: Material( child: Column( children: <Widget>[ ExpansionTile( dense: dense, enableFeedback: enableFeedback, visualDensity: visualDensity, title: Text('Title', key: titleKey), children: const <Widget>[ Text('Child 0'), ], ), Text('Non descendant', key: nonDescendantKey), ], ), ), )); final Finder tileFinder = find.byType(ListTile); final ListTile tileWidget = tester.widget<ListTile>(tileFinder); expect(tileWidget.dense, dense); expect(tileWidget.enableFeedback, enableFeedback); expect(tileWidget.visualDensity, visualDensity); }); testWidgets('ExpansionTileController should not toggle if disabled', (WidgetTester tester) async { final ExpansionTileController controller = ExpansionTileController(); await tester.pumpWidget(MaterialApp( home: Material( child: ExpansionTile( enabled: false, controller: controller, title: const Text('Title'), children: const <Widget>[ Text('Child 0'), ], ), ), )); expect(find.text('Child 0'), findsNothing); expect(controller.isExpanded, isFalse); await tester.tap(find.widgetWithText(ExpansionTile, 'Title')); await tester.pumpAndSettle(); expect(find.text('Child 0'), findsNothing); expect(controller.isExpanded, isFalse); controller.expand(); await tester.pumpAndSettle(); expect(find.text('Child 0'), findsOneWidget); expect(controller.isExpanded, isTrue); await tester.tap(find.widgetWithText(ExpansionTile, 'Title')); await tester.pumpAndSettle(); expect(find.text('Child 0'), findsOneWidget); expect(controller.isExpanded, isTrue); }); }
flutter/packages/flutter/test/material/expansion_tile_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/expansion_tile_test.dart", "repo_id": "flutter", "token_count": 21262 }
669
// 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 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('IconButtonThemeData lerp special cases', () { expect(IconButtonThemeData.lerp(null, null, 0), null); const IconButtonThemeData data = IconButtonThemeData(); expect(identical(IconButtonThemeData.lerp(data, data, 0.5), data), true); }); testWidgets('Passing no IconButtonTheme returns defaults', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.light(); await tester.pumpWidget( MaterialApp( theme: ThemeData.from(colorScheme: colorScheme, useMaterial3: true), home: Scaffold( body: Center( child: IconButton( onPressed: () { }, icon: const Icon(Icons.ac_unit), ), ), ), ), ); final Finder buttonMaterial = find.descendant( of: find.byType(IconButton), matching: find.byType(Material), ); final Material material = tester.widget<Material>(buttonMaterial); expect(material.animationDuration, const Duration(milliseconds: 200)); expect(material.borderRadius, null); expect(material.color, Colors.transparent); expect(material.elevation, 0.0); expect(material.shadowColor, Colors.transparent); expect(material.shape, const StadiumBorder()); expect(material.textStyle, null); expect(material.type, MaterialType.button); final Align align = tester.firstWidget<Align>(find.ancestor(of: find.byIcon(Icons.ac_unit), matching: find.byType(Align))); expect(align.alignment, Alignment.center); }); group('[Theme, IconTheme, IconButton style overrides]', () { const Color foregroundColor = Color(0xff000001); const Color disabledForegroundColor = Color(0xff000002); const Color backgroundColor = Color(0xff000003); const Color shadowColor = Color(0xff000004); const double elevation = 3; const EdgeInsets padding = EdgeInsets.all(3); const Size minimumSize = Size(200, 200); const BorderSide side = BorderSide(color: Colors.green, width: 2); const OutlinedBorder shape = RoundedRectangleBorder(side: side, borderRadius: BorderRadius.all(Radius.circular(2))); const MouseCursor enabledMouseCursor = SystemMouseCursors.text; const MouseCursor disabledMouseCursor = SystemMouseCursors.grab; const MaterialTapTargetSize tapTargetSize = MaterialTapTargetSize.shrinkWrap; const Duration animationDuration = Duration(milliseconds: 25); const bool enableFeedback = false; const AlignmentGeometry alignment = Alignment.centerLeft; final ButtonStyle style = IconButton.styleFrom( foregroundColor: foregroundColor, disabledForegroundColor: disabledForegroundColor, backgroundColor: backgroundColor, shadowColor: shadowColor, elevation: elevation, padding: padding, minimumSize: minimumSize, side: side, shape: shape, enabledMouseCursor: enabledMouseCursor, disabledMouseCursor: disabledMouseCursor, tapTargetSize: tapTargetSize, animationDuration: animationDuration, enableFeedback: enableFeedback, alignment: alignment, ); Widget buildFrame({ ButtonStyle? buttonStyle, ButtonStyle? themeStyle, ButtonStyle? overallStyle }) { final Widget child = Builder( builder: (BuildContext context) { return IconButton( style: buttonStyle, onPressed: () { }, icon: const Icon(Icons.ac_unit), ); }, ); return MaterialApp( theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true).copyWith( iconButtonTheme: IconButtonThemeData(style: overallStyle), ), home: Scaffold( body: Center( // If the IconButtonTheme widget is present, it's used // instead of the Theme's ThemeData.iconButtonTheme. child: themeStyle == null ? child : IconButtonTheme( data: IconButtonThemeData(style: themeStyle), child: child, ), ), ), ); } final Finder findMaterial = find.descendant( of: find.byType(IconButton), matching: find.byType(Material), ); final Finder findInkWell = find.descendant( of: find.byType(IconButton), matching: find.byType(InkWell), ); const Set<MaterialState> enabled = <MaterialState>{}; const Set<MaterialState> disabled = <MaterialState>{ MaterialState.disabled }; const Set<MaterialState> hovered = <MaterialState>{ MaterialState.hovered }; const Set<MaterialState> focused = <MaterialState>{ MaterialState.focused }; const Set<MaterialState> pressed = <MaterialState>{ MaterialState.pressed }; void checkButton(WidgetTester tester) { final Material material = tester.widget<Material>(findMaterial); final InkWell inkWell = tester.widget<InkWell>(findInkWell); expect(material.textStyle, null); expect(material.color, backgroundColor); expect(material.shadowColor, shadowColor); expect(material.elevation, elevation); expect(MaterialStateProperty.resolveAs<MouseCursor?>(inkWell.mouseCursor, enabled), enabledMouseCursor); expect(MaterialStateProperty.resolveAs<MouseCursor?>(inkWell.mouseCursor, disabled), disabledMouseCursor); expect(inkWell.overlayColor!.resolve(hovered), foregroundColor.withOpacity(0.08)); expect(inkWell.overlayColor!.resolve(focused), foregroundColor.withOpacity(0.1)); expect(inkWell.overlayColor!.resolve(pressed), foregroundColor.withOpacity(0.1)); expect(inkWell.enableFeedback, enableFeedback); expect(material.borderRadius, null); expect(material.shape, shape); expect(material.animationDuration, animationDuration); expect(tester.getSize(find.byType(IconButton)), const Size(200, 200)); final Align align = tester.firstWidget<Align>(find.ancestor(of: find.byIcon(Icons.ac_unit), matching: find.byType(Align))); expect(align.alignment, alignment); } testWidgets('Button style overrides defaults', (WidgetTester tester) async { await tester.pumpWidget(buildFrame(buttonStyle: style)); await tester.pumpAndSettle(); // allow the animations to finish checkButton(tester); }); testWidgets('Button theme style overrides defaults', (WidgetTester tester) async { await tester.pumpWidget(buildFrame(themeStyle: style)); await tester.pumpAndSettle(); checkButton(tester); }); testWidgets('Overall Theme button theme style overrides defaults', (WidgetTester tester) async { await tester.pumpWidget(buildFrame(overallStyle: style)); await tester.pumpAndSettle(); checkButton(tester); }); // Same as the previous tests with empty ButtonStyle's instead of null. testWidgets('Button style overrides defaults, empty theme and overall styles', (WidgetTester tester) async { await tester.pumpWidget(buildFrame(buttonStyle: style, themeStyle: const ButtonStyle(), overallStyle: const ButtonStyle())); await tester.pumpAndSettle(); // allow the animations to finish checkButton(tester); }); testWidgets('Button theme style overrides defaults, empty button and overall styles', (WidgetTester tester) async { await tester.pumpWidget(buildFrame(buttonStyle: const ButtonStyle(), themeStyle: style, overallStyle: const ButtonStyle())); await tester.pumpAndSettle(); // allow the animations to finish checkButton(tester); }); testWidgets('Overall Theme button theme style overrides defaults, null theme and empty overall style', (WidgetTester tester) async { await tester.pumpWidget(buildFrame(buttonStyle: const ButtonStyle(), overallStyle: style)); await tester.pumpAndSettle(); // allow the animations to finish checkButton(tester); }); }); testWidgets('Theme shadowColor', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.light(); const Color shadowColor = Color(0xff000001); const Color overriddenColor = Color(0xff000002); Widget buildFrame({ Color? overallShadowColor, Color? themeShadowColor, Color? shadowColor }) { return MaterialApp( theme: ThemeData.from(colorScheme: colorScheme, useMaterial3: true).copyWith( shadowColor: overallShadowColor, ), home: Scaffold( body: Center( child: IconButtonTheme( data: IconButtonThemeData( style: IconButton.styleFrom( shadowColor: themeShadowColor, ), ), child: Builder( builder: (BuildContext context) { return IconButton( style: IconButton.styleFrom( shadowColor: shadowColor, ), onPressed: () { }, icon: const Icon(Icons.add), ); }, ), ), ), ), ); } final Finder buttonMaterialFinder = find.descendant( of: find.byType(IconButton), matching: find.byType(Material), ); await tester.pumpWidget(buildFrame()); Material material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, Colors.transparent); //default await tester.pumpWidget(buildFrame(overallShadowColor: shadowColor)); await tester.pumpAndSettle(); // theme animation material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, Colors.transparent); await tester.pumpWidget(buildFrame(themeShadowColor: shadowColor)); await tester.pumpAndSettle(); // theme animation material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, shadowColor); await tester.pumpWidget(buildFrame(shadowColor: shadowColor)); await tester.pumpAndSettle(); // theme animation material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, shadowColor); await tester.pumpWidget(buildFrame(overallShadowColor: overriddenColor, themeShadowColor: shadowColor)); await tester.pumpAndSettle(); // theme animation material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, shadowColor); await tester.pumpWidget(buildFrame(themeShadowColor: overriddenColor, shadowColor: shadowColor)); await tester.pumpAndSettle(); // theme animation material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, shadowColor); }); }
flutter/packages/flutter/test/material/icon_button_theme_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/icon_button_theme_test.dart", "repo_id": "flutter", "token_count": 3929 }
670
// 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 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('MaterialStateProperty.resolveWith()', () { final MaterialStateProperty<MaterialState> value = MaterialStateProperty.resolveWith<MaterialState>( (Set<MaterialState> states) => states.first, ); expect(value.resolve(<MaterialState>{MaterialState.hovered}), MaterialState.hovered); expect(value.resolve(<MaterialState>{MaterialState.focused}), MaterialState.focused); expect(value.resolve(<MaterialState>{MaterialState.pressed}), MaterialState.pressed); expect(value.resolve(<MaterialState>{MaterialState.dragged}), MaterialState.dragged); expect(value.resolve(<MaterialState>{MaterialState.selected}), MaterialState.selected); expect(value.resolve(<MaterialState>{MaterialState.disabled}), MaterialState.disabled); expect(value.resolve(<MaterialState>{MaterialState.error}), MaterialState.error); }); test('MaterialStateProperty.all()', () { final MaterialStateProperty<int> value = MaterialStateProperty.all<int>(123); expect(value.resolve(<MaterialState>{MaterialState.hovered}), 123); expect(value.resolve(<MaterialState>{MaterialState.focused}), 123); expect(value.resolve(<MaterialState>{MaterialState.pressed}), 123); expect(value.resolve(<MaterialState>{MaterialState.dragged}), 123); expect(value.resolve(<MaterialState>{MaterialState.selected}), 123); expect(value.resolve(<MaterialState>{MaterialState.disabled}), 123); expect(value.resolve(<MaterialState>{MaterialState.error}), 123); }); test('MaterialStatePropertyAll', () { const MaterialStatePropertyAll<int> value = MaterialStatePropertyAll<int>(123); expect(value.resolve(<MaterialState>{}), 123); expect(value.resolve(<MaterialState>{MaterialState.hovered}), 123); expect(value.resolve(<MaterialState>{MaterialState.focused}), 123); expect(value.resolve(<MaterialState>{MaterialState.pressed}), 123); expect(value.resolve(<MaterialState>{MaterialState.dragged}), 123); expect(value.resolve(<MaterialState>{MaterialState.selected}), 123); expect(value.resolve(<MaterialState>{MaterialState.disabled}), 123); expect(value.resolve(<MaterialState>{MaterialState.error}), 123); }); test('toString formats correctly', () { const MaterialStateProperty<Color?> colorProperty = MaterialStatePropertyAll<Color?>(Color(0xFFFFFFFF)); expect(colorProperty.toString(), equals('WidgetStatePropertyAll(Color(0xffffffff))')); const MaterialStateProperty<double?> doubleProperty = MaterialStatePropertyAll<double?>(33 + 1/3); expect(doubleProperty.toString(), equals('WidgetStatePropertyAll(33.3)')); }); test("Can interpolate between two MaterialStateProperty's", () { const MaterialStateProperty<TextStyle?> textStyle1 = MaterialStatePropertyAll<TextStyle?>( TextStyle(fontSize: 14.0), ); const MaterialStateProperty<TextStyle?> textStyle2 = MaterialStatePropertyAll<TextStyle?>( TextStyle(fontSize: 20.0), ); // Using `0.0` interpolation value. TextStyle textStyle = MaterialStateProperty.lerp<TextStyle?>( textStyle1, textStyle2, 0.0, TextStyle.lerp, )!.resolve(enabled)!; expect(textStyle.fontSize, 14.0); // Using `0.5` interpolation value. textStyle = MaterialStateProperty.lerp<TextStyle?>( textStyle1, textStyle2, 0.5, TextStyle.lerp, )!.resolve(enabled)!; expect(textStyle.fontSize, 17.0); // Using `1.0` interpolation value. textStyle = MaterialStateProperty.lerp<TextStyle?>( textStyle1, textStyle2, 1.0, TextStyle.lerp, )!.resolve(enabled)!; expect(textStyle.fontSize, 20.0); }); } Set<MaterialState> enabled = <MaterialState>{};
flutter/packages/flutter/test/material/material_state_property_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/material_state_property_test.dart", "repo_id": "flutter", "token_count": 1343 }
671
// 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 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('OutlinedButtonThemeData lerp special cases', () { expect(OutlinedButtonThemeData.lerp(null, null, 0), null); const OutlinedButtonThemeData data = OutlinedButtonThemeData(); expect(identical(OutlinedButtonThemeData.lerp(data, data, 0.5), data), true); }); testWidgets('Material3: Passing no OutlinedButtonTheme returns defaults', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.light(); await tester.pumpWidget( MaterialApp( theme: ThemeData.from(useMaterial3: true, colorScheme: colorScheme), home: Scaffold( body: Center( child: OutlinedButton( onPressed: () { }, child: const Text('button'), ), ), ), ), ); final Finder buttonMaterial = find.descendant( of: find.byType(OutlinedButton), matching: find.byType(Material), ); final Material material = tester.widget<Material>(buttonMaterial); expect(material.animationDuration, const Duration(milliseconds: 200)); expect(material.borderRadius, null); expect(material.color, Colors.transparent); expect(material.elevation, 0.0); expect(material.shadowColor, Colors.transparent); expect(material.shape, isInstanceOf<StadiumBorder>()); final StadiumBorder materialShape = material.shape! as StadiumBorder; expect(materialShape.side, BorderSide(color: colorScheme.outline)); expect(material.textStyle!.color, colorScheme.primary); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); final Align align = tester.firstWidget<Align>(find.ancestor(of: find.text('button'), matching: find.byType(Align))); expect(align.alignment, Alignment.center); }); testWidgets('Material2: Passing no OutlinedButtonTheme returns defaults', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.light(); await tester.pumpWidget( MaterialApp( theme: ThemeData.from(useMaterial3: false, colorScheme: colorScheme), home: Scaffold( body: Center( child: OutlinedButton( onPressed: () { }, child: const Text('button'), ), ), ), ), ); final Finder buttonMaterial = find.descendant( of: find.byType(OutlinedButton), matching: find.byType(Material), ); final Material material = tester.widget<Material>(buttonMaterial); expect(material.animationDuration, const Duration(milliseconds: 200)); expect(material.borderRadius, null); expect(material.color, Colors.transparent); expect(material.elevation, 0.0); expect(material.shadowColor, Colors.black); expect(material.shape, isInstanceOf<RoundedRectangleBorder>()); final RoundedRectangleBorder materialShape = material.shape! as RoundedRectangleBorder; expect(materialShape.side, BorderSide(color: colorScheme.onSurface.withOpacity(0.12))); expect(materialShape.borderRadius, const BorderRadius.all(Radius.circular(4.0))); expect(material.textStyle!.color, colorScheme.primary); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); final Align align = tester.firstWidget<Align>(find.ancestor(of: find.text('button'), matching: find.byType(Align))); expect(align.alignment, Alignment.center); }); group('[Theme, TextTheme, OutlinedButton style overrides]', () { const Color foregroundColor = Color(0xff000001); const Color backgroundColor = Color(0xff000002); const Color disabledColor = Color(0xff000003); const Color shadowColor = Color(0xff000004); const double elevation = 3; const TextStyle textStyle = TextStyle(fontSize: 12.0); const EdgeInsets padding = EdgeInsets.all(3); const Size minimumSize = Size(200, 200); const BorderSide side = BorderSide(color: Colors.green, width: 2); const OutlinedBorder shape = RoundedRectangleBorder(side: side, borderRadius: BorderRadius.all(Radius.circular(2))); const MouseCursor enabledMouseCursor = SystemMouseCursors.text; const MouseCursor disabledMouseCursor = SystemMouseCursors.grab; const MaterialTapTargetSize tapTargetSize = MaterialTapTargetSize.shrinkWrap; const Duration animationDuration = Duration(milliseconds: 25); const bool enableFeedback = false; const AlignmentGeometry alignment = Alignment.centerLeft; final ButtonStyle style = OutlinedButton.styleFrom( foregroundColor: foregroundColor, disabledForegroundColor: disabledColor, backgroundColor: backgroundColor, disabledBackgroundColor: disabledColor, shadowColor: shadowColor, elevation: elevation, textStyle: textStyle, padding: padding, minimumSize: minimumSize, side: side, shape: shape, enabledMouseCursor: enabledMouseCursor, disabledMouseCursor: disabledMouseCursor, tapTargetSize: tapTargetSize, animationDuration: animationDuration, enableFeedback: enableFeedback, alignment: alignment, ); Widget buildFrame({ ButtonStyle? buttonStyle, ButtonStyle? themeStyle, ButtonStyle? overallStyle }) { final Widget child = Builder( builder: (BuildContext context) { return OutlinedButton( style: buttonStyle, onPressed: () { }, child: const Text('button'), ); }, ); return MaterialApp( theme: ThemeData.from(colorScheme: const ColorScheme.light()).copyWith( outlinedButtonTheme: OutlinedButtonThemeData(style: overallStyle), ), home: Scaffold( body: Center( // If the OutlinedButtonTheme widget is present, it's used // instead of the Theme's ThemeData.outlinedButtonTheme. child: themeStyle == null ? child : OutlinedButtonTheme( data: OutlinedButtonThemeData(style: themeStyle), child: child, ), ), ), ); } final Finder findMaterial = find.descendant( of: find.byType(OutlinedButton), matching: find.byType(Material), ); final Finder findInkWell = find.descendant( of: find.byType(OutlinedButton), matching: find.byType(InkWell), ); const Set<MaterialState> enabled = <MaterialState>{}; const Set<MaterialState> disabled = <MaterialState>{ MaterialState.disabled }; const Set<MaterialState> hovered = <MaterialState>{ MaterialState.hovered }; const Set<MaterialState> focused = <MaterialState>{ MaterialState.focused }; void checkButton(WidgetTester tester) { final Material material = tester.widget<Material>(findMaterial); final InkWell inkWell = tester.widget<InkWell>(findInkWell); expect(material.textStyle!.color, foregroundColor); expect(material.textStyle!.fontSize, 12); expect(material.color, backgroundColor); expect(material.shadowColor, shadowColor); expect(material.elevation, elevation); expect(MaterialStateProperty.resolveAs<MouseCursor?>(inkWell.mouseCursor, enabled), enabledMouseCursor); expect(MaterialStateProperty.resolveAs<MouseCursor?>(inkWell.mouseCursor, disabled), disabledMouseCursor); expect(inkWell.overlayColor!.resolve(hovered), foregroundColor.withOpacity(0.08)); expect(inkWell.overlayColor!.resolve(focused), foregroundColor.withOpacity(0.1)); expect(inkWell.enableFeedback, enableFeedback); expect(material.borderRadius, null); expect(material.shape, shape); expect(material.animationDuration, animationDuration); expect(tester.getSize(find.byType(OutlinedButton)), const Size(200, 200)); final Align align = tester.firstWidget<Align>(find.ancestor(of: find.text('button'), matching: find.byType(Align))); expect(align.alignment, alignment); } testWidgets('Button style overrides defaults', (WidgetTester tester) async { await tester.pumpWidget(buildFrame(buttonStyle: style)); await tester.pumpAndSettle(); // allow the animations to finish checkButton(tester); }); testWidgets('Button theme style overrides defaults', (WidgetTester tester) async { await tester.pumpWidget(buildFrame(themeStyle: style)); await tester.pumpAndSettle(); checkButton(tester); }); testWidgets('Overall Theme button theme style overrides defaults', (WidgetTester tester) async { await tester.pumpWidget(buildFrame(overallStyle: style)); await tester.pumpAndSettle(); checkButton(tester); }); // Same as the previous tests with empty ButtonStyle's instead of null. testWidgets('Button style overrides defaults, empty theme and overall styles', (WidgetTester tester) async { await tester.pumpWidget(buildFrame(buttonStyle: style, themeStyle: const ButtonStyle(), overallStyle: const ButtonStyle())); await tester.pumpAndSettle(); // allow the animations to finish checkButton(tester); }); testWidgets('Button theme style overrides defaults, empty button and overall styles', (WidgetTester tester) async { await tester.pumpWidget(buildFrame(buttonStyle: const ButtonStyle(), themeStyle: style, overallStyle: const ButtonStyle())); await tester.pumpAndSettle(); // allow the animations to finish checkButton(tester); }); testWidgets('Overall Theme button theme style overrides defaults, null theme and empty overall style', (WidgetTester tester) async { await tester.pumpWidget(buildFrame(buttonStyle: const ButtonStyle(), overallStyle: style)); await tester.pumpAndSettle(); // allow the animations to finish checkButton(tester); }); }); testWidgets('Material3: Theme shadowColor', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.light(); const Color shadowColor = Color(0xff000001); const Color overriddenColor = Color(0xff000002); Widget buildFrame({ Color? overallShadowColor, Color? themeShadowColor, Color? shadowColor }) { return MaterialApp( theme: ThemeData.from( useMaterial3: true, colorScheme: colorScheme.copyWith(shadow: overallShadowColor), ), home: Scaffold( body: Center( child: OutlinedButtonTheme( data: OutlinedButtonThemeData( style: OutlinedButton.styleFrom( shadowColor: themeShadowColor, ), ), child: Builder( builder: (BuildContext context) { return OutlinedButton( style: OutlinedButton.styleFrom( shadowColor: shadowColor, ), onPressed: () { }, child: const Text('button'), ); }, ), ), ), ), ); } final Finder buttonMaterialFinder = find.descendant( of: find.byType(OutlinedButton), matching: find.byType(Material), ); await tester.pumpWidget(buildFrame()); Material material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, Colors.transparent); await tester.pumpWidget(buildFrame(overallShadowColor: shadowColor)); await tester.pumpAndSettle(); // theme animation material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, Colors.transparent); await tester.pumpWidget(buildFrame(themeShadowColor: shadowColor)); await tester.pumpAndSettle(); // theme animation material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, shadowColor); await tester.pumpWidget(buildFrame(shadowColor: shadowColor)); await tester.pumpAndSettle(); // theme animation material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, shadowColor); await tester.pumpWidget(buildFrame(overallShadowColor: overriddenColor, themeShadowColor: shadowColor)); await tester.pumpAndSettle(); // theme animation material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, shadowColor); await tester.pumpWidget(buildFrame(themeShadowColor: overriddenColor, shadowColor: shadowColor)); await tester.pumpAndSettle(); // theme animation material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, shadowColor); }); testWidgets('Material2: Theme shadowColor', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.light(); const Color shadowColor = Color(0xff000001); const Color overriddenColor = Color(0xff000002); Widget buildFrame({ Color? overallShadowColor, Color? themeShadowColor, Color? shadowColor }) { return MaterialApp( theme: ThemeData.from(useMaterial3: false, colorScheme: colorScheme).copyWith( shadowColor: overallShadowColor, ), home: Scaffold( body: Center( child: OutlinedButtonTheme( data: OutlinedButtonThemeData( style: OutlinedButton.styleFrom( shadowColor: themeShadowColor, ), ), child: Builder( builder: (BuildContext context) { return OutlinedButton( style: OutlinedButton.styleFrom( shadowColor: shadowColor, ), onPressed: () { }, child: const Text('button'), ); }, ), ), ), ), ); } final Finder buttonMaterialFinder = find.descendant( of: find.byType(OutlinedButton), matching: find.byType(Material), ); await tester.pumpWidget(buildFrame()); Material material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, Colors.black); //default await tester.pumpWidget(buildFrame(overallShadowColor: shadowColor)); await tester.pumpAndSettle(); // theme animation material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, shadowColor); await tester.pumpWidget(buildFrame(themeShadowColor: shadowColor)); await tester.pumpAndSettle(); // theme animation material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, shadowColor); await tester.pumpWidget(buildFrame(shadowColor: shadowColor)); await tester.pumpAndSettle(); // theme animation material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, shadowColor); await tester.pumpWidget(buildFrame(overallShadowColor: overriddenColor, themeShadowColor: shadowColor)); await tester.pumpAndSettle(); // theme animation material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, shadowColor); await tester.pumpWidget(buildFrame(themeShadowColor: overriddenColor, shadowColor: shadowColor)); await tester.pumpAndSettle(); // theme animation material = tester.widget<Material>(buttonMaterialFinder); expect(material.shadowColor, shadowColor); }); }
flutter/packages/flutter/test/material/outlined_button_theme_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/outlined_button_theme_test.dart", "repo_id": "flutter", "token_count": 5750 }
672
// 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. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('$ReorderableListView', () { const double itemHeight = 48.0; const List<String> originalListItems = <String>['Item 1', 'Item 2', 'Item 3', 'Item 4']; late List<String> listItems; void onReorder(int oldIndex, int newIndex) { if (oldIndex < newIndex) { newIndex -= 1; } final String element = listItems.removeAt(oldIndex); listItems.insert(newIndex, element); } Widget listItemToWidget(String listItem) { return SizedBox( key: Key(listItem), height: itemHeight, width: itemHeight, child: Text(listItem), ); } Widget build({ Widget? header, Widget? footer, Axis scrollDirection = Axis.vertical, bool reverse = false, EdgeInsets padding = EdgeInsets.zero, TextDirection textDirection = TextDirection.ltr, TargetPlatform? platform, }) { return MaterialApp( theme: ThemeData(platform: platform), home: Directionality( textDirection: textDirection, child: SizedBox( height: itemHeight * 10, width: itemHeight * 10, child: ReorderableListView( header: header, footer: footer, scrollDirection: scrollDirection, onReorder: onReorder, reverse: reverse, padding: padding, children: listItems.map<Widget>(listItemToWidget).toList(), ), ), ), ); } setUp(() { // Copy the original list into listItems. listItems = originalListItems.toList(); }); group('in vertical mode', () { testWidgets('reorder is not triggered when children length is less or equals to 1', (WidgetTester tester) async { bool onReorderWasCalled = false; final List<String> currentListItems = listItems.take(1).toList(); final ReorderableListView reorderableListView = ReorderableListView( header: const Text('Header'), onReorder: (_, __) => onReorderWasCalled = true, children: currentListItems.map<Widget>(listItemToWidget).toList(), ); final List<String> currentOriginalListItems = originalListItems.take(1).toList(); await tester.pumpWidget(MaterialApp( home: SizedBox( height: itemHeight * 10, child: reorderableListView, ), )); expect(currentListItems, orderedEquals(currentOriginalListItems)); final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('Item 1'))); await tester.pump(kLongPressTimeout + kPressTimeout); expect(currentListItems, orderedEquals(currentOriginalListItems)); await drag.moveTo(tester.getBottomLeft(find.text('Item 1')) * 2); expect(currentListItems, orderedEquals(currentOriginalListItems)); await drag.up(); expect(onReorderWasCalled, false); expect(currentListItems, orderedEquals(<String>['Item 1'])); }); testWidgets('reorders its contents only when a drag finishes', (WidgetTester tester) async { await tester.pumpWidget(build()); expect(listItems, orderedEquals(originalListItems)); final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('Item 1'))); await tester.pump(kLongPressTimeout + kPressTimeout); expect(listItems, orderedEquals(originalListItems)); await drag.moveTo(tester.getCenter(find.text('Item 4'))); expect(listItems, orderedEquals(originalListItems)); await drag.up(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 2', 'Item 3', 'Item 1', 'Item 4'])); }); testWidgets('allows reordering from the very top to the very bottom', (WidgetTester tester) async { await tester.pumpWidget(build()); expect(listItems, orderedEquals(originalListItems)); await longPressDrag( tester, tester.getCenter(find.text('Item 1')), tester.getCenter(find.text('Item 4')) + const Offset(0.0, itemHeight * 2), ); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 2', 'Item 3', 'Item 4', 'Item 1'])); }); testWidgets('allows reordering from the very bottom to the very top', (WidgetTester tester) async { await tester.pumpWidget(build()); expect(listItems, orderedEquals(originalListItems)); await longPressDrag( tester, tester.getCenter(find.text('Item 4')), tester.getCenter(find.text('Item 1')), ); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 4', 'Item 1', 'Item 2', 'Item 3'])); }); testWidgets('allows reordering inside the middle of the widget', (WidgetTester tester) async { await tester.pumpWidget(build()); expect(listItems, orderedEquals(originalListItems)); await longPressDrag( tester, tester.getCenter(find.text('Item 3')), tester.getCenter(find.text('Item 2')), ); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 1', 'Item 3', 'Item 2', 'Item 4'])); }); testWidgets('properly reorders with a header', (WidgetTester tester) async { await tester.pumpWidget(build(header: const Text('Header Text'))); expect(find.text('Header Text'), findsOneWidget); expect(listItems, orderedEquals(originalListItems)); await longPressDrag( tester, tester.getCenter(find.text('Item 1')), tester.getCenter(find.text('Item 4')) + const Offset(0.0, itemHeight * 2), ); await tester.pumpAndSettle(); expect(find.text('Header Text'), findsOneWidget); expect(listItems, orderedEquals(<String>['Item 2', 'Item 3', 'Item 4', 'Item 1'])); }); testWidgets('properly reorders with a footer', (WidgetTester tester) async { await tester.pumpWidget(build(footer: const Text('Footer Text'))); expect(find.text('Footer Text'), findsOneWidget); expect(listItems, orderedEquals(originalListItems)); await longPressDrag( tester, tester.getCenter(find.text('Item 1')), tester.getCenter(find.text('Item 4')) + const Offset(0.0, itemHeight * 2), ); await tester.pumpAndSettle(); expect(find.text('Footer Text'), findsOneWidget); expect(listItems, orderedEquals(<String>['Item 2', 'Item 3', 'Item 4', 'Item 1'])); }); testWidgets('properly determines the vertical drop area extents', (WidgetTester tester) async { final Widget reorderableListView = ReorderableListView( onReorder: (int oldIndex, int newIndex) { }, children: const <Widget>[ SizedBox( key: Key('Normal item'), height: itemHeight, child: Text('Normal item'), ), SizedBox( key: Key('Tall item'), height: itemHeight * 2, child: Text('Tall item'), ), SizedBox( key: Key('Last item'), height: itemHeight, child: Text('Last item'), ), ], ); await tester.pumpWidget(MaterialApp( home: SizedBox( height: itemHeight * 10, child: reorderableListView, ), )); double getListHeight() { final RenderSliverList listScrollView = tester.renderObject(find.byType(SliverList)); return listScrollView.geometry!.maxPaintExtent; } const double kDraggingListHeight = 4 * itemHeight; // Drag a normal text item expect(getListHeight(), kDraggingListHeight); TestGesture drag = await tester.startGesture(tester.getCenter(find.text('Normal item'))); await tester.pump(kLongPressTimeout + kPressTimeout); await tester.pumpAndSettle(); expect(getListHeight(), kDraggingListHeight); // Move it await drag.moveTo(tester.getCenter(find.text('Last item'))); await tester.pumpAndSettle(); expect(getListHeight(), kDraggingListHeight); // Drop it await drag.up(); await tester.pumpAndSettle(); expect(getListHeight(), kDraggingListHeight); // Drag a tall item drag = await tester.startGesture(tester.getCenter(find.text('Tall item'))); await tester.pump(kLongPressTimeout + kPressTimeout); await tester.pumpAndSettle(); expect(getListHeight(), kDraggingListHeight); // Move it await drag.moveTo(tester.getCenter(find.text('Last item'))); await tester.pumpAndSettle(); expect(getListHeight(), kDraggingListHeight); // Drop it await drag.up(); await tester.pumpAndSettle(); expect(getListHeight(), kDraggingListHeight); }); testWidgets('Vertical drag in progress golden image', (WidgetTester tester) async { debugDisableShadows = false; final Widget reorderableListView = ReorderableListView( children: <Widget>[ Container( key: const Key('pink'), width: double.infinity, height: itemHeight, color: Colors.pink, ), Container( key: const Key('blue'), width: double.infinity, height: itemHeight, color: Colors.blue, ), Container( key: const Key('green'), width: double.infinity, height: itemHeight, color: Colors.green, ), ], onReorder: (int oldIndex, int newIndex) { }, ); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget(MaterialApp( home: Container( color: Colors.white, height: itemHeight * 3, // Wrap in an overlay so that the golden image includes the dragged item. child: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry(builder: (BuildContext context) { // Wrap the list in padding to test that the positioning // is correct when the origin of the overlay is different // from the list. return Padding( padding: const EdgeInsets.all(24), child: reorderableListView, ); }), ], ), ), )); // Start dragging the second item. final TestGesture drag = await tester.startGesture(tester.getCenter(find.byKey(const Key('blue')))); await tester.pump(kLongPressTimeout + kPressTimeout); // Drag it up to be partially over the top item. await drag.moveBy(const Offset(0, -itemHeight / 3)); await tester.pumpAndSettle(); // Should be an image of the second item overlapping the bottom of the // first with a gap between the first and third and a drop shadow on // the dragged item. await expectLater( find.byType(Overlay).last, matchesGoldenFile('reorderable_list_test.vertical.drop_area.png'), ); debugDisableShadows = true; }); testWidgets('Preserves children states when the list parent changes the order', (WidgetTester tester) async { _StatefulState findState(Key key) { return find.byElementPredicate((Element element) => element.findAncestorWidgetOfExactType<_Stateful>()?.key == key) .evaluate() .first .findAncestorStateOfType<_StatefulState>()!; } await tester.pumpWidget(MaterialApp( home: ReorderableListView( children: <Widget>[ _Stateful(key: const Key('A')), _Stateful(key: const Key('B')), _Stateful(key: const Key('C')), ], onReorder: (int oldIndex, int newIndex) { }, ), )); await tester.tap(find.byKey(const Key('A'))); await tester.pumpAndSettle(); // Only the 'A' widget should be checked. expect(findState(const Key('A')).checked, true); expect(findState(const Key('B')).checked, false); expect(findState(const Key('C')).checked, false); await tester.pumpWidget(MaterialApp( home: ReorderableListView( children: <Widget>[ _Stateful(key: const Key('B')), _Stateful(key: const Key('C')), _Stateful(key: const Key('A')), ], onReorder: (int oldIndex, int newIndex) { }, ), )); // Only the 'A' widget should be checked. expect(findState(const Key('B')).checked, false); expect(findState(const Key('C')).checked, false); expect(findState(const Key('A')).checked, true); }); testWidgets('Preserves children states when rebuilt', (WidgetTester tester) async { const Key firstBox = Key('key'); Widget build() { return MaterialApp( home: Directionality( textDirection: TextDirection.ltr, child: SizedBox( width: 100, height: 100, child: ReorderableListView( children: const <Widget>[ SizedBox(key: firstBox, width: 10, height: 10), ], onReorder: (_, __) {}, ), ), ), ); } // When the widget is rebuilt, the state of child should be consistent. await tester.pumpWidget(build()); final Element e0 = tester.element(find.byKey(firstBox)); await tester.pumpWidget(build()); final Element e1 = tester.element(find.byKey(firstBox)); expect(e0, equals(e1)); }); testWidgets('Uses the PrimaryScrollController when available', (WidgetTester tester) async { final ScrollController primary = ScrollController(); addTearDown(primary.dispose); final Widget reorderableList = ReorderableListView( children: const <Widget>[ SizedBox(width: 100.0, height: 100.0, key: Key('C'), child: Text('C')), SizedBox(width: 100.0, height: 100.0, key: Key('B'), child: Text('B')), SizedBox(width: 100.0, height: 100.0, key: Key('A'), child: Text('A')), ], onReorder: (int oldIndex, int newIndex) { }, ); Widget buildWithScrollController(ScrollController controller) { return MaterialApp( home: PrimaryScrollController( controller: controller, child: SizedBox( height: 100.0, width: 100.0, child: reorderableList, ), ), ); } await tester.pumpWidget(buildWithScrollController(primary)); Scrollable scrollView = tester.widget( find.byType(Scrollable), ); expect(scrollView.controller, primary); // Now try changing the primary scroll controller and checking that the scroll view gets updated. final ScrollController primary2 = ScrollController(); addTearDown(primary2.dispose); await tester.pumpWidget(buildWithScrollController(primary2)); scrollView = tester.widget( find.byType(Scrollable), ); expect(scrollView.controller, primary2); }); testWidgets('Test custom ScrollController behavior when set', (WidgetTester tester) async { const Key firstBox = Key('C'); const Key secondBox = Key('B'); const Key thirdBox = Key('A'); final ScrollController customController = ScrollController(); addTearDown(customController.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( body: SizedBox( height: 150, child: ReorderableListView( scrollController: customController, onReorder: (int oldIndex, int newIndex) { }, children: const <Widget>[ SizedBox(width: 100.0, height: 100.0, key: firstBox, child: Text('C')), SizedBox(width: 100.0, height: 100.0, key: secondBox, child: Text('B')), SizedBox(width: 100.0, height: 100.0, key: thirdBox, child: Text('A')), ], ), ), ), ), ); // Check initial scroll offset of first list item relative to // the offset of the list view. customController.animateTo( 40.0, duration: const Duration(milliseconds: 200), curve: Curves.linear, ); await tester.pumpAndSettle(); Offset listViewTopLeft = tester.getTopLeft( find.byType(ReorderableListView), ); Offset firstBoxTopLeft = tester.getTopLeft( find.byKey(firstBox), ); expect(firstBoxTopLeft.dy, listViewTopLeft.dy - 40.0); // Drag the UI to see if the scroll controller updates accordingly await tester.drag( find.text('B'), const Offset(0.0, -100.0), ); listViewTopLeft = tester.getTopLeft( find.byType(ReorderableListView), ); firstBoxTopLeft = tester.getTopLeft( find.byKey(firstBox), ); // Initial scroll controller offset: 40.0 // Drag UI by 100.0 upwards vertically // First 20.0 px always ignored, so scroll offset is only // shifted by 80.0. // Final offset: 40.0 + 80.0 = 120.0 // The total distance available to scroll is 300.0 - 150.0 = 150.0, or // height of the ReorderableListView minus height of the SizedBox. Since // The final offset is less than this, it's not limited. expect(customController.offset, 120.0); }); testWidgets('ReorderableList auto scrolling is fast enough', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/121603. final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( body: ReorderableListView.builder( scrollController: controller, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('data', key: ValueKey<int>(index)); }, onReorder: (int oldIndex, int newIndex) {}, ), ), ), ); // Start gesture on first item. final TestGesture drag = await tester.startGesture(tester.getCenter(find.byKey(const ValueKey<int>(0)))); await tester.pump(kLongPressTimeout + kPressTimeout); final Offset bottomRight = tester.getBottomRight(find.byType(ReorderableListView)); // Drag enough for move to start. await drag.moveTo(Offset(bottomRight.dx / 2, bottomRight.dy)); await tester.pump(); // Use a fixed value to make sure the default velocity scalar is bigger // than a certain amount. const double kMinimumAllowedAutoScrollDistancePer5ms = 1.7; await tester.pump(const Duration(milliseconds: 5)); expect(controller.offset, greaterThan(kMinimumAllowedAutoScrollDistancePer5ms)); await tester.pump(const Duration(milliseconds: 5)); expect(controller.offset, greaterThan(kMinimumAllowedAutoScrollDistancePer5ms * 2)); await tester.pump(const Duration(milliseconds: 5)); expect(controller.offset, greaterThan(kMinimumAllowedAutoScrollDistancePer5ms * 3)); await tester.pump(const Duration(milliseconds: 5)); expect(controller.offset, greaterThan(kMinimumAllowedAutoScrollDistancePer5ms * 4)); }); testWidgets('Still builds when no PrimaryScrollController is available', (WidgetTester tester) async { final Widget reorderableList = ReorderableListView( children: const <Widget>[ SizedBox(width: 100.0, height: 100.0, key: Key('C'), child: Text('C')), SizedBox(width: 100.0, height: 100.0, key: Key('B'), child: Text('B')), SizedBox(width: 100.0, height: 100.0, key: Key('A'), child: Text('A')), ], onReorder: (int oldIndex, int newIndex) { }, ); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); final Widget overlay = Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry(builder: (BuildContext context) => reorderableList), ], ); final Widget boilerplate = Localizations( locale: const Locale('en'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultMaterialLocalizations.delegate, DefaultWidgetsLocalizations.delegate, ], child:SizedBox( width: 100.0, height: 100.0, child: Directionality( textDirection: TextDirection.ltr, child: overlay, ), ), ); await expectLater( () => tester.pumpWidget(boilerplate), returnsNormally, ); }); group('Accessibility (a11y/Semantics)', () { Map<CustomSemanticsAction, VoidCallback> getSemanticsActions(int index) { final Semantics semantics = find.ancestor( of: find.byKey(Key(listItems[index])), matching: find.byType(Semantics), ).evaluate().first.widget as Semantics; return semantics.properties.customSemanticsActions!; } const CustomSemanticsAction moveToStart = CustomSemanticsAction(label: 'Move to the start'); const CustomSemanticsAction moveToEnd = CustomSemanticsAction(label: 'Move to the end'); const CustomSemanticsAction moveUp = CustomSemanticsAction(label: 'Move up'); const CustomSemanticsAction moveDown = CustomSemanticsAction(label: 'Move down'); testWidgets('Provides the correct accessibility actions in LTR and RTL modes', (WidgetTester tester) async { // The a11y actions for a vertical list are the same in LTR and RTL modes. final SemanticsHandle handle = tester.ensureSemantics(); for (final TextDirection direction in TextDirection.values) { await tester.pumpWidget(build()); // The first item can be moved down or to the end. final Map<CustomSemanticsAction, VoidCallback> firstSemanticsActions = getSemanticsActions(0); expect(firstSemanticsActions.length, 2, reason: 'The first list item should have 2 custom actions with $direction.'); expect(firstSemanticsActions.containsKey(moveToStart), false, reason: 'The first item cannot `Move to the start` with $direction.'); expect(firstSemanticsActions.containsKey(moveUp), false, reason: 'The first item cannot `Move up` with $direction.'); expect(firstSemanticsActions.containsKey(moveDown), true, reason: 'The first item should be able to `Move down` with $direction.'); expect(firstSemanticsActions.containsKey(moveToEnd), true, reason: 'The first item should be able to `Move to the end` with $direction.'); // Items in the middle can be moved to the start, end, up or down. for (int i = 1; i < listItems.length - 1; i += 1) { final Map<CustomSemanticsAction, VoidCallback> ithSemanticsActions = getSemanticsActions(i); expect(ithSemanticsActions.length, 4, reason: 'List item $i should have 4 custom actions with $direction.'); expect(ithSemanticsActions.containsKey(moveToStart), true, reason: 'List item $i should be able to `Move to the start` with $direction.'); expect(ithSemanticsActions.containsKey(moveUp), true, reason: 'List item $i should be able to `Move up` with $direction.'); expect(ithSemanticsActions.containsKey(moveDown), true, reason: 'List item $i should be able to `Move down` with $direction.'); expect(ithSemanticsActions.containsKey(moveToEnd), true, reason: 'List item $i should be able to `Move to the end` with $direction.'); } // The last item can be moved up or to the start. final Map<CustomSemanticsAction, VoidCallback> lastSemanticsActions = getSemanticsActions(listItems.length - 1); expect(lastSemanticsActions.length, 2, reason: 'The last list item should have 2 custom actions with $direction.'); expect(lastSemanticsActions.containsKey(moveToStart), true, reason: 'The last item should be able to `Move to the start` with $direction.'); expect(lastSemanticsActions.containsKey(moveUp), true, reason: 'The last item should be able to `Move up` with $direction.'); expect(lastSemanticsActions.containsKey(moveDown), false, reason: 'The last item cannot `Move down` with $direction.'); expect(lastSemanticsActions.containsKey(moveToEnd), false, reason: 'The last item cannot `Move to the end` with $direction.'); } handle.dispose(); }); testWidgets('First item accessibility (a11y) actions work', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); expect(listItems, orderedEquals(originalListItems)); // Test out move to end: move Item 1 to the end of the list. await tester.pumpWidget(build()); Map<CustomSemanticsAction, VoidCallback> firstSemanticsActions = getSemanticsActions(0); firstSemanticsActions[moveToEnd]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 2', 'Item 3', 'Item 4', 'Item 1'])); // Test out move after: move Item 2 (the current first item) one space down. await tester.pumpWidget(build()); firstSemanticsActions = getSemanticsActions(0); firstSemanticsActions[moveDown]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 3', 'Item 2', 'Item 4', 'Item 1'])); handle.dispose(); }); testWidgets('Middle item accessibility (a11y) actions work', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); expect(listItems, orderedEquals(originalListItems)); // Test out move to end: move Item 2 to the end of the list. await tester.pumpWidget(build()); Map<CustomSemanticsAction, VoidCallback> middleSemanticsActions = getSemanticsActions(1); middleSemanticsActions[moveToEnd]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 1', 'Item 3', 'Item 4', 'Item 2'])); // Test out move after: move Item 3 (the current second item) one space down. await tester.pumpWidget(build()); middleSemanticsActions = getSemanticsActions(1); middleSemanticsActions[moveDown]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 1', 'Item 4', 'Item 3', 'Item 2'])); // Test out move after: move Item 3 (the current third item) one space up. await tester.pumpWidget(build()); middleSemanticsActions = getSemanticsActions(2); middleSemanticsActions[moveUp]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 1', 'Item 3', 'Item 4', 'Item 2'])); // Test out move to start: move Item 4 (the current third item) to the start of the list. await tester.pumpWidget(build()); middleSemanticsActions = getSemanticsActions(2); middleSemanticsActions[moveToStart]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 4', 'Item 1', 'Item 3', 'Item 2'])); handle.dispose(); }); testWidgets('Last item accessibility (a11y) actions work', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); expect(listItems, orderedEquals(originalListItems)); // Test out move to start: move Item 4 to the start of the list. await tester.pumpWidget(build()); Map<CustomSemanticsAction, VoidCallback> lastSemanticsActions = getSemanticsActions(listItems.length - 1); lastSemanticsActions[moveToStart]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 4', 'Item 1', 'Item 2', 'Item 3'])); // Test out move up: move Item 3 (the current last item) one space up. await tester.pumpWidget(build()); lastSemanticsActions = getSemanticsActions(listItems.length - 1); lastSemanticsActions[moveUp]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 4', 'Item 1', 'Item 3', 'Item 2'])); handle.dispose(); }); testWidgets("Doesn't hide accessibility when a child declares its own semantics", (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); final Widget reorderableListView = ReorderableListView( onReorder: (int oldIndex, int newIndex) { }, children: <Widget>[ const SizedBox( key: Key('List tile 1'), height: itemHeight, child: Text('List tile 1'), ), SizedBox( key: const Key('Switch tile'), height: itemHeight, child: Material( child: SwitchListTile( title: const Text('Switch tile'), value: true, onChanged: (bool? newValue) { }, ), ), ), const SizedBox( key: Key('List tile 2'), height: itemHeight, child: Text('List tile 2'), ), ], ); await tester.pumpWidget(MaterialApp( home: SizedBox( height: itemHeight * 10, child: reorderableListView, ), )); // Get the switch tile's semantics: final SemanticsNode semanticsNode = tester.getSemantics(find.byKey(const Key('Switch tile'))); // Check for ReorderableListView custom semantics actions. expect(semanticsNode, matchesSemantics( customActions: const <CustomSemanticsAction>[ CustomSemanticsAction(label: 'Move up'), CustomSemanticsAction(label: 'Move down'), CustomSemanticsAction(label: 'Move to the end'), CustomSemanticsAction(label: 'Move to the start'), ], )); // Check for properties of SwitchTile semantics. late SemanticsNode child; semanticsNode.visitChildren((SemanticsNode node) { child = node; return false; }); expect(child, matchesSemantics( hasToggledState: true, isToggled: true, isEnabled: true, isFocusable: true, hasEnabledState: true, label: 'Switch tile', hasTapAction: true, )); handle.dispose(); }); }); }); group('in horizontal mode', () { testWidgets('reorder is not triggered when children length is less or equals to 1', (WidgetTester tester) async { bool onReorderWasCalled = false; final List<String> currentListItems = listItems.take(1).toList(); final ReorderableListView reorderableListView = ReorderableListView( header: const Text('Header'), scrollDirection: Axis.horizontal, onReorder: (_, __) => onReorderWasCalled = true, children: currentListItems.map<Widget>(listItemToWidget).toList(), ); final List<String> currentOriginalListItems = originalListItems.take(1).toList(); await tester.pumpWidget(MaterialApp( home: SizedBox( height: itemHeight * 10, child: reorderableListView, ), )); expect(currentListItems, orderedEquals(currentOriginalListItems)); final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('Item 1'))); await tester.pump(kLongPressTimeout + kPressTimeout); expect(currentListItems, orderedEquals(currentOriginalListItems)); await drag.moveTo(tester.getBottomLeft(find.text('Item 1')) * 2); expect(currentListItems, orderedEquals(currentOriginalListItems)); await drag.up(); expect(onReorderWasCalled, false); expect(currentListItems, orderedEquals(<String>['Item 1'])); }); testWidgets('allows reordering from the very top to the very bottom', (WidgetTester tester) async { await tester.pumpWidget(build(scrollDirection: Axis.horizontal)); expect(listItems, orderedEquals(originalListItems)); await longPressDrag( tester, tester.getCenter(find.text('Item 1')), tester.getCenter(find.text('Item 4')) + const Offset(itemHeight * 2, 0.0), ); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 2', 'Item 3', 'Item 4', 'Item 1'])); }); testWidgets('allows reordering from the very bottom to the very top', (WidgetTester tester) async { await tester.pumpWidget(build(scrollDirection: Axis.horizontal)); expect(listItems, orderedEquals(originalListItems)); await longPressDrag( tester, tester.getCenter(find.text('Item 4')), tester.getCenter(find.text('Item 1')), ); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 4', 'Item 1', 'Item 2', 'Item 3'])); }); testWidgets('allows reordering inside the middle of the widget', (WidgetTester tester) async { await tester.pumpWidget(build(scrollDirection: Axis.horizontal)); expect(listItems, orderedEquals(originalListItems)); await longPressDrag( tester, tester.getCenter(find.text('Item 3')), tester.getCenter(find.text('Item 2')), ); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 1', 'Item 3', 'Item 2', 'Item 4'])); }); testWidgets('properly reorders with a header', (WidgetTester tester) async { await tester.pumpWidget(build(header: const Text('Header Text'), scrollDirection: Axis.horizontal)); expect(find.text('Header Text'), findsOneWidget); expect(listItems, orderedEquals(originalListItems)); await longPressDrag( tester, tester.getCenter(find.text('Item 1')), tester.getCenter(find.text('Item 4')) + const Offset(itemHeight * 2, 0.0), ); await tester.pumpAndSettle(); expect(find.text('Header Text'), findsOneWidget); expect(listItems, orderedEquals(<String>['Item 2', 'Item 3', 'Item 4', 'Item 1'])); await tester.pumpWidget(build(header: const Text('Header Text'), scrollDirection: Axis.horizontal)); await longPressDrag( tester, tester.getCenter(find.text('Item 4')), tester.getCenter(find.text('Item 3')), ); await tester.pumpAndSettle(); expect(find.text('Header Text'), findsOneWidget); expect(listItems, orderedEquals(<String>['Item 2', 'Item 4', 'Item 3', 'Item 1'])); }); testWidgets('properly reorders with a footer', (WidgetTester tester) async { await tester.pumpWidget(build(footer: const Text('Footer Text'), scrollDirection: Axis.horizontal)); expect(find.text('Footer Text'), findsOneWidget); expect(listItems, orderedEquals(originalListItems)); await longPressDrag( tester, tester.getCenter(find.text('Item 1')), tester.getCenter(find.text('Item 4')) + const Offset(itemHeight * 2, 0.0), ); await tester.pumpAndSettle(); expect(find.text('Footer Text'), findsOneWidget); expect(listItems, orderedEquals(<String>['Item 2', 'Item 3', 'Item 4', 'Item 1'])); await tester.pumpWidget(build(footer: const Text('Footer Text'), scrollDirection: Axis.horizontal)); await longPressDrag( tester, tester.getCenter(find.text('Item 4')), tester.getCenter(find.text('Item 3')), ); await tester.pumpAndSettle(); expect(find.text('Footer Text'), findsOneWidget); expect(listItems, orderedEquals(<String>['Item 2', 'Item 4', 'Item 3', 'Item 1'])); }); testWidgets('properly determines the horizontal drop area extents', (WidgetTester tester) async { final Widget reorderableListView = ReorderableListView( scrollDirection: Axis.horizontal, onReorder: (int oldIndex, int newIndex) { }, children: const <Widget>[ SizedBox( key: Key('Normal item'), width: itemHeight, child: Text('Normal item'), ), SizedBox( key: Key('Tall item'), width: itemHeight * 2, child: Text('Tall item'), ), SizedBox( key: Key('Last item'), width: itemHeight, child: Text('Last item'), ), ], ); await tester.pumpWidget(MaterialApp( home: SizedBox( width: itemHeight * 10, child: reorderableListView, ), )); double getListWidth() { final RenderSliverList listScrollView = tester.renderObject(find.byType(SliverList)); return listScrollView.geometry!.maxPaintExtent; } const double kDraggingListWidth = 4 * itemHeight; // Drag a normal text item expect(getListWidth(), kDraggingListWidth); TestGesture drag = await tester.startGesture(tester.getCenter(find.text('Normal item'))); await tester.pump(kLongPressTimeout + kPressTimeout); await tester.pumpAndSettle(); expect(getListWidth(), kDraggingListWidth); // Move it await drag.moveTo(tester.getCenter(find.text('Last item'))); await tester.pumpAndSettle(); expect(getListWidth(), kDraggingListWidth); // Drop it await drag.up(); await tester.pumpAndSettle(); expect(getListWidth(), kDraggingListWidth); // Drag a tall item drag = await tester.startGesture(tester.getCenter(find.text('Tall item'))); await tester.pump(kLongPressTimeout + kPressTimeout); await tester.pumpAndSettle(); expect(getListWidth(), kDraggingListWidth); // Move it await drag.moveTo(tester.getCenter(find.text('Last item'))); await tester.pumpAndSettle(); expect(getListWidth(), kDraggingListWidth); // Drop it await drag.up(); await tester.pumpAndSettle(); expect(getListWidth(), kDraggingListWidth); }); testWidgets('Horizontal drag in progress golden image', (WidgetTester tester) async { debugDisableShadows = false; final Widget reorderableListView = ReorderableListView( scrollDirection: Axis.horizontal, onReorder: (int oldIndex, int newIndex) { }, children: <Widget>[ Container( key: const Key('pink'), height: double.infinity, width: itemHeight, color: Colors.pink, ), Container( key: const Key('blue'), height: double.infinity, width: itemHeight, color: Colors.blue, ), Container( key: const Key('green'), height: double.infinity, width: itemHeight, color: Colors.green, ), ], ); late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget(MaterialApp( home: Container( color: Colors.white, width: itemHeight * 3, // Wrap in an overlay so that the golden image includes the dragged item. child: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry(builder: (BuildContext context) { // Wrap the list in padding to test that the positioning // is correct when the origin of the overlay is different // from the list. return Padding( padding: const EdgeInsets.all(24), child: reorderableListView, ); }), ], ), ), )); // Start dragging the second item. final TestGesture drag = await tester.startGesture(tester.getCenter(find.byKey(const Key('blue')))); await tester.pump(kLongPressTimeout + kPressTimeout); // Drag it left to be partially over the first item. await drag.moveBy(const Offset(-itemHeight / 3, 0)); await tester.pumpAndSettle(); // Should be an image of the second item overlapping the right of the // first with a gap between the first and third and a drop shadow on // the dragged item. await expectLater( find.byType(Overlay).last, matchesGoldenFile('reorderable_list_test.horizontal.drop_area.png'), ); debugDisableShadows = true; }); testWidgets('Preserves children states when the list parent changes the order', (WidgetTester tester) async { _StatefulState findState(Key key) { return find.byElementPredicate((Element element) => element.findAncestorWidgetOfExactType<_Stateful>()?.key == key) .evaluate() .first .findAncestorStateOfType<_StatefulState>()!; } await tester.pumpWidget(MaterialApp( home: ReorderableListView( onReorder: (int oldIndex, int newIndex) { }, scrollDirection: Axis.horizontal, children: <Widget>[ _Stateful(key: const Key('A')), _Stateful(key: const Key('B')), _Stateful(key: const Key('C')), ], ), )); await tester.tap(find.byKey(const Key('A'))); await tester.pumpAndSettle(); // Only the 'A' widget should be checked. expect(findState(const Key('A')).checked, true); expect(findState(const Key('B')).checked, false); expect(findState(const Key('C')).checked, false); await tester.pumpWidget(MaterialApp( home: ReorderableListView( onReorder: (int oldIndex, int newIndex) { }, scrollDirection: Axis.horizontal, children: <Widget>[ _Stateful(key: const Key('B')), _Stateful(key: const Key('C')), _Stateful(key: const Key('A')), ], ), )); // Only the 'A' widget should be checked. expect(findState(const Key('B')).checked, false); expect(findState(const Key('C')).checked, false); expect(findState(const Key('A')).checked, true); }); testWidgets('Preserves children states when rebuilt', (WidgetTester tester) async { const Key firstBox = Key('key'); Widget build() { return MaterialApp( home: Directionality( textDirection: TextDirection.ltr, child: SizedBox( width: 100, height: 100, child: ReorderableListView( scrollDirection: Axis.horizontal, children: const <Widget>[ SizedBox(key: firstBox, width: 10, height: 10), ], onReorder: (_, __) {}, ), ), ), ); } // When the widget is rebuilt, the state of child should be consistent. await tester.pumpWidget(build()); final Element e0 = tester.element(find.byKey(firstBox)); await tester.pumpWidget(build()); final Element e1 = tester.element(find.byKey(firstBox)); expect(e0, equals(e1)); }); group('Accessibility (a11y/Semantics)', () { Map<CustomSemanticsAction, VoidCallback> getSemanticsActions(int index) { final Semantics semantics = find.ancestor( of: find.byKey(Key(listItems[index])), matching: find.byType(Semantics), ).evaluate().first.widget as Semantics; return semantics.properties.customSemanticsActions!; } const CustomSemanticsAction moveToStart = CustomSemanticsAction(label: 'Move to the start'); const CustomSemanticsAction moveToEnd = CustomSemanticsAction(label: 'Move to the end'); const CustomSemanticsAction moveLeft = CustomSemanticsAction(label: 'Move left'); const CustomSemanticsAction moveRight = CustomSemanticsAction(label: 'Move right'); testWidgets('Provides the correct accessibility actions in LTR mode', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(build(scrollDirection: Axis.horizontal)); // The first item can be moved right or to the end. final Map<CustomSemanticsAction, VoidCallback> firstSemanticsActions = getSemanticsActions(0); expect(firstSemanticsActions.length, 2, reason: 'The first list item should have 2 custom actions.'); expect(firstSemanticsActions.containsKey(moveToStart), false, reason: 'The first item cannot `Move to the start`.'); expect(firstSemanticsActions.containsKey(moveLeft), false, reason: 'The first item cannot `Move left`.'); expect(firstSemanticsActions.containsKey(moveRight), true, reason: 'The first item should be able to `Move right`.'); expect(firstSemanticsActions.containsKey(moveToEnd), true, reason: 'The first item should be able to `Move to the end`.'); // Items in the middle can be moved to the start, end, left or right. for (int i = 1; i < listItems.length - 1; i += 1) { final Map<CustomSemanticsAction, VoidCallback> ithSemanticsActions = getSemanticsActions(i); expect(ithSemanticsActions.length, 4, reason: 'List item $i should have 4 custom actions.'); expect(ithSemanticsActions.containsKey(moveToStart), true, reason: 'List item $i should be able to `Move to the start`.'); expect(ithSemanticsActions.containsKey(moveLeft), true, reason: 'List item $i should be able to `Move left`.'); expect(ithSemanticsActions.containsKey(moveRight), true, reason: 'List item $i should be able to `Move right`.'); expect(ithSemanticsActions.containsKey(moveToEnd), true, reason: 'List item $i should be able to `Move to the end`.'); } // The last item can be moved left or to the start. final Map<CustomSemanticsAction, VoidCallback> lastSemanticsActions = getSemanticsActions(listItems.length - 1); expect(lastSemanticsActions.length, 2, reason: 'The last list item should have 2 custom actions.'); expect(lastSemanticsActions.containsKey(moveToStart), true, reason: 'The last item should be able to `Move to the start`.'); expect(lastSemanticsActions.containsKey(moveLeft), true, reason: 'The last item should be able to `Move left`.'); expect(lastSemanticsActions.containsKey(moveRight), false, reason: 'The last item cannot `Move right`.'); expect(lastSemanticsActions.containsKey(moveToEnd), false, reason: 'The last item cannot `Move to the end`.'); handle.dispose(); }); testWidgets('Provides the correct accessibility actions in Right-To-Left directionality', (WidgetTester tester) async { // In RTL mode, the right is the start and the left is the end. // The array representation is unchanged (LTR), but the direction of the motion actions is reversed. final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget(build(scrollDirection: Axis.horizontal, textDirection: TextDirection.rtl)); // The first item can be moved right or to the end. final Map<CustomSemanticsAction, VoidCallback> firstSemanticsActions = getSemanticsActions(0); expect(firstSemanticsActions.length, 2, reason: 'The first list item should have 2 custom actions.'); expect(firstSemanticsActions.containsKey(moveToStart), false, reason: 'The first item cannot `Move to the start`.'); expect(firstSemanticsActions.containsKey(moveRight), false, reason: 'The first item cannot `Move right`.'); expect(firstSemanticsActions.containsKey(moveLeft), true, reason: 'The first item should be able to `Move left`.'); expect(firstSemanticsActions.containsKey(moveToEnd), true, reason: 'The first item should be able to `Move to the end`.'); // Items in the middle can be moved to the start, end, left or right. for (int i = 1; i < listItems.length - 1; i += 1) { final Map<CustomSemanticsAction, VoidCallback> ithSemanticsActions = getSemanticsActions(i); expect(ithSemanticsActions.length, 4, reason: 'List item $i should have 4 custom actions.'); expect(ithSemanticsActions.containsKey(moveToStart), true, reason: 'List item $i should be able to `Move to the start`.'); expect(ithSemanticsActions.containsKey(moveRight), true, reason: 'List item $i should be able to `Move right`.'); expect(ithSemanticsActions.containsKey(moveLeft), true, reason: 'List item $i should be able to `Move left`.'); expect(ithSemanticsActions.containsKey(moveToEnd), true, reason: 'List item $i should be able to `Move to the end`.'); } // The last item can be moved left or to the start. final Map<CustomSemanticsAction, VoidCallback> lastSemanticsActions = getSemanticsActions(listItems.length - 1); expect(lastSemanticsActions.length, 2, reason: 'The last list item should have 2 custom actions.'); expect(lastSemanticsActions.containsKey(moveToStart), true, reason: 'The last item should be able to `Move to the start`.'); expect(lastSemanticsActions.containsKey(moveRight), true, reason: 'The last item should be able to `Move right`.'); expect(lastSemanticsActions.containsKey(moveLeft), false, reason: 'The last item cannot `Move left`.'); expect(lastSemanticsActions.containsKey(moveToEnd), false, reason: 'The last item cannot `Move to the end`.'); handle.dispose(); }); testWidgets('First item accessibility (a11y) actions work in LTR mode', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); expect(listItems, orderedEquals(originalListItems)); // Test out move to end: move Item 1 to the end of the list. await tester.pumpWidget(build(scrollDirection: Axis.horizontal)); Map<CustomSemanticsAction, VoidCallback> firstSemanticsActions = getSemanticsActions(0); firstSemanticsActions[moveToEnd]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 2', 'Item 3', 'Item 4', 'Item 1'])); // Test out move after: move Item 2 (the current first item) one space to the right. await tester.pumpWidget(build(scrollDirection: Axis.horizontal)); firstSemanticsActions = getSemanticsActions(0); firstSemanticsActions[moveRight]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 3', 'Item 2', 'Item 4', 'Item 1'])); handle.dispose(); }); testWidgets('First item accessibility (a11y) actions work in Right-To-Left directionality', (WidgetTester tester) async { // In RTL mode, the right is the start and the left is the end. // The array representation is unchanged (LTR), but the direction of the motion actions is reversed. final SemanticsHandle handle = tester.ensureSemantics(); expect(listItems, orderedEquals(originalListItems)); // Test out move to end: move Item 1 to the end of the list. await tester.pumpWidget(build(scrollDirection: Axis.horizontal, textDirection: TextDirection.rtl)); Map<CustomSemanticsAction, VoidCallback> firstSemanticsActions = getSemanticsActions(0); firstSemanticsActions[moveToEnd]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 2', 'Item 3', 'Item 4', 'Item 1'])); // Test out move after: move Item 2 (the current first item) one space to the left. await tester.pumpWidget(build(scrollDirection: Axis.horizontal, textDirection: TextDirection.rtl)); firstSemanticsActions = getSemanticsActions(0); firstSemanticsActions[moveLeft]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 3', 'Item 2', 'Item 4', 'Item 1'])); handle.dispose(); }); testWidgets('Middle item accessibility (a11y) actions work in LTR mode', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); expect(listItems, orderedEquals(originalListItems)); // Test out move to end: move Item 2 to the end of the list. await tester.pumpWidget(build(scrollDirection: Axis.horizontal)); Map<CustomSemanticsAction, VoidCallback> middleSemanticsActions = getSemanticsActions(1); middleSemanticsActions[moveToEnd]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 1', 'Item 3', 'Item 4', 'Item 2'])); // Test out move after: move Item 3 (the current second item) one space to the right. await tester.pumpWidget(build(scrollDirection: Axis.horizontal)); middleSemanticsActions = getSemanticsActions(1); middleSemanticsActions[moveRight]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 1', 'Item 4', 'Item 3', 'Item 2'])); // Test out move after: move Item 3 (the current third item) one space to the left. await tester.pumpWidget(build(scrollDirection: Axis.horizontal)); middleSemanticsActions = getSemanticsActions(2); middleSemanticsActions[moveLeft]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 1', 'Item 3', 'Item 4', 'Item 2'])); // Test out move to start: move Item 4 (the current third item) to the start of the list. await tester.pumpWidget(build(scrollDirection: Axis.horizontal)); middleSemanticsActions = getSemanticsActions(2); middleSemanticsActions[moveToStart]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 4', 'Item 1', 'Item 3', 'Item 2'])); handle.dispose(); }); testWidgets('Middle item accessibility (a11y) actions work in Right-To-Left directionality', (WidgetTester tester) async { // In RTL mode, the right is the start and the left is the end. // The array representation is unchanged (LTR), but the direction of the motion actions is reversed. final SemanticsHandle handle = tester.ensureSemantics(); expect(listItems, orderedEquals(originalListItems)); // Test out move to end: move Item 2 to the end of the list. await tester.pumpWidget(build(scrollDirection: Axis.horizontal, textDirection: TextDirection.rtl)); Map<CustomSemanticsAction, VoidCallback> middleSemanticsActions = getSemanticsActions(1); middleSemanticsActions[moveToEnd]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 1', 'Item 3', 'Item 4', 'Item 2'])); // Test out move after: move Item 3 (the current second item) one space to the left. await tester.pumpWidget(build(scrollDirection: Axis.horizontal, textDirection: TextDirection.rtl)); middleSemanticsActions = getSemanticsActions(1); middleSemanticsActions[moveLeft]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 1', 'Item 4', 'Item 3', 'Item 2'])); // Test out move after: move Item 3 (the current third item) one space to the right. await tester.pumpWidget(build(scrollDirection: Axis.horizontal, textDirection: TextDirection.rtl)); middleSemanticsActions = getSemanticsActions(2); middleSemanticsActions[moveRight]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 1', 'Item 3', 'Item 4', 'Item 2'])); // Test out move to start: move Item 4 (the current third item) to the start of the list. await tester.pumpWidget(build(scrollDirection: Axis.horizontal, textDirection: TextDirection.rtl)); middleSemanticsActions = getSemanticsActions(2); middleSemanticsActions[moveToStart]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 4', 'Item 1', 'Item 3', 'Item 2'])); handle.dispose(); }); testWidgets('Last item accessibility (a11y) actions work in LTR mode', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); expect(listItems, orderedEquals(originalListItems)); // Test out move to start: move Item 4 to the start of the list. await tester.pumpWidget(build(scrollDirection: Axis.horizontal)); Map<CustomSemanticsAction, VoidCallback> lastSemanticsActions = getSemanticsActions(listItems.length - 1); lastSemanticsActions[moveToStart]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 4', 'Item 1', 'Item 2', 'Item 3'])); // Test out move before: move Item 3 (the current last item) one space to the left. await tester.pumpWidget(build(scrollDirection: Axis.horizontal)); lastSemanticsActions = getSemanticsActions(listItems.length - 1); lastSemanticsActions[moveLeft]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 4', 'Item 1', 'Item 3', 'Item 2'])); handle.dispose(); }); testWidgets('Last item accessibility (a11y) actions work in Right-To-Left directionality', (WidgetTester tester) async { // In RTL mode, the right is the start and the left is the end. // The array representation is unchanged (LTR), but the direction of the motion actions is reversed. final SemanticsHandle handle = tester.ensureSemantics(); expect(listItems, orderedEquals(originalListItems)); // Test out move to start: move Item 4 to the start of the list. await tester.pumpWidget(build(scrollDirection: Axis.horizontal, textDirection: TextDirection.rtl)); Map<CustomSemanticsAction, VoidCallback> lastSemanticsActions = getSemanticsActions(listItems.length - 1); lastSemanticsActions[moveToStart]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 4', 'Item 1', 'Item 2', 'Item 3'])); // Test out move before: move Item 3 (the current last item) one space to the right. await tester.pumpWidget(build(scrollDirection: Axis.horizontal, textDirection: TextDirection.rtl)); lastSemanticsActions = getSemanticsActions(listItems.length - 1); lastSemanticsActions[moveRight]!(); await tester.pumpAndSettle(); expect(listItems, orderedEquals(<String>['Item 4', 'Item 1', 'Item 3', 'Item 2'])); handle.dispose(); }); }); }); testWidgets('ReorderableListView.builder asserts on negative childCount', (WidgetTester tester) async { expect(() => ReorderableListView.builder( itemBuilder: (BuildContext context, int index) { return const SizedBox(); }, itemCount: -1, onReorder: (int from, int to) {}, ), throwsAssertionError); }); testWidgets('ReorderableListView.builder only creates the children it needs', (WidgetTester tester) async { final Set<int> itemsCreated = <int>{}; await tester.pumpWidget(MaterialApp( home: ReorderableListView.builder( itemBuilder: (BuildContext context, int index) { itemsCreated.add(index); return Text(index.toString(), key: ValueKey<int>(index)); }, itemCount: 1000, onReorder: (int from, int to) {}, ), )); // Should have only created the first 18 items. expect(itemsCreated, <int>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}); }); group('Padding', () { testWidgets('Padding with no header & footer', (WidgetTester tester) async { const EdgeInsets padding = EdgeInsets.fromLTRB(10, 20, 30, 40); // Vertical await tester.pumpWidget(build(padding: padding)); expect(tester.getRect(find.byKey(const Key('Item 1'))), const Rect.fromLTRB(10, 20, 770, 68)); expect(tester.getRect(find.byKey(const Key('Item 4'))), const Rect.fromLTRB(10, 164, 770, 212)); // Horizontal await tester.pumpWidget(build(padding: padding, scrollDirection: Axis.horizontal)); expect(tester.getRect(find.byKey(const Key('Item 1'))), const Rect.fromLTRB(10, 20, 58, 560)); expect(tester.getRect(find.byKey(const Key('Item 4'))), const Rect.fromLTRB(154, 20, 202, 560)); }); testWidgets('Padding with header or footer', (WidgetTester tester) async { const EdgeInsets padding = EdgeInsets.fromLTRB(10, 20, 30, 40); const Key headerKey = Key('Header'); const Key footerKey = Key('Footer'); const Widget verticalHeader = SizedBox(key: headerKey, height: 10); const Widget horizontalHeader = SizedBox(key: headerKey, width: 10); const Widget verticalFooter = SizedBox(key: footerKey, height: 10); const Widget horizontalFooter = SizedBox(key: footerKey, width: 10); // Vertical Header await tester.pumpWidget(build(padding: padding, header: verticalHeader)); expect(tester.getRect(find.byKey(headerKey)), const Rect.fromLTRB(10, 20, 770, 30)); expect(tester.getRect(find.byKey(const Key('Item 1'))), const Rect.fromLTRB(10, 30, 770, 78)); expect(tester.getRect(find.byKey(const Key('Item 4'))), const Rect.fromLTRB(10, 174, 770, 222)); // Vertical Footer await tester.pumpWidget(build(padding: padding, footer: verticalFooter)); expect(tester.getRect(find.byKey(footerKey)), const Rect.fromLTRB(10, 212, 770, 222)); expect(tester.getRect(find.byKey(const Key('Item 1'))), const Rect.fromLTRB(10, 20, 770, 68)); expect(tester.getRect(find.byKey(const Key('Item 4'))), const Rect.fromLTRB(10, 164, 770, 212)); // Vertical Header, reversed await tester.pumpWidget(build(padding: padding, header: verticalHeader, reverse: true)); expect(tester.getRect(find.byKey(headerKey)), const Rect.fromLTRB(10, 550, 770, 560)); expect(tester.getRect(find.byKey(const Key('Item 1'))), const Rect.fromLTRB(10, 502, 770, 550)); expect(tester.getRect(find.byKey(const Key('Item 4'))), const Rect.fromLTRB(10, 358, 770, 406)); // Vertical Footer, reversed await tester.pumpWidget(build(padding: padding, footer: verticalFooter, reverse: true)); expect(tester.getRect(find.byKey(footerKey)), const Rect.fromLTRB(10, 358, 770, 368)); expect(tester.getRect(find.byKey(const Key('Item 1'))), const Rect.fromLTRB(10, 512, 770, 560)); expect(tester.getRect(find.byKey(const Key('Item 4'))), const Rect.fromLTRB(10, 368, 770, 416)); // Horizontal Header await tester.pumpWidget(build(padding: padding, header: horizontalHeader, scrollDirection: Axis.horizontal)); expect(tester.getRect(find.byKey(headerKey)), const Rect.fromLTRB(10, 20, 20, 560)); expect(tester.getRect(find.byKey(const Key('Item 1'))), const Rect.fromLTRB(20, 20, 68, 560)); expect(tester.getRect(find.byKey(const Key('Item 4'))), const Rect.fromLTRB(164, 20, 212, 560)); // // Horizontal Footer await tester.pumpWidget(build(padding: padding, footer: horizontalFooter, scrollDirection: Axis.horizontal)); expect(tester.getRect(find.byKey(footerKey)), const Rect.fromLTRB(202, 20, 212, 560)); expect(tester.getRect(find.byKey(const Key('Item 1'))), const Rect.fromLTRB(10, 20, 58, 560)); expect(tester.getRect(find.byKey(const Key('Item 4'))), const Rect.fromLTRB(154, 20, 202, 560)); // Horizontal Header, reversed await tester.pumpWidget(build(padding: padding, header: horizontalHeader, scrollDirection: Axis.horizontal, reverse: true)); expect(tester.getRect(find.byKey(headerKey)), const Rect.fromLTRB(760, 20, 770, 560)); expect(tester.getRect(find.byKey(const Key('Item 1'))), const Rect.fromLTRB(712, 20, 760, 560)); expect(tester.getRect(find.byKey(const Key('Item 4'))), const Rect.fromLTRB(568, 20, 616, 560)); // // Horizontal Footer, reversed await tester.pumpWidget(build(padding: padding, footer: horizontalFooter, scrollDirection: Axis.horizontal, reverse: true)); expect(tester.getRect(find.byKey(footerKey)), const Rect.fromLTRB(568, 20, 578, 560)); expect(tester.getRect(find.byKey(const Key('Item 1'))), const Rect.fromLTRB(722, 20, 770, 560)); expect(tester.getRect(find.byKey(const Key('Item 4'))), const Rect.fromLTRB(578, 20, 626, 560)); }); }); testWidgets('ReorderableListView can be reversed', (WidgetTester tester) async { final Widget reorderableListView = ReorderableListView( reverse: true, onReorder: (int oldIndex, int newIndex) { }, children: const <Widget>[ SizedBox( key: Key('A'), child: Text('A'), ), SizedBox( key: Key('B'), child: Text('B'), ), SizedBox( key: Key('C'), child: Text('C'), ), ], ); await tester.pumpWidget(MaterialApp( home: reorderableListView, )); expect(tester.getCenter(find.text('A')).dy, greaterThan(tester.getCenter(find.text('B')).dy)); }); testWidgets('Animation test when placing an item in place', (WidgetTester tester) async { const Key testItemKey = Key('Test item'); final Widget reorderableListView = ReorderableListView( onReorder: (int oldIndex, int newIndex) { }, children: const <Widget>[ SizedBox( key: Key('First item'), height: itemHeight, child: Text('First item'), ), SizedBox( key: testItemKey, height: itemHeight, child: Text('Test item'), ), SizedBox( key: Key('Last item'), height: itemHeight, child: Text('Last item'), ), ], ); await tester.pumpWidget(MaterialApp( home: SizedBox( height: itemHeight * 10, child: reorderableListView, ), )); Offset getTestItemPosition() { final RenderBox testItem = tester.renderObject<RenderBox>(find.byKey(testItemKey)); return testItem.localToGlobal(Offset.zero); } // Before pick it up. final Offset startPosition = getTestItemPosition(); // Pick it up. final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(testItemKey))); await tester.pump(kLongPressTimeout + kPressTimeout); expect(getTestItemPosition(), startPosition); // Put it down. await gesture.up(); await tester.pump(); expect(getTestItemPosition(), startPosition); // After put it down. await tester.pumpAndSettle(); expect(getTestItemPosition(), startPosition); }); // TODO(djshuckerow): figure out how to write a test for scrolling the list. testWidgets('ReorderableListView on desktop platforms should have drag handles', (WidgetTester tester) async { await tester.pumpWidget(build()); // All four items should have drag handles and not delayed listeners. expect(find.byIcon(Icons.drag_handle), findsNWidgets(4)); expect(find.byType(ReorderableDelayedDragStartListener), findsNothing); }, variant: TargetPlatformVariant.desktop()); testWidgets('ReorderableListView on mobile platforms should not have drag handles', (WidgetTester tester) async { await tester.pumpWidget(build()); // All four items should have delayed listeners and not drag handles. expect(find.byType(ReorderableDelayedDragStartListener), findsNWidgets(4)); expect(find.byIcon(Icons.drag_handle), findsNothing); }, variant: TargetPlatformVariant.mobile()); testWidgets('Vertical list renders drag handle in correct position', (WidgetTester tester) async { await tester.pumpWidget(build(platform: TargetPlatform.macOS)); final Finder listView = find.byType(ReorderableListView); final Finder item1 = find.byKey(const Key('Item 1')); final Finder dragHandle = find.byIcon(Icons.drag_handle).first; // Should be centered vertically within the item and 8 pixels from the right edge of the list. expect(tester.getCenter(dragHandle).dy, tester.getCenter(item1).dy); expect(tester.getTopRight(dragHandle).dx, tester.getSize(listView).width - 8); }); testWidgets('Horizontal list renders drag handle in correct position', (WidgetTester tester) async { await tester.pumpWidget(build(scrollDirection: Axis.horizontal, platform: TargetPlatform.macOS)); final Finder listView = find.byType(ReorderableListView); final Finder item1 = find.byKey(const Key('Item 1')); final Finder dragHandle = find.byIcon(Icons.drag_handle).first; // Should be centered horizontally within the item and 8 pixels from the bottom of the list. expect(tester.getCenter(dragHandle).dx, tester.getCenter(item1).dx); expect(tester.getBottomRight(dragHandle).dy, tester.getSize(listView).height - 8); }); }); testWidgets('ReorderableListView, can deal with the dragged item getting unmounted and rebuilt during drag', (WidgetTester tester) async { // See https://github.com/flutter/flutter/issues/74840 for more details. final List<int> items = List<int>.generate(100, (int index) => index); void handleReorder(int fromIndex, int toIndex) { if (toIndex > fromIndex) { toIndex -= 1; } items.insert(toIndex, items.removeAt(fromIndex)); } // The list is 800x600, 8 items, each item is 800x100 with // an "item $index" text widget at the item's origin. Drags are initiated by // a simple press on the text widget. await tester.pumpWidget(MaterialApp( home: ReorderableListView.builder( itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(items[index]), height: 100, child: ReorderableDragStartListener( index: index, child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text('item ${items[index]}'), ], ), ), ); }, buildDefaultDragHandles: false, itemCount: items.length, onReorder: handleReorder, ), )); // Drag item 0 downwards and force an auto scroll off the end of the list // far enough that item zeros original entry in the list is unmounted. final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('item 0'))); await tester.pump(kPressTimeout); // Off the bottom of the screen, which should autoscroll until we hit the // end of the list await drag.moveBy(const Offset(0, 700)); await tester.pump(const Duration(seconds: 30)); await tester.pumpAndSettle(); // Ensure we made it to the bottom (only 4 should be showing as there should // be a gap at the end for the drop area of the dragged item. for (final int i in <int>[95, 96, 97, 98, 99]) { expect(find.text('item $i'), findsOneWidget); } // Drag back to off the top of the list, which should autoscroll until // we hit the beginning of the list. This should cause the first item's // entry to be rebuilt. However, the contents should not be in both places. await drag.moveBy(const Offset(0, -1400)); await tester.pump(const Duration(seconds: 30)); await tester.pumpAndSettle(); // Release back at the top so item 0 should drop where it was await drag.up(); await tester.pumpAndSettle(); // Should not have changed anything for (final int i in <int>[0, 1, 2, 3, 4, 5]) { expect(find.text('item $i'), findsOneWidget); } expect(items.take(8), orderedEquals(<int>[0, 1, 2, 3, 4, 5, 6, 7])); }); testWidgets('ReorderableListView calls onReorderStart and onReorderEnd correctly', (WidgetTester tester) async { final List<int> items = List<int>.generate(8, (int index) => index); int? startIndex, endIndex; final Finder item0 = find.textContaining('item 0'); void handleReorder(int fromIndex, int toIndex) { if (toIndex > fromIndex) { toIndex -= 1; } items.insert(toIndex, items.removeAt(fromIndex)); } await tester.pumpWidget(MaterialApp( home: ReorderableListView.builder( itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(items[index]), height: 100, child: ReorderableDragStartListener( index: index, child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text('item ${items[index]}'), ], ), ), ); }, buildDefaultDragHandles: false, itemCount: items.length, onReorder: handleReorder, onReorderStart: (int index) { startIndex = index; }, onReorderEnd: (int index) { endIndex = index; }, ), )); TestGesture drag = await tester.startGesture(tester.getCenter(item0)); await tester.pump(kPressTimeout); // Drag enough for move to start. await drag.moveBy(const Offset(0, 20)); expect(startIndex, equals(0)); expect(endIndex, isNull); // Move item0 from index 0 to index 3 await drag.moveBy(const Offset(0, 300)); await tester.pumpAndSettle(); await drag.up(); await tester.pumpAndSettle(); expect(endIndex, equals(3)); startIndex = null; endIndex = null; drag = await tester.startGesture(tester.getCenter(item0)); await tester.pump(kPressTimeout); // Drag enough for move to start. await drag.moveBy(const Offset(0, 20)); expect(startIndex, equals(2)); expect(endIndex, isNull); // Move item0 from index 2 to index 0 await drag.moveBy(const Offset(0, -200)); await tester.pumpAndSettle(); await drag.up(); await tester.pumpAndSettle(); expect(endIndex, equals(0)); }); testWidgets('ReorderableListView throws an error when key is not passed to its children', (WidgetTester tester) async { final Widget reorderableListView = ReorderableListView.builder( itemBuilder: (BuildContext context, int index) { return SizedBox(child: Text('Item $index')); }, itemCount: 3, onReorder: (int oldIndex, int newIndex) { }, ); await tester.pumpWidget(MaterialApp( home: reorderableListView, )); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect(exception.toString(), contains('Every item of ReorderableListView must have a key.')); }); testWidgets('Throws an error if no overlay present', (WidgetTester tester) async { final Widget reorderableList = ReorderableListView( children: const <Widget>[ SizedBox(width: 100.0, height: 100.0, key: Key('C'), child: Text('C')), SizedBox(width: 100.0, height: 100.0, key: Key('B'), child: Text('B')), SizedBox(width: 100.0, height: 100.0, key: Key('A'), child: Text('A')), ], onReorder: (int oldIndex, int newIndex) { }, ); final Widget boilerplate = Localizations( locale: const Locale('en'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultMaterialLocalizations.delegate, DefaultWidgetsLocalizations.delegate, ], child: SizedBox( width: 100.0, height: 100.0, child: Directionality( textDirection: TextDirection.ltr, child: reorderableList, ), ), ); await tester.pumpWidget(boilerplate); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect(exception.toString(), contains('No Overlay widget found')); expect(exception.toString(), contains('ReorderableListView widgets require an Overlay widget ancestor')); }); testWidgets('ReorderableListView asserts on both non-null itemExtent and prototypeItem', (WidgetTester tester) async { expect(() => ReorderableListView( itemExtent: 30, prototypeItem: const SizedBox(), onReorder: (int fromIndex, int toIndex) { }, children: const <Widget>[], ), throwsAssertionError); }); testWidgets('ReorderableListView.builder asserts on both non-null itemExtent and prototypeItem', (WidgetTester tester) async { final List<int> numbers = <int>[0,1,2]; expect(() => ReorderableListView.builder( itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(numbers[index]), height: 20 + numbers[index] * 10, child: ReorderableDragStartListener( index: index, child: Text(numbers[index].toString()), ) ); }, itemCount: numbers.length, itemExtent: 30, prototypeItem: const SizedBox(), onReorder: (int fromIndex, int toIndex) { }, ), throwsAssertionError); }); testWidgets('if itemExtent is non-null, children have same extent in the scroll direction', (WidgetTester tester) async { final List<int> numbers = <int>[0,1,2]; await tester.pumpWidget( MaterialApp( home: Scaffold( body: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return ReorderableListView.builder( itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(numbers[index]), // children with different heights height: 20 + numbers[index] * 10, child: ReorderableDragStartListener( index: index, child: Text(numbers[index].toString()), ) ); }, itemCount: numbers.length, itemExtent: 30, onReorder: (int fromIndex, int toIndex) { }, ); }, ), ), ) ); final double item0Height = tester.getSize(find.text('0').hitTestable()).height; final double item1Height = tester.getSize(find.text('1').hitTestable()).height; final double item2Height = tester.getSize(find.text('2').hitTestable()).height; expect(item0Height, 30.0); expect(item1Height, 30.0); expect(item2Height, 30.0); }); testWidgets('if prototypeItem is non-null, children have same extent in the scroll direction', (WidgetTester tester) async { final List<int> numbers = <int>[0,1,2]; await tester.pumpWidget( MaterialApp( home: Scaffold( body: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return ReorderableListView.builder( itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(numbers[index]), // children with different heights height: 20 + numbers[index] * 10, child: ReorderableDragStartListener( index: index, child: Text(numbers[index].toString()), ) ); }, itemCount: numbers.length, prototypeItem: const SizedBox( height: 30, child: Text('3'), ), onReorder: (int oldIndex, int newIndex) { }, ); }, ), ), ) ); final double item0Height = tester.getSize(find.text('0').hitTestable()).height; final double item1Height = tester.getSize(find.text('1').hitTestable()).height; final double item2Height = tester.getSize(find.text('2').hitTestable()).height; expect(item0Height, 30.0); expect(item1Height, 30.0); expect(item2Height, 30.0); }); testWidgets('ReorderableListView auto scrolls speed is configurable', (WidgetTester tester) async { Future<void> pumpFor({ required Duration duration, Duration interval = const Duration(milliseconds: 50), }) async { await tester.pump(); int times = (duration.inMilliseconds / interval.inMilliseconds).ceil(); while (times > 0) { await tester.pump(interval + const Duration(milliseconds: 1)); await tester.idle(); times--; } } Future<double> pumpListAndDrag({required double autoScrollerVelocityScalar}) async { final List<int> items = List<int>.generate(10, (int index) => index); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( MaterialApp( home: ReorderableListView.builder( itemBuilder: (BuildContext context, int index) { return Container( key: ValueKey<int>(items[index]), height: 100, color: items[index].isOdd ? Colors.red : Colors.green, child: ReorderableDragStartListener( index: index, child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text('item ${items[index]}'), const Icon(Icons.drag_handle), ], ), ), ); }, itemCount: items.length, onReorder: (int fromIndex, int toIndex) {}, scrollController: scrollController, autoScrollerVelocityScalar: autoScrollerVelocityScalar, ), ), ); expect(scrollController.offset, 0); final Finder item = find.text('item 0'); final TestGesture drag = await tester.startGesture(tester.getCenter(item)); // Drag just enough to touch the edge but not surpass it, so the // auto scroller is not yet triggered await drag.moveBy(const Offset(0, 500)); await pumpFor(duration: const Duration(milliseconds: 200)); expect(scrollController.offset, 0); // Now drag a little bit more so the auto scroller triggers await drag.moveBy(const Offset(0, 50)); await pumpFor( duration: const Duration(milliseconds: 600), interval: Duration(milliseconds: (1000 / autoScrollerVelocityScalar).round()), ); return scrollController.offset; } const double fastVelocityScalar = 20; final double offsetForFastScroller = await pumpListAndDrag(autoScrollerVelocityScalar: fastVelocityScalar); // Reset widget tree await tester.pumpWidget(const SizedBox()); const double slowVelocityScalar = 5; final double offsetForSlowScroller = await pumpListAndDrag(autoScrollerVelocityScalar: slowVelocityScalar); expect(offsetForFastScroller / offsetForSlowScroller, fastVelocityScalar / slowVelocityScalar); }); } Future<void> longPressDrag(WidgetTester tester, Offset start, Offset end) async { final TestGesture drag = await tester.startGesture(start); await tester.pump(kLongPressTimeout + kPressTimeout); await drag.moveTo(end); await tester.pump(kPressTimeout); await drag.up(); } class _Stateful extends StatefulWidget { // Ignoring the preference for const constructors because we want to test with regular non-const instances. // ignore:prefer_const_constructors_in_immutables _Stateful({super.key}); @override State<StatefulWidget> createState() => _StatefulState(); } class _StatefulState extends State<_Stateful> { bool? checked = false; @override Widget build(BuildContext context) { return SizedBox( width: 48.0, height: 48.0, child: Material( child: Checkbox( value: checked, onChanged: (bool? newValue) => checked = newValue, ), ), ); } }
flutter/packages/flutter/test/material/reorderable_list_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/reorderable_list_test.dart", "repo_id": "flutter", "token_count": 36876 }
673
// 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 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('positions itself at anchorAbove if it fits and shifts up when not', (WidgetTester tester) async { late StateSetter setState; const double toolbarOverlap = 100; const double height = 500; double anchorY = 200.0; await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; return CustomSingleChildLayout( delegate: SpellCheckSuggestionsToolbarLayoutDelegate( anchor: Offset(50.0, anchorY), ), child: Container( width: 200.0, height: height, color: const Color(0xffff0000), ), ); }, ), ), ), ); // When the toolbar doesn't fit below anchor, it positions itself such that // it can just fit. double toolbarY = tester.getTopLeft(find.byType(Container)).dy; // Total height available is 600. expect(toolbarY, equals(toolbarOverlap)); // When it does fit below anchor, it positions itself there. setState(() { anchorY = anchorY - toolbarOverlap; }); await tester.pump(); toolbarY = tester.getTopLeft(find.byType(Container)).dy; expect(toolbarY, equals(anchorY)); }); }
flutter/packages/flutter/test/material/spell_check_suggestions_toolbar_layout_delegate_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/spell_check_suggestions_toolbar_layout_delegate_test.dart", "repo_id": "flutter", "token_count": 736 }
674
// 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 'package:flutter/gestures.dart' show kPressTimeout; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; bool confirmCalled = false; bool cancelCalled = false; class TestInkSplash extends InkSplash { TestInkSplash({ required super.controller, required super.referenceBox, super.position, required super.color, super.containedInkWell, super.rectCallback, super.borderRadius, super.customBorder, super.radius, super.onRemoved, required super.textDirection, }); @override void confirm() { confirmCalled = true; super.confirm(); } @override void cancel() { cancelCalled = true; super.cancel(); } } class TestInkSplashFactory extends InteractiveInkFeatureFactory { const TestInkSplashFactory(); @override InteractiveInkFeature create({ required MaterialInkController controller, required RenderBox referenceBox, Offset? position, required Color color, bool containedInkWell = false, RectCallback? rectCallback, BorderRadius? borderRadius, ShapeBorder? customBorder, double? radius, VoidCallback? onRemoved, required TextDirection textDirection, }) { return TestInkSplash( controller: controller, referenceBox: referenceBox, position: position, color: color, containedInkWell: containedInkWell, rectCallback: rectCallback, borderRadius: borderRadius, customBorder: customBorder, radius: radius, onRemoved: onRemoved, textDirection: textDirection, ); } } void main() { setUp(() { confirmCalled = false; cancelCalled = false; }); testWidgets('Tapping should never cause a splash', (WidgetTester tester) async { final Key textField1 = UniqueKey(); final Key textField2 = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Theme( data: ThemeData.light().copyWith(splashFactory: const TestInkSplashFactory()), child: Material( child: Container( alignment: Alignment.topLeft, child: Column( children: <Widget>[ TextField( key: textField1, decoration: const InputDecoration( labelText: 'label', ), ), TextField( key: textField2, decoration: const InputDecoration( labelText: 'label', ), ), ], ), ), ), ), ), ); await tester.tap(find.byKey(textField1)); await tester.pumpAndSettle(); expect(confirmCalled, isFalse); expect(cancelCalled, isFalse); await tester.tap(find.byKey(textField1)); await tester.pumpAndSettle(); expect(confirmCalled, isFalse); expect(cancelCalled, isFalse); await tester.tap(find.byKey(textField2)); await tester.pumpAndSettle(); expect(confirmCalled, isFalse); expect(cancelCalled, isFalse); await tester.tapAt(tester.getTopLeft(find.byKey(textField1))); await tester.pumpAndSettle(); expect(confirmCalled, isFalse); expect(cancelCalled, isFalse); await tester.tap(find.byKey(textField2)); await tester.pumpAndSettle(); expect(confirmCalled, isFalse); expect(cancelCalled, isFalse); }); testWidgets('Splash should never be created or canceled', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Theme( data: ThemeData.light().copyWith(splashFactory: const TestInkSplashFactory()), child: Material( child: ListView( children: <Widget>[ const TextField( decoration: InputDecoration( labelText: 'label1', ), ), const TextField( decoration: InputDecoration( labelText: 'label2', ), ), Container( height: 1000.0, color: const Color(0xFF00FF00), ), ], ), ), ), ), ); // If there were a splash, this would cancel the splash. final TestGesture gesture1 = await tester.startGesture(tester.getCenter(find.text('label1'))); await tester.pump(kPressTimeout); await gesture1.moveTo(const Offset(400.0, 300.0)); await gesture1.up(); expect(confirmCalled, isFalse); expect(cancelCalled, isFalse); // Pointer is dragged upwards causing a scroll, splash would be canceled. final TestGesture gesture2 = await tester.startGesture(tester.getCenter(find.text('label2'))); await tester.pump(kPressTimeout); await gesture2.moveBy(const Offset(0.0, -200.0)); await gesture2.up(); expect(confirmCalled, isFalse); expect(cancelCalled, isFalse); }); }
flutter/packages/flutter/test/material/text_field_splash_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/text_field_splash_test.dart", "repo_id": "flutter", "token_count": 2303 }
675
// 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 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; Widget boilerplate({required Widget child}) { return Directionality( textDirection: TextDirection.ltr, child: Center(child: child), ); } void main() { test('ToggleButtonsThemeData copyWith, ==, hashCode basics', () { expect(const ToggleButtonsThemeData(), const ToggleButtonsThemeData().copyWith()); expect(const ToggleButtonsThemeData().hashCode, const ToggleButtonsThemeData().copyWith().hashCode); }); test('ToggleButtonsThemeData lerp special cases', () { expect(ToggleButtonsThemeData.lerp(null, null, 0), null); const ToggleButtonsThemeData data = ToggleButtonsThemeData(); expect(identical(ToggleButtonsThemeData.lerp(data, data, 0.5), data), true); }); test('ToggleButtonsThemeData defaults', () { const ToggleButtonsThemeData themeData = ToggleButtonsThemeData(); expect(themeData.textStyle, null); expect(themeData.constraints, null); expect(themeData.color, null); expect(themeData.selectedColor, null); expect(themeData.disabledColor, null); expect(themeData.fillColor, null); expect(themeData.focusColor, null); expect(themeData.highlightColor, null); expect(themeData.hoverColor, null); expect(themeData.splashColor, null); expect(themeData.borderColor, null); expect(themeData.selectedBorderColor, null); expect(themeData.disabledBorderColor, null); expect(themeData.borderRadius, null); expect(themeData.borderWidth, null); const ToggleButtonsTheme theme = ToggleButtonsTheme(data: ToggleButtonsThemeData(), child: SizedBox()); expect(theme.data.textStyle, null); expect(theme.data.constraints, null); expect(theme.data.color, null); expect(theme.data.selectedColor, null); expect(theme.data.disabledColor, null); expect(theme.data.fillColor, null); expect(theme.data.focusColor, null); expect(theme.data.highlightColor, null); expect(theme.data.hoverColor, null); expect(theme.data.splashColor, null); expect(theme.data.borderColor, null); expect(theme.data.selectedBorderColor, null); expect(theme.data.disabledBorderColor, null); expect(theme.data.borderRadius, null); expect(theme.data.borderWidth, null); }); testWidgets('Default ToggleButtonsThemeData debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const ToggleButtonsThemeData().debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description, <String>[]); }); testWidgets('ToggleButtonsThemeData implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const ToggleButtonsThemeData( textStyle: TextStyle(fontSize: 10), constraints: BoxConstraints(minHeight: 10.0, maxHeight: 20.0), color: Color(0xfffffff0), selectedColor: Color(0xfffffff1), disabledColor: Color(0xfffffff2), fillColor: Color(0xfffffff3), focusColor: Color(0xfffffff4), highlightColor: Color(0xfffffff5), hoverColor: Color(0xfffffff6), splashColor: Color(0xfffffff7), borderColor: Color(0xfffffff8), selectedBorderColor: Color(0xfffffff9), disabledBorderColor: Color(0xfffffffa), borderRadius: BorderRadius.all(Radius.circular(4.0)), borderWidth: 2.0, ).debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description, <String>[ 'textStyle.inherit: true', 'textStyle.size: 10.0', 'constraints: BoxConstraints(0.0<=w<=Infinity, 10.0<=h<=20.0)', 'color: Color(0xfffffff0)', 'selectedColor: Color(0xfffffff1)', 'disabledColor: Color(0xfffffff2)', 'fillColor: Color(0xfffffff3)', 'focusColor: Color(0xfffffff4)', 'highlightColor: Color(0xfffffff5)', 'hoverColor: Color(0xfffffff6)', 'splashColor: Color(0xfffffff7)', 'borderColor: Color(0xfffffff8)', 'selectedBorderColor: Color(0xfffffff9)', 'disabledBorderColor: Color(0xfffffffa)', 'borderRadius: BorderRadius.circular(4.0)', 'borderWidth: 2.0', ]); }); testWidgets('Theme text style, except color, is applied', (WidgetTester tester) async { await tester.pumpWidget( Material( child: boilerplate( child: ToggleButtonsTheme( data: const ToggleButtonsThemeData( textStyle: TextStyle( color: Colors.orange, textBaseline: TextBaseline.ideographic, fontSize: 20.0, ), ), child: ToggleButtons( isSelected: const <bool>[false, true], onPressed: (int index) {}, children: const <Widget>[ Text('First child'), Text('Second child'), ], ), ), ), ), ); TextStyle textStyle; textStyle = tester.widget<DefaultTextStyle>(find.descendant( of: find.widgetWithText(TextButton, 'First child'), matching: find.byType(DefaultTextStyle), )).style; expect(textStyle.textBaseline, TextBaseline.ideographic); expect(textStyle.fontSize, 20.0); expect(textStyle.color, isNot(Colors.orange)); textStyle = tester.widget<DefaultTextStyle>(find.descendant( of: find.widgetWithText(TextButton, 'Second child'), matching: find.byType(DefaultTextStyle), )).style; expect(textStyle.textBaseline, TextBaseline.ideographic); expect(textStyle.fontSize, 20.0); expect(textStyle.color, isNot(Colors.orange)); }); testWidgets('Custom BoxConstraints', (WidgetTester tester) async { // Test for minimum constraints await tester.pumpWidget( Material( child: boilerplate( child: ToggleButtonsTheme( data: const ToggleButtonsThemeData( constraints: BoxConstraints( minWidth: 50.0, minHeight: 60.0, ), ), child: ToggleButtons( tapTargetSize: MaterialTapTargetSize.shrinkWrap, isSelected: const <bool>[false, false, false], onPressed: (int index) {}, children: const <Widget>[ Icon(Icons.check), Icon(Icons.access_alarm), Icon(Icons.cake), ], ), ), ), ), ); Rect firstRect = tester.getRect(find.byType(TextButton).at(0)); expect(firstRect.width, 50.0); expect(firstRect.height, 60.0); Rect secondRect = tester.getRect(find.byType(TextButton).at(1)); expect(secondRect.width, 50.0); expect(secondRect.height, 60.0); Rect thirdRect = tester.getRect(find.byType(TextButton).at(2)); expect(thirdRect.width, 50.0); expect(thirdRect.height, 60.0); // Test for maximum constraints await tester.pumpWidget( Material( child: boilerplate( child: ToggleButtonsTheme( data: const ToggleButtonsThemeData( constraints: BoxConstraints( maxWidth: 20.0, maxHeight: 10.0, ), ), child: ToggleButtons( tapTargetSize: MaterialTapTargetSize.shrinkWrap, isSelected: const <bool>[false, false, false], onPressed: (int index) {}, children: const <Widget>[ Icon(Icons.check), Icon(Icons.access_alarm), Icon(Icons.cake), ], ), ), ), ), ); firstRect = tester.getRect(find.byType(TextButton).at(0)); expect(firstRect.width, 20.0); expect(firstRect.height, 10.0); secondRect = tester.getRect(find.byType(TextButton).at(1)); expect(secondRect.width, 20.0); expect(secondRect.height, 10.0); thirdRect = tester.getRect(find.byType(TextButton).at(2)); expect(thirdRect.width, 20.0); expect(thirdRect.height, 10.0); }); testWidgets( 'Theme text/icon colors for enabled, selected and disabled states', (WidgetTester tester) async { TextStyle buttonTextStyle(String text) { return tester.widget<DefaultTextStyle>(find.descendant( of: find.widgetWithText(TextButton, text), matching: find.byType(DefaultTextStyle), )).style; } IconTheme iconTheme(IconData icon) { return tester.widget(find.descendant( of: find.widgetWithIcon(TextButton, icon), matching: find.byType(IconTheme), )); } final ThemeData theme = ThemeData(); const Color enabledColor = Colors.lime; const Color selectedColor = Colors.green; const Color disabledColor = Colors.yellow; await tester.pumpWidget( Material( child: boilerplate( child: ToggleButtonsTheme( data: const ToggleButtonsThemeData(), child: ToggleButtons( color: enabledColor, isSelected: const <bool>[false], onPressed: (int index) {}, children: const <Widget>[ // This Row is used like this to test for both TextStyle // and IconTheme for Text and Icon widgets respectively. Row(children: <Widget>[ Text('First child'), Icon(Icons.check), ]), ], ), ), ), ), ); // Custom theme enabled color expect(theme.colorScheme.onSurface, isNot(enabledColor)); expect(buttonTextStyle('First child').color, enabledColor); expect(iconTheme(Icons.check).data.color, enabledColor); await tester.pumpWidget( Material( child: boilerplate( child: ToggleButtonsTheme( data: const ToggleButtonsThemeData( selectedColor: selectedColor, ), child: ToggleButtons( color: enabledColor, isSelected: const <bool>[true], onPressed: (int index) {}, children: const <Widget>[ Row(children: <Widget>[ Text('First child'), Icon(Icons.check), ]), ], ), ), ), ), ); await tester.pumpAndSettle(); // Custom theme selected color expect(theme.colorScheme.primary, isNot(selectedColor)); expect(buttonTextStyle('First child').color, selectedColor); expect(iconTheme(Icons.check).data.color, selectedColor); await tester.pumpWidget( Material( child: boilerplate( child: ToggleButtonsTheme( data: const ToggleButtonsThemeData( disabledColor: disabledColor, ), child: ToggleButtons( color: enabledColor, isSelected: const <bool>[false], children: const <Widget>[ Row(children: <Widget>[ Text('First child'), Icon(Icons.check), ]), ], ), ), ), ), ); await tester.pumpAndSettle(); // Custom theme disabled color expect(theme.disabledColor, isNot(disabledColor)); expect(buttonTextStyle('First child').color, disabledColor); expect(iconTheme(Icons.check).data.color, disabledColor); }, ); testWidgets('Theme button fillColor', (WidgetTester tester) async { const Color customFillColor = Colors.green; await tester.pumpWidget( Material( child: boilerplate( child: ToggleButtonsTheme( data: const ToggleButtonsThemeData(fillColor: customFillColor), child: ToggleButtons( isSelected: const <bool>[true], onPressed: (int index) {}, children: const <Widget>[ Row(children: <Widget>[ Text('First child'), ]), ], ), ), ), ), ); final Material material = tester.widget<Material>(find.descendant( of: find.byType(TextButton), matching: find.byType(Material), )); expect(material.color, customFillColor); expect(material.type, MaterialType.button); }); testWidgets('Custom Theme button fillColor in different states', (WidgetTester tester) async { Material buttonColor(String text) { return tester.widget<Material>( find.descendant( of: find.byType(TextButton), matching: find.widgetWithText(Material, text), ), ); } const Color enabledFillColor = Colors.green; const Color selectedFillColor = Colors.blue; const Color disabledFillColor = Colors.yellow; Color getColor(Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return selectedFillColor; } else if (states.contains(MaterialState.disabled)) { return disabledFillColor; } return enabledFillColor; } await tester.pumpWidget( Material( child: boilerplate( child: ToggleButtonsTheme( data: ToggleButtonsThemeData(fillColor: MaterialStateColor.resolveWith(getColor)), child: ToggleButtons( isSelected: const <bool>[true, false], onPressed: (int index) {}, children: const <Widget> [ Text('First child'), Text('Second child'), ], ), ), ), ), ); await tester.pumpAndSettle(); expect(buttonColor('First child').color, selectedFillColor); expect(buttonColor('Second child').color, enabledFillColor); await tester.pumpWidget( Material( child: boilerplate( child: ToggleButtonsTheme( data: ToggleButtonsThemeData(fillColor: MaterialStateColor.resolveWith(getColor)), child: ToggleButtons( isSelected: const <bool>[true, false], children: const <Widget>[ Text('First child'), Text('Second child'), ], ), ), ), ), ); expect(buttonColor('First child').color, disabledFillColor); expect(buttonColor('Second child').color, disabledFillColor); }); testWidgets('Theme InkWell colors', (WidgetTester tester) async { const Color splashColor = Color(0xff4caf50); const Color highlightColor = Color(0xffcddc39); const Color hoverColor = Color(0xffffeb3b); const Color focusColor = Color(0xffffff00); final FocusNode focusNode = FocusNode(); await tester.pumpWidget( Material( child: boilerplate( child: ToggleButtonsTheme( data: const ToggleButtonsThemeData( splashColor: splashColor, highlightColor: highlightColor, hoverColor: hoverColor, focusColor: focusColor, ), child: ToggleButtons( isSelected: const <bool>[true], onPressed: (int index) {}, focusNodes: <FocusNode>[focusNode], children: const <Widget>[ Text('First child'), ], ), ), ), ), ); final Offset center = tester.getCenter(find.text('First child')); // splashColor // highlightColor final TestGesture touchGesture = await tester.createGesture(); await touchGesture.down(center); await tester.pumpAndSettle(); RenderObject inkFeatures; inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) { return object.runtimeType.toString() == '_RenderInkFeatures'; }); expect( inkFeatures, paints ..circle(color: splashColor) ); await touchGesture.up(); await tester.pumpAndSettle(); // hoverColor final TestGesture hoverGesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await hoverGesture.addPointer(); await hoverGesture.moveTo(center); await tester.pumpAndSettle(); inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) { return object.runtimeType.toString() == '_RenderInkFeatures'; }); expect(inkFeatures, paints..rect(color: hoverColor)); await hoverGesture.moveTo(Offset.zero); // focusColor focusNode.requestFocus(); await tester.pumpAndSettle(); inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) { return object.runtimeType.toString() == '_RenderInkFeatures'; }); expect(inkFeatures, paints..rect(color: focusColor)); await hoverGesture.removePointer(); focusNode.dispose(); }); testWidgets( 'Theme border width and border colors for enabled, selected and disabled states', (WidgetTester tester) async { const Color borderColor = Color(0xff4caf50); const Color selectedBorderColor = Color(0xffcddc39); const Color disabledBorderColor = Color(0xffffeb3b); const double customWidth = 2.0; await tester.pumpWidget( Material( child: boilerplate( child: ToggleButtonsTheme( data: const ToggleButtonsThemeData( borderColor: borderColor, borderWidth: customWidth, ), child: ToggleButtons( isSelected: const <bool>[false], onPressed: (int index) {}, children: const <Widget>[ Text('First child'), ], ), ), ), ), ); RenderObject toggleButtonRenderObject; toggleButtonRenderObject = tester.allRenderObjects.firstWhere((RenderObject object) { return object.runtimeType.toString() == '_SelectToggleButtonRenderObject'; }); expect( toggleButtonRenderObject, paints // physical model layer paint ..path() ..path( style: PaintingStyle.stroke, color: borderColor, strokeWidth: customWidth, ), ); await tester.pumpWidget( Material( child: boilerplate( child: ToggleButtonsTheme( data: const ToggleButtonsThemeData( selectedBorderColor: selectedBorderColor, borderWidth: customWidth, ), child: ToggleButtons( isSelected: const <bool>[true], onPressed: (int index) {}, children: const <Widget>[ Text('First child'), ], ), ), ), ), ); toggleButtonRenderObject = tester.allRenderObjects.firstWhere((RenderObject object) { return object.runtimeType.toString() == '_SelectToggleButtonRenderObject'; }); expect( toggleButtonRenderObject, paints // physical model layer paint ..path() ..path( style: PaintingStyle.stroke, color: selectedBorderColor, strokeWidth: customWidth, ), ); await tester.pumpWidget( Material( child: boilerplate( child: ToggleButtonsTheme( data: const ToggleButtonsThemeData( disabledBorderColor: disabledBorderColor, borderWidth: customWidth, ), child: ToggleButtons( isSelected: const <bool>[false], children: const <Widget>[ Text('First child'), ], ), ), ), ), ); toggleButtonRenderObject = tester.allRenderObjects.firstWhere((RenderObject object) { return object.runtimeType.toString() == '_SelectToggleButtonRenderObject'; }); expect( toggleButtonRenderObject, paints // physical model layer paint ..path() ..path( style: PaintingStyle.stroke, color: disabledBorderColor, strokeWidth: customWidth, ), ); }, ); }
flutter/packages/flutter/test/material/toggle_buttons_theme_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/toggle_buttons_theme_test.dart", "repo_id": "flutter", "token_count": 9393 }
676
// 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 'package:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('BorderSide - asserts when constructed incorrectly', () { expect( const BorderSide(), const BorderSide(), ); expect(() => BorderSide(width: nonconst(-1.0)), throwsAssertionError); expect( const BorderSide(width: -0.0), const BorderSide( width: 0.0, ), ); }); test('BorderSide - merging', () { const BorderSide blue = BorderSide(color: Color(0xFF0000FF)); const BorderSide blue2 = BorderSide(color: Color(0xFF0000FF), width: 2.0); const BorderSide green = BorderSide(color: Color(0xFF00FF00)); const BorderSide green2 = BorderSide(color: Color(0xFF00FF00), width: 2.0); const BorderSide green3 = BorderSide(color: Color(0xFF00FF00), width: 3.0); const BorderSide green5 = BorderSide(color: Color(0xFF00FF00), width: 5.0); const BorderSide none = BorderSide(style: BorderStyle.none); const BorderSide none2 = BorderSide(color: Color(0xFF0000FF), width: 2.0, style: BorderStyle.none); const BorderSide none3 = BorderSide(style: BorderStyle.none, width: 3.0); const BorderSide side2 = BorderSide(width: 2.0); const BorderSide side3 = BorderSide(width: 3.0); const BorderSide side5 = BorderSide(width: 5.0); const BorderSide solid = BorderSide(); const BorderSide yellowNone = BorderSide(style: BorderStyle.none, color: Color(0xFFFFFF00), width: 0.0); // canMerge expect( BorderSide.canMerge(BorderSide.none, BorderSide.none), isTrue); expect( BorderSide.canMerge(BorderSide.none, side2), isTrue); expect( BorderSide.canMerge(BorderSide.none, yellowNone), isTrue); expect( BorderSide.canMerge(green, blue), isFalse); expect( BorderSide.canMerge(green2, blue2), isFalse); expect( BorderSide.canMerge(green2, green3), isTrue); expect( BorderSide.canMerge(green2, none2), isFalse); expect( BorderSide.canMerge(none3, BorderSide.none), isTrue); expect( BorderSide.canMerge(none3, side2), isFalse); expect( BorderSide.canMerge(none3, yellowNone), isTrue); expect( BorderSide.canMerge(side2, BorderSide.none), isTrue); expect( BorderSide.canMerge(side2, none3), isFalse); expect( BorderSide.canMerge(side2, side3), isTrue); expect( BorderSide.canMerge(side2, yellowNone), isTrue); expect( BorderSide.canMerge(side3, side2), isTrue); expect( BorderSide.canMerge(solid, none), isFalse); expect( BorderSide.canMerge(yellowNone, side2), isTrue); expect( BorderSide.canMerge(yellowNone, yellowNone), isTrue); // merge, for the same combinations expect( BorderSide.merge(BorderSide.none, BorderSide.none), BorderSide.none); expect( BorderSide.merge(BorderSide.none, side2), side2); expect( BorderSide.merge(BorderSide.none, yellowNone), BorderSide.none); expect(() => BorderSide.merge(green, blue), throwsAssertionError); expect(() => BorderSide.merge(green2, blue2), throwsAssertionError); expect( BorderSide.merge(green2, green3), green5); expect(() => BorderSide.merge(green2, none2), throwsAssertionError); expect( BorderSide.merge(none3, BorderSide.none), none3); expect(() => BorderSide.merge(none3, side2), throwsAssertionError); expect( BorderSide.merge(none3, yellowNone), none3); expect( BorderSide.merge(side2, BorderSide.none), side2); expect(() => BorderSide.merge(side2, none3), throwsAssertionError); expect( BorderSide.merge(side2, side3), side5); expect( BorderSide.merge(side2, yellowNone), side2); expect( BorderSide.merge(side3, side2), side5); expect(() => BorderSide.merge(solid, none), throwsAssertionError); expect( BorderSide.merge(yellowNone, side2), side2); expect( BorderSide.merge(yellowNone, yellowNone), BorderSide.none); }); test('BorderSide - asserts when copied incorrectly', () { const BorderSide green2 = BorderSide(color: Color(0xFF00FF00), width: 2.0); const BorderSide blue3 = BorderSide(color: Color(0xFF0000FF), width: 3.0); const BorderSide blue2 = BorderSide(color: Color(0xFF0000FF), width: 2.0); const BorderSide green3 = BorderSide(color: Color(0xFF00FF00), width: 3.0); const BorderSide none2 = BorderSide(color: Color(0xFF00FF00), width: 2.0, style: BorderStyle.none); expect(green2.copyWith(color: const Color(0xFF0000FF), width: 3.0), blue3); expect(green2.copyWith(width: 3.0), green3); expect(green2.copyWith(color: const Color(0xFF0000FF)), blue2); expect(green2.copyWith(style: BorderStyle.none), none2); }); test('BorderSide - scale', () { const BorderSide side3 = BorderSide(width: 3.0, color: Color(0xFF0000FF)); const BorderSide side6 = BorderSide(width: 6.0, color: Color(0xFF0000FF)); const BorderSide none = BorderSide(style: BorderStyle.none, width: 0.0, color: Color(0xFF0000FF)); expect(side3.scale(2.0), side6); expect(side6.scale(0.5), side3); expect(side6.scale(0.0), none); expect(side6.scale(-1.0), none); expect(none.scale(2.0), none); }); test('BorderSide - toPaint', () { final Paint paint1 = const BorderSide(width: 2.5, color: Color(0xFFFFFF00)).toPaint(); expect(paint1.strokeWidth, 2.5); expect(paint1.style, PaintingStyle.stroke); expect(paint1.color, const Color(0xFFFFFF00)); expect(paint1.blendMode, BlendMode.srcOver); final Paint paint2 = const BorderSide(width: 2.5, color: Color(0xFFFFFF00), style: BorderStyle.none).toPaint(); expect(paint2.strokeWidth, 0.0); expect(paint2.style, PaintingStyle.stroke); expect(paint2.color, const Color(0x00000000)); expect(paint2.blendMode, BlendMode.srcOver); }); test('BorderSide - lerp identical a,b', () { const BorderSide border = BorderSide(); expect(identical(BorderSide.lerp(border, border, 0.5), border), true); }); test("BorderSide - won't lerp into negative widths", () { const BorderSide side0 = BorderSide(width: 0.0); const BorderSide side1 = BorderSide(); const BorderSide side2 = BorderSide(width: 2.0); expect(BorderSide.lerp(side2, side1, 10.0), BorderSide.none); expect(BorderSide.lerp(side1, side2, -10.0), BorderSide.none); expect(BorderSide.lerp(side0, side1, 2.0), side2); expect(BorderSide.lerp(side1, side0, 2.0), BorderSide.none); expect(BorderSide.lerp(side2, side1, 2.0), side0); }); test('BorderSide - toString', () { expect( const BorderSide(color: Color(0xFFAABBCC), width: 1.2345).toString(), 'BorderSide(color: Color(0xffaabbcc), width: 1.2)', ); }); test('BorderSide - lerp with strokeAlign', () { const BorderSide side0 = BorderSide(width: 2.0); const BorderSide side1 = BorderSide(width: 2.0, strokeAlign: BorderSide.strokeAlignOutside); expect(BorderSide.lerp(side0, side1, 0), const BorderSide(width: 2.0)); expect(BorderSide.lerp(side0, side1, 0.5), const BorderSide(width: 2.0, strokeAlign: BorderSide.strokeAlignCenter)); expect(BorderSide.lerp(side0, side1, 1), const BorderSide(width: 2.0, strokeAlign: BorderSide.strokeAlignOutside)); const BorderSide side2 = BorderSide(width: 2.0); const BorderSide side3 = BorderSide(width: 2.0, strokeAlign: BorderSide.strokeAlignCenter); expect(BorderSide.lerp(side2, side3, 0), const BorderSide(width: 2.0)); expect(BorderSide.lerp(side2, side3, 0.5), const BorderSide(width: 2.0, strokeAlign: -0.5)); expect(BorderSide.lerp(side2, side3, 1), const BorderSide(width: 2.0, strokeAlign: BorderSide.strokeAlignCenter)); }); }
flutter/packages/flutter/test/painting/border_side_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/border_side_test.dart", "repo_id": "flutter", "token_count": 2974 }
677
// 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 'package:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('positionDependentBox', () { // For historical reasons, significantly more tests of this function // exist in: ../material/tooltip_test.dart expect( positionDependentBox( size: const Size(100.0, 100.0), childSize: const Size(20.0, 10.0), target: const Offset(50.0, 50.0), preferBelow: false, margin: 0.0, ), const Offset(40.0, 40.0), ); expect( positionDependentBox( size: const Size(100.0, 100.0), childSize: const Size(200.0, 10.0), target: const Offset(50.0, 50.0), preferBelow: false, margin: 0.0, ), const Offset(-50.0, 40.0), ); expect( positionDependentBox( size: const Size(100.0, 100.0), childSize: const Size(200.0, 10.0), target: const Offset(0.0, 50.0), preferBelow: false, margin: 0.0, ), const Offset(-50.0, 40.0), ); expect( positionDependentBox( size: const Size(100.0, 100.0), childSize: const Size(200.0, 10.0), target: const Offset(100.0, 50.0), preferBelow: false, margin: 0.0, ), const Offset(-50.0, 40.0), ); expect( positionDependentBox( size: const Size(100.0, 100.0), childSize: const Size(50.0, 10.0), target: const Offset(50.0, 50.0), preferBelow: false, margin: 20.0, // 60.0 left ), const Offset(25.0, 40.0), ); expect( positionDependentBox( size: const Size(100.0, 100.0), childSize: const Size(50.0, 10.0), target: const Offset(50.0, 50.0), preferBelow: false, margin: 30.0, // 40.0 left ), const Offset(25.0, 40.0), ); expect( positionDependentBox( size: const Size(100.0, 100.0), childSize: const Size(50.0, 10.0), target: const Offset(0.0, 50.0), preferBelow: false, margin: 20.0, // 60.0 left ), const Offset(20.0, 40.0), ); expect( positionDependentBox( size: const Size(100.0, 100.0), childSize: const Size(50.0, 10.0), target: const Offset(0.0, 50.0), preferBelow: false, margin: 30.0, // 40.0 left ), const Offset(25.0, 40.0), ); expect( positionDependentBox( size: const Size(100.0, 100.0), childSize: const Size(50.0, 10.0), target: const Offset(100.0, 50.0), preferBelow: false, margin: 20.0, // 60.0 left ), const Offset(30.0, 40.0), ); expect( positionDependentBox( size: const Size(100.0, 100.0), childSize: const Size(50.0, 10.0), target: const Offset(100.0, 50.0), preferBelow: false, margin: 30.0, // 40.0 left ), const Offset(25.0, 40.0), ); }); }
flutter/packages/flutter/test/painting/geometry_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/geometry_test.dart", "repo_id": "flutter", "token_count": 1550 }
678
// 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'; import 'package:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:vector_math/vector_math_64.dart'; void main() { test('MatrixUtils.transformRect handles very large finite values', () { const Rect evilRect = Rect.fromLTRB(0.0, -1.7976931348623157e+308, 800.0, 1.7976931348623157e+308); final Matrix4 transform = Matrix4.identity()..translate(10.0); final Rect transformedRect = MatrixUtils.transformRect(transform, evilRect); expect(transformedRect.isFinite, true); }); test('MatrixUtils.getAsTranslation()', () { Matrix4 test; test = Matrix4.identity(); expect(MatrixUtils.getAsTranslation(test), equals(Offset.zero)); test = Matrix4.zero(); expect(MatrixUtils.getAsTranslation(test), isNull); test = Matrix4.rotationX(1.0); expect(MatrixUtils.getAsTranslation(test), isNull); test = Matrix4.rotationZ(1.0); expect(MatrixUtils.getAsTranslation(test), isNull); test = Matrix4.translationValues(1.0, 2.0, 0.0); expect(MatrixUtils.getAsTranslation(test), equals(const Offset(1.0, 2.0))); test = Matrix4.translationValues(1.0, 2.0, 3.0); expect(MatrixUtils.getAsTranslation(test), isNull); test = Matrix4.identity(); expect(MatrixUtils.getAsTranslation(test), equals(Offset.zero)); test.rotateX(2.0); expect(MatrixUtils.getAsTranslation(test), isNull); test = Matrix4.identity(); expect(MatrixUtils.getAsTranslation(test), equals(Offset.zero)); test.scale(2.0); expect(MatrixUtils.getAsTranslation(test), isNull); test = Matrix4.identity(); expect(MatrixUtils.getAsTranslation(test), equals(Offset.zero)); test.translate(2.0, -2.0); expect(MatrixUtils.getAsTranslation(test), equals(const Offset(2.0, -2.0))); test.translate(4.0, 8.0); expect(MatrixUtils.getAsTranslation(test), equals(const Offset(6.0, 6.0))); }); test('cylindricalProjectionTransform identity', () { final Matrix4 initialState = MatrixUtils.createCylindricalProjectionTransform( radius: 0.0, angle: 0.0, perspective: 0.0, ); expect(initialState, Matrix4.identity()); }); test('cylindricalProjectionTransform rotate with no radius', () { final Matrix4 simpleRotate = MatrixUtils.createCylindricalProjectionTransform( radius: 0.0, angle: pi / 2.0, perspective: 0.0, ); expect(simpleRotate, Matrix4.rotationX(pi / 2.0)); }); test('cylindricalProjectionTransform radius does not change scale', () { final Matrix4 noRotation = MatrixUtils.createCylindricalProjectionTransform( radius: 1000000.0, angle: 0.0, perspective: 0.0, ); expect(noRotation, Matrix4.identity()); }); test('cylindricalProjectionTransform calculation spot check', () { final Matrix4 actual = MatrixUtils.createCylindricalProjectionTransform( radius: 100.0, angle: pi / 3.0, ); expect(actual.storage, <dynamic>[ 1.0, 0.0, 0.0, 0.0, 0.0, moreOrLessEquals(0.5), moreOrLessEquals(0.8660254037844386), moreOrLessEquals(-0.0008660254037844386), 0.0, moreOrLessEquals(-0.8660254037844386), moreOrLessEquals(0.5), moreOrLessEquals(-0.0005), 0.0, moreOrLessEquals(-86.60254037844386), moreOrLessEquals(-50.0), 1.05, ]); }); test('forceToPoint', () { const Offset forcedOffset = Offset(20, -30); final Matrix4 forcedTransform = MatrixUtils.forceToPoint(forcedOffset); expect( MatrixUtils.transformPoint(forcedTransform, forcedOffset), forcedOffset, ); expect( MatrixUtils.transformPoint(forcedTransform, Offset.zero), forcedOffset, ); expect( MatrixUtils.transformPoint(forcedTransform, const Offset(1, 1)), forcedOffset, ); expect( MatrixUtils.transformPoint(forcedTransform, const Offset(-1, -1)), forcedOffset, ); expect( MatrixUtils.transformPoint(forcedTransform, const Offset(-20, 30)), forcedOffset, ); expect( MatrixUtils.transformPoint(forcedTransform, const Offset(-1.2344, 1422434.23)), forcedOffset, ); }); test('transformRect with no perspective (w = 1)', () { const Rect rectangle20x20 = Rect.fromLTRB(10, 20, 30, 40); // Identity expect( MatrixUtils.transformRect(Matrix4.identity(), rectangle20x20), rectangle20x20, ); // 2D Scaling expect( MatrixUtils.transformRect(Matrix4.diagonal3Values(2, 2, 2), rectangle20x20), const Rect.fromLTRB(20, 40, 60, 80), ); // Rotation expect( MatrixUtils.transformRect(Matrix4.rotationZ(pi / 2.0), rectangle20x20), within<Rect>(distance: 0.00001, from: const Rect.fromLTRB(-40.0, 10.0, -20.0, 30.0)), ); }); test('transformRect with perspective (w != 1)', () { final Matrix4 transform = MatrixUtils.createCylindricalProjectionTransform( radius: 10.0, angle: pi / 8.0, perspective: 0.3, ); for (int i = 1; i < 10000; i++) { final Rect rect = Rect.fromLTRB(11.0 * i, 12.0 * i, 15.0 * i, 18.0 * i); final Rect golden = _vectorWiseTransformRect(transform, rect); expect( MatrixUtils.transformRect(transform, rect), within<Rect>(distance: 0.00001, from: golden), ); } }); } // Produces the same computation as `MatrixUtils.transformPoint` but it uses // the built-in perspective transform methods in the Matrix4 class as a // golden implementation of the optimized `MatrixUtils.transformPoint` // to make sure optimizations do not contain bugs. Offset _transformPoint(Matrix4 transform, Offset point) { final Vector3 position3 = Vector3(point.dx, point.dy, 0.0); final Vector3 transformed3 = transform.perspectiveTransform(position3); return Offset(transformed3.x, transformed3.y); } // Produces the same computation as `MatrixUtils.transformRect` but it does this // one point at a time. This function is used as the golden implementation of the // optimized `MatrixUtils.transformRect` to make sure optimizations do not contain // bugs. Rect _vectorWiseTransformRect(Matrix4 transform, Rect rect) { final Offset point1 = _transformPoint(transform, rect.topLeft); final Offset point2 = _transformPoint(transform, rect.topRight); final Offset point3 = _transformPoint(transform, rect.bottomLeft); final Offset point4 = _transformPoint(transform, rect.bottomRight); return Rect.fromLTRB( _min4(point1.dx, point2.dx, point3.dx, point4.dx), _min4(point1.dy, point2.dy, point3.dy, point4.dy), _max4(point1.dx, point2.dx, point3.dx, point4.dx), _max4(point1.dy, point2.dy, point3.dy, point4.dy), ); } double _min4(double a, double b, double c, double d) { return min(a, min(b, min(c, d))); } double _max4(double a, double b, double c, double d) { return max(a, max(b, max(c, d))); }
flutter/packages/flutter/test/painting/matrix_utils_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/matrix_utils_test.dart", "repo_id": "flutter", "token_count": 2630 }
679
// 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:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; void _checkCaretOffsetsLtrAt(String text, List<int> boundaries) { expect(boundaries.first, 0); expect(boundaries.last, text.length); final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr; // Lay out the string up to each boundary, and record the width. final List<double> prefixWidths = <double>[]; for (final int boundary in boundaries) { painter.text = TextSpan(text: text.substring(0, boundary)); painter.layout(); prefixWidths.add(painter.width); } // The painter has the full text laid out. Check the caret offsets. double caretOffset(int offset) { final TextPosition position = ui.TextPosition(offset: offset); return painter.getOffsetForCaret(position, ui.Rect.zero).dx; } expect(boundaries.map(caretOffset).toList(), prefixWidths); double lastOffset = caretOffset(0); for (int i = 1; i <= text.length; i++) { final double offset = caretOffset(i); expect(offset, greaterThanOrEqualTo(lastOffset)); lastOffset = offset; } painter.dispose(); } /// Check the caret offsets are accurate for the given single line of LTR text. /// /// This lays out the given text as a single line with [TextDirection.ltr] /// and checks the following invariants, which should always hold if the text /// is made up of LTR characters: /// * The caret offsets go monotonically from 0.0 to the width of the text. /// * At each character (that is, grapheme cluster) boundary, the caret /// offset equals the width that the text up to that point would have /// if laid out on its own. /// /// If you have a [TextSpan] instead of a plain [String], /// see [caretOffsetsForTextSpan]. void checkCaretOffsetsLtr(String text) { final List<int> characterBoundaries = <int>[]; final CharacterRange range = CharacterRange.at(text, 0); while (true) { characterBoundaries.add(range.current.length); if (range.stringAfterLength <= 0) { break; } range.expandNext(); } _checkCaretOffsetsLtrAt(text, characterBoundaries); } /// Check the caret offsets are accurate for the given single line of LTR text, /// ignoring character boundaries within each given cluster. /// /// This concatenates [clusters] into a string and then performs the same /// checks as [checkCaretOffsetsLtr], except that instead of checking the /// offset-equals-prefix-width invariant at every character boundary, /// it does so only at the boundaries between the elements of [clusters]. /// /// The elements of [clusters] should be composed of whole characters: each /// element should be a valid character range in the concatenated string. /// /// Consider using [checkCaretOffsetsLtr] instead of this function. If that /// doesn't pass, you may have an instance of <https://github.com/flutter/flutter/issues/122478>. void checkCaretOffsetsLtrFromPieces(List<String> clusters) { final StringBuffer buffer = StringBuffer(); final List<int> boundaries = <int>[]; boundaries.add(buffer.length); for (final String cluster in clusters) { buffer.write(cluster); boundaries.add(buffer.length); } _checkCaretOffsetsLtrAt(buffer.toString(), boundaries); } /// Compute the caret offsets for the given single line of text, a [TextSpan]. /// /// This lays out the given text as a single line with the given [textDirection] /// and returns a full list of caret offsets, one at each code unit boundary. /// /// This also checks that the offset at the very start or very end, if the text /// direction is RTL or LTR respectively, equals the line's width. /// /// If you have a [String] instead of a nontrivial [TextSpan], /// consider using [checkCaretOffsetsLtr] instead. List<double> caretOffsetsForTextSpan(TextDirection textDirection, TextSpan text) { final TextPainter painter = TextPainter() ..textDirection = textDirection ..text = text ..layout(); final int length = text.toPlainText().length; final List<double> result = List<double>.generate(length + 1, (int offset) { final TextPosition position = ui.TextPosition(offset: offset); return painter.getOffsetForCaret(position, ui.Rect.zero).dx; }); switch (textDirection) { case TextDirection.ltr: expect(result[length], painter.width); case TextDirection.rtl: expect(result[0], painter.width); } painter.dispose(); return result; } void main() { group('caret', () { test('TextPainter caret test', () { final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr; String text = 'A'; checkCaretOffsetsLtr(text); painter.text = TextSpan(text: text); painter.layout(); Offset caretOffset = painter.getOffsetForCaret( const ui.TextPosition(offset: 0), ui.Rect.zero, ); expect(caretOffset.dx, 0); caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: text.length), ui.Rect.zero); expect(caretOffset.dx, painter.width); // Check that getOffsetForCaret handles a character that is encoded as a // surrogate pair. text = 'A\u{1F600}'; checkCaretOffsetsLtr(text); painter.text = TextSpan(text: text); painter.layout(); caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: text.length), ui.Rect.zero); expect(caretOffset.dx, painter.width); painter.dispose(); }); test('TextPainter caret test with WidgetSpan', () { // Regression test for https://github.com/flutter/flutter/issues/98458. final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr; painter.text = const TextSpan(children: <InlineSpan>[ TextSpan(text: 'before'), WidgetSpan(child: Text('widget')), TextSpan(text: 'after'), ]); painter.setPlaceholderDimensions(const <PlaceholderDimensions>[ PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), ]); painter.layout(); final Offset caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: painter.text!.toPlainText().length), ui.Rect.zero); expect(caretOffset.dx, painter.width); painter.dispose(); }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 test('TextPainter null text test', () { final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr; List<TextSpan> children = <TextSpan>[const TextSpan(text: 'B'), const TextSpan(text: 'C')]; painter.text = TextSpan(children: children); painter.layout(); Offset caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 0), ui.Rect.zero); expect(caretOffset.dx, 0); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 1), ui.Rect.zero); expect(caretOffset.dx, painter.width / 2); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 2), ui.Rect.zero); expect(caretOffset.dx, painter.width); children = <TextSpan>[]; painter.text = TextSpan(children: children); painter.layout(); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 0), ui.Rect.zero); expect(caretOffset.dx, 0); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 1), ui.Rect.zero); expect(caretOffset.dx, 0); painter.dispose(); }); test('TextPainter caret emoji test', () { final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr; // Format: '👩‍<zwj>👩‍<zwj>👦👩‍<zwj>👩‍<zwj>👧‍<zwj>👧👏<modifier>' // One three-person family, one four-person family, one clapping hands (medium skin tone). const String text = '👩‍👩‍👦👩‍👩‍👧‍👧👏🏽'; checkCaretOffsetsLtr(text); painter.text = const TextSpan(text: text); painter.layout(maxWidth: 10000); expect(text.length, 23); Offset caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 0), ui.Rect.zero); expect(caretOffset.dx, 0); // 👩‍ caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: text.length), ui.Rect.zero); expect(caretOffset.dx, painter.width); // Two UTF-16 codepoints per emoji, one codepoint per zwj caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 1), ui.Rect.zero); expect(caretOffset.dx, 42); // 👩‍ caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 2), ui.Rect.zero); expect(caretOffset.dx, 42); // <zwj> caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 3), ui.Rect.zero); expect(caretOffset.dx, 42); // 👩‍ caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 4), ui.Rect.zero); expect(caretOffset.dx, 42); // 👩‍ caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 5), ui.Rect.zero); expect(caretOffset.dx, 42); // <zwj> caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 6), ui.Rect.zero); expect(caretOffset.dx, 42); // 👦 caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 7), ui.Rect.zero); expect(caretOffset.dx, 42); // 👦 caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 8), ui.Rect.zero); expect(caretOffset.dx, 42); // 👩‍ caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 9), ui.Rect.zero); expect(caretOffset.dx, 98); // 👩‍ caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 10), ui.Rect.zero); expect(caretOffset.dx, 98); // <zwj> caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 11), ui.Rect.zero); expect(caretOffset.dx, 98); // 👩‍ caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 12), ui.Rect.zero); expect(caretOffset.dx, 98); // 👩‍ caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 13), ui.Rect.zero); expect(caretOffset.dx, 98); // <zwj> caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 14), ui.Rect.zero); expect(caretOffset.dx, 98); // 👧‍ caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 15), ui.Rect.zero); expect(caretOffset.dx, 98); // 👧‍ caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 16), ui.Rect.zero); expect(caretOffset.dx, 98); // <zwj> caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 17), ui.Rect.zero); expect(caretOffset.dx, 98); // 👧 caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 18), ui.Rect.zero); expect(caretOffset.dx, 98); // 👧 caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 19), ui.Rect.zero); expect(caretOffset.dx, 98); // 👏 caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 20), ui.Rect.zero); expect(caretOffset.dx, 126); // 👏 caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 21), ui.Rect.zero); expect(caretOffset.dx, 126); // <medium skin tone modifier> caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 22), ui.Rect.zero); expect(caretOffset.dx, 126); // <medium skin tone modifier> caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 23), ui.Rect.zero); expect(caretOffset.dx, 126); // end of string painter.dispose(); }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 test('TextPainter caret emoji tests: single, long emoji', () { // Regression test for https://github.com/flutter/flutter/issues/50563 checkCaretOffsetsLtr('👩‍🚀'); checkCaretOffsetsLtr('👩‍❤️‍💋‍👩'); checkCaretOffsetsLtr('👨‍👩‍👦‍👦'); checkCaretOffsetsLtr('👨🏾‍🤝‍👨🏻'); checkCaretOffsetsLtr('👨‍👦'); checkCaretOffsetsLtr('👩‍👦'); checkCaretOffsetsLtr('🏌🏿‍♀️'); checkCaretOffsetsLtr('🏊‍♀️'); checkCaretOffsetsLtr('🏄🏻‍♂️'); // These actually worked even before #50563 was fixed (because // their lengths in code units are powers of 2, namely 4 and 8). checkCaretOffsetsLtr('🇺🇳'); checkCaretOffsetsLtr('👩‍❤️‍👨'); }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 test('TextPainter caret emoji test: letters, then 1 emoji of 5 code units', () { // Regression test for https://github.com/flutter/flutter/issues/50563 checkCaretOffsetsLtr('a👩‍🚀'); checkCaretOffsetsLtr('ab👩‍🚀'); checkCaretOffsetsLtr('abc👩‍🚀'); checkCaretOffsetsLtr('abcd👩‍🚀'); }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 test('TextPainter caret zalgo test', () { // Regression test for https://github.com/flutter/flutter/issues/98516 checkCaretOffsetsLtr('Z͉̳̺ͥͬ̾a̴͕̲̒̒͌̋ͪl̨͎̰̘͉̟ͤ̀̈̚͜g͕͔̤͖̟̒͝ͅo̵̡̡̼͚̐ͯ̅ͪ̆ͣ̚'); }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 test('TextPainter caret Devanagari test', () { // Regression test for https://github.com/flutter/flutter/issues/118403 checkCaretOffsetsLtrFromPieces( <String>['प्रा', 'प्त', ' ', 'व', 'र्ण', 'न', ' ', 'प्र', 'व्रु', 'ति']); }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 test('TextPainter caret Devanagari test, full strength', () { // Regression test for https://github.com/flutter/flutter/issues/118403 checkCaretOffsetsLtr('प्राप्त वर्णन प्रव्रुति'); }, skip: true); // https://github.com/flutter/flutter/issues/122478 test('TextPainter caret emoji test LTR: letters next to emoji, as separate TextBoxes', () { // Regression test for https://github.com/flutter/flutter/issues/122477 // The trigger for this bug was to have SkParagraph report separate // TextBoxes for the emoji and for the characters next to it. // In normal usage on a real device, this can happen by simply typing // letters and then an emoji, presumably because they get different fonts. // In these tests, our single test font covers both letters and emoji, // so we provoke the same effect by adding styles. expect(caretOffsetsForTextSpan( TextDirection.ltr, const TextSpan(children: <TextSpan>[ TextSpan(text: '👩‍🚀', style: TextStyle()), TextSpan(text: ' words', style: TextStyle(fontWeight: FontWeight.bold)), ])), <double>[0, 28, 28, 28, 28, 28, 42, 56, 70, 84, 98, 112]); expect(caretOffsetsForTextSpan( TextDirection.ltr, const TextSpan(children: <TextSpan>[ TextSpan(text: 'words ', style: TextStyle(fontWeight: FontWeight.bold)), TextSpan(text: '👩‍🚀', style: TextStyle()), ])), <double>[0, 14, 28, 42, 56, 70, 84, 112, 112, 112, 112, 112]); }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 test('TextPainter caret emoji test RTL: letters next to emoji, as separate TextBoxes', () { // Regression test for https://github.com/flutter/flutter/issues/122477 expect(caretOffsetsForTextSpan( TextDirection.rtl, const TextSpan(children: <TextSpan>[ TextSpan(text: '👩‍🚀', style: TextStyle()), TextSpan(text: ' מילים', style: TextStyle(fontWeight: FontWeight.bold)), ])), <double>[112, 84, 84, 84, 84, 84, 70, 56, 42, 28, 14, 0]); expect(caretOffsetsForTextSpan( TextDirection.rtl, const TextSpan(children: <TextSpan>[ TextSpan(text: 'מילים ', style: TextStyle(fontWeight: FontWeight.bold)), TextSpan(text: '👩‍🚀', style: TextStyle()), ])), <double>[112, 98, 84, 70, 56, 42, 28, 0, 0, 0, 0, 0]); }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 test('TextPainter caret center space test', () { final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr; const String text = 'test text with space at end '; painter.text = const TextSpan(text: text); painter.textAlign = TextAlign.center; painter.layout(); Offset caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 0), ui.Rect.zero); expect(caretOffset.dx, 21); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: text.length), ui.Rect.zero); // The end of the line is 441, but the width is only 420, so the cursor is // stopped there without overflowing. expect(caretOffset.dx, painter.width); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 1), ui.Rect.zero); expect(caretOffset.dx, 35); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 2), ui.Rect.zero); expect(caretOffset.dx, 49); painter.dispose(); }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 test('TextPainter caret height and line height', () { final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr ..strutStyle = const StrutStyle(fontSize: 50.0); const String text = 'A'; painter.text = const TextSpan(text: text, style: TextStyle(height: 1.0)); painter.layout(); final double caretHeight = painter.getFullHeightForCaret( const ui.TextPosition(offset: 0), ui.Rect.zero, )!; expect(caretHeight, 50.0); painter.dispose(); }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 test('upstream downstream makes no difference in the same line within the same bidi run', () { final TextPainter painter = TextPainter(textDirection: TextDirection.ltr) ..text = const TextSpan(text: 'aa') ..layout(); final Rect largeRect = Offset.zero & const Size.square(5); expect( painter.getOffsetForCaret(const TextPosition(offset: 1), largeRect), painter.getOffsetForCaret(const TextPosition(offset: 1, affinity: TextAffinity.upstream), largeRect), ); }); test('trailing newlines', () { const double fontSize = 14.0; final TextPainter painter = TextPainter(); final Rect largeRect = Offset.zero & const Size.square(5); String text = 'a '; painter ..text = TextSpan(text: text) ..textDirection = TextDirection.ltr ..layout(minWidth: 1000.0, maxWidth: 1000.0); expect( painter.getOffsetForCaret(TextPosition(offset: text.length), largeRect).dx, text.length * fontSize, ); text = 'ل '; painter ..text = TextSpan(text: text) ..textDirection = TextDirection.rtl ..layout(minWidth: 1000.0, maxWidth: 1000.0); expect( painter.getOffsetForCaret(TextPosition(offset: text.length), largeRect).dx, 1000 - text.length * fontSize - largeRect.width, ); }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 test('End of text caret when the text ends with +1 bidi level', () { const double fontSize = 14.0; final TextPainter painter = TextPainter(); final Rect largeRect = Offset.zero & const Size.square(5); const String text = 'aل'; painter ..text = const TextSpan(text: text) ..textDirection = TextDirection.ltr ..layout(minWidth: 1000.0, maxWidth: 1000.0); expect( painter.getOffsetForCaret(const TextPosition(offset: 0), largeRect).dx, 0.0, ); expect( painter.getOffsetForCaret(const TextPosition(offset: 1), largeRect).dx, fontSize * 2 - largeRect.width, ); expect( painter.getOffsetForCaret(const TextPosition(offset: 2), largeRect).dx, fontSize * 2, ); }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 test('handles newlines properly', () { final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr; const double SIZE_OF_A = 14.0; // square size of "a" character String text = 'aaa'; painter.text = TextSpan(text: text); painter.layout(); // getOffsetForCaret in a plain one-line string is the same for either affinity. int offset = 0; painter.text = TextSpan(text: text); painter.layout(); Offset caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, SIZE_OF_A * offset); expect(caretOffset.dy, 0.0); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, SIZE_OF_A * offset); expect(caretOffset.dy, 0.0); offset = 1; caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, SIZE_OF_A * offset); expect(caretOffset.dy, 0.0); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, SIZE_OF_A * offset); expect(caretOffset.dy, 0.0); offset = 2; caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, SIZE_OF_A * offset); expect(caretOffset.dy, 0.0); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, SIZE_OF_A * offset); expect(caretOffset.dy, 0.0); offset = 3; caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, SIZE_OF_A * offset); expect(caretOffset.dy, 0.0); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, SIZE_OF_A * offset); expect(caretOffset.dy, 0.0); // For explicit newlines, getOffsetForCaret places the caret at the location // indicated by offset regardless of affinity. text = '\n\n'; painter.text = TextSpan(text: text); painter.layout(); offset = 0; caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, 0.0); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, 0.0); offset = 1; caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A); offset = 2; caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A * 2); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A * 2); // getOffsetForCaret in an unwrapped string with explicit newlines is the // same for either affinity. text = '\naaa'; painter.text = TextSpan(text: text); painter.layout(); offset = 0; caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, 0.0); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, 0.0); offset = 1; caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A); // When text wraps on its own, getOffsetForCaret disambiguates between the // end of one line and start of next using affinity. text = 'aaaaaaaa'; // Just enough to wrap one character down to second line painter.text = TextSpan(text: text); painter.layout(maxWidth: 100); // SIZE_OF_A * text.length > 100, so it wraps caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: text.length - 1), ui.Rect.zero, ); // When affinity is downstream, cursor is at beginning of second line expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: text.length - 1, affinity: ui.TextAffinity.upstream), ui.Rect.zero, ); // When affinity is upstream, cursor is at end of first line expect(caretOffset.dx, 98.0); expect(caretOffset.dy, 0.0); // When given a string with a newline at the end, getOffsetForCaret puts // the cursor at the start of the next line regardless of affinity text = 'aaa\n'; painter.text = TextSpan(text: text); painter.layout(); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: text.length), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A); offset = text.length; caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A); // Given a one-line right aligned string, positioning the cursor at offset 0 // means that it appears at the "end" of the string, after the character // that was typed first, at x=0. painter.textAlign = TextAlign.right; text = 'aaa'; painter.text = TextSpan(text: text); painter.layout(); offset = 0; caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, 0.0); painter.textAlign = TextAlign.left; // When given an offset after a newline in the middle of a string, // getOffsetForCaret returns the start of the next line regardless of // affinity. text = 'aaa\naaa'; painter.text = TextSpan(text: text); painter.layout(); offset = 4; caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A); // When given a string with multiple trailing newlines, places the caret // in the position given by offset regardless of affinity. text = 'aaa\n\n\n'; offset = 3; caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, SIZE_OF_A * 3); expect(caretOffset.dy, 0.0); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, SIZE_OF_A * 3); expect(caretOffset.dy, 0.0); offset = 4; painter.text = TextSpan(text: text); painter.layout(); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A); offset = 5; caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A * 2); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A * 2); offset = 6; caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A * 3); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A * 3); // When given a string with multiple leading newlines, places the caret in // the position given by offset regardless of affinity. text = '\n\n\naaa'; offset = 3; painter.text = TextSpan(text: text); painter.layout(); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A * 3); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A * 3); offset = 2; caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A * 2); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A * 2); offset = 1; caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy,SIZE_OF_A); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, SIZE_OF_A); offset = 0; caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, 0.0); caretOffset = painter.getOffsetForCaret( ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), ui.Rect.zero, ); expect(caretOffset.dx, 0.0); expect(caretOffset.dy, 0.0); painter.dispose(); }); }); test('TextPainter error test', () { final TextPainter painter = TextPainter(textDirection: TextDirection.ltr); expect( () => painter.paint(MockCanvas(), Offset.zero), throwsA(isA<StateError>().having( (StateError error) => error.message, 'message', contains('TextPainter.paint called when text geometry was not yet calculated'), )), ); painter.dispose(); }); test('TextPainter requires textDirection', () { final TextPainter painter1 = TextPainter(text: const TextSpan(text: '')); expect(painter1.layout, throwsStateError); final TextPainter painter2 = TextPainter(text: const TextSpan(text: ''), textDirection: TextDirection.rtl); expect(painter2.layout, isNot(throwsStateError)); }); test('TextPainter size test', () { final TextPainter painter = TextPainter( text: const TextSpan( text: 'X', style: TextStyle(inherit: false, fontSize: 123.0), ), textDirection: TextDirection.ltr, ); painter.layout(); expect(painter.size, const Size(123.0, 123.0)); painter.dispose(); }); test('TextPainter textScaler test', () { final TextPainter painter = TextPainter( text: const TextSpan( text: 'X', style: TextStyle(inherit: false, fontSize: 10.0), ), textDirection: TextDirection.ltr, textScaler: const TextScaler.linear(2.0), ); painter.layout(); expect(painter.size, const Size(20.0, 20.0)); painter.dispose(); }); test('TextPainter textScaler null style test', () { final TextPainter painter = TextPainter( text: const TextSpan( text: 'X', ), textDirection: TextDirection.ltr, textScaler: const TextScaler.linear(2.0), ); painter.layout(); expect(painter.size, const Size(28.0, 28.0)); painter.dispose(); }); test('TextPainter default text height is 14 pixels', () { final TextPainter painter = TextPainter( text: const TextSpan(text: 'x'), textDirection: TextDirection.ltr, ); painter.layout(); expect(painter.preferredLineHeight, 14.0); expect(painter.size, const Size(14.0, 14.0)); painter.dispose(); }); test('TextPainter sets paragraph size from root', () { final TextPainter painter = TextPainter( text: const TextSpan(text: 'x', style: TextStyle(fontSize: 100.0)), textDirection: TextDirection.ltr, ); painter.layout(); expect(painter.preferredLineHeight, 100.0); expect(painter.size, const Size(100.0, 100.0)); painter.dispose(); }); test('TextPainter intrinsic dimensions', () { const TextStyle style = TextStyle( inherit: false, fontSize: 10.0, ); TextPainter painter; painter = TextPainter( text: const TextSpan( text: 'X X X', style: style, ), textDirection: TextDirection.ltr, ); painter.layout(); expect(painter.size, const Size(50.0, 10.0)); expect(painter.minIntrinsicWidth, 10.0); expect(painter.maxIntrinsicWidth, 50.0); painter.dispose(); painter = TextPainter( text: const TextSpan( text: 'X X X', style: style, ), textDirection: TextDirection.ltr, ellipsis: 'e', ); painter.layout(); expect(painter.size, const Size(50.0, 10.0)); expect(painter.minIntrinsicWidth, 50.0); expect(painter.maxIntrinsicWidth, 50.0); painter.dispose(); painter = TextPainter( text: const TextSpan( text: 'X X XXXX', style: style, ), textDirection: TextDirection.ltr, maxLines: 2, ); painter.layout(); expect(painter.size, const Size(80.0, 10.0)); expect(painter.minIntrinsicWidth, 40.0); expect(painter.maxIntrinsicWidth, 80.0); painter.dispose(); painter = TextPainter( text: const TextSpan( text: 'X X XXXX XX', style: style, ), textDirection: TextDirection.ltr, maxLines: 2, ); painter.layout(); expect(painter.size, const Size(110.0, 10.0)); expect(painter.minIntrinsicWidth, 70.0); expect(painter.maxIntrinsicWidth, 110.0); painter.dispose(); painter = TextPainter( text: const TextSpan( text: 'XXXXXXXX XXXX XX X', style: style, ), textDirection: TextDirection.ltr, maxLines: 2, ); painter.layout(); expect(painter.size, const Size(180.0, 10.0)); expect(painter.minIntrinsicWidth, 90.0); expect(painter.maxIntrinsicWidth, 180.0); painter.dispose(); painter = TextPainter( text: const TextSpan( text: 'X XX XXXX XXXXXXXX', style: style, ), textDirection: TextDirection.ltr, maxLines: 2, ); painter.layout(); expect(painter.size, const Size(180.0, 10.0)); expect(painter.minIntrinsicWidth, 90.0); expect(painter.maxIntrinsicWidth, 180.0); painter.dispose(); }, skip: true); // https://github.com/flutter/flutter/issues/13512 test('TextPainter widget span', () { final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr; const String text = 'test'; painter.text = const TextSpan( text: text, children: <InlineSpan>[ WidgetSpan(child: SizedBox(width: 50, height: 30)), TextSpan(text: text), WidgetSpan(child: SizedBox(width: 50, height: 30)), WidgetSpan(child: SizedBox(width: 50, height: 30)), TextSpan(text: text), WidgetSpan(child: SizedBox(width: 50, height: 30)), WidgetSpan(child: SizedBox(width: 50, height: 30)), WidgetSpan(child: SizedBox(width: 50, height: 30)), WidgetSpan(child: SizedBox(width: 50, height: 30)), WidgetSpan(child: SizedBox(width: 50, height: 30)), WidgetSpan(child: SizedBox(width: 50, height: 30)), WidgetSpan(child: SizedBox(width: 50, height: 30)), WidgetSpan(child: SizedBox(width: 50, height: 30)), WidgetSpan(child: SizedBox(width: 50, height: 30)), WidgetSpan(child: SizedBox(width: 50, height: 30)), WidgetSpan(child: SizedBox(width: 50, height: 30)), ], ); // We provide dimensions for the widgets painter.setPlaceholderDimensions(const <PlaceholderDimensions>[ PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(51, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), ]); painter.layout(maxWidth: 500); // Now, each of the WidgetSpans will have their own placeholder 'hole'. Offset caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 1), ui.Rect.zero); expect(caretOffset.dx, 14); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 4), ui.Rect.zero); expect(caretOffset.dx, 56); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 5), ui.Rect.zero); expect(caretOffset.dx, 106); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 6), ui.Rect.zero); expect(caretOffset.dx, 120); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 10), ui.Rect.zero); expect(caretOffset.dx, 212); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 11), ui.Rect.zero); expect(caretOffset.dx, 262); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 12), ui.Rect.zero); expect(caretOffset.dx, 276); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 13), ui.Rect.zero); expect(caretOffset.dx, 290); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 14), ui.Rect.zero); expect(caretOffset.dx, 304); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 15), ui.Rect.zero); expect(caretOffset.dx, 318); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 16), ui.Rect.zero); expect(caretOffset.dx, 368); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 17), ui.Rect.zero); expect(caretOffset.dx, 418); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 18), ui.Rect.zero); expect(caretOffset.dx, 0); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 19), ui.Rect.zero); expect(caretOffset.dx, 50); caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 23), ui.Rect.zero); expect(caretOffset.dx, 250); expect(painter.inlinePlaceholderBoxes!.length, 14); expect(painter.inlinePlaceholderBoxes![0], const TextBox.fromLTRBD(56, 0, 106, 30, TextDirection.ltr)); expect(painter.inlinePlaceholderBoxes![2], const TextBox.fromLTRBD(212, 0, 262, 30, TextDirection.ltr)); expect(painter.inlinePlaceholderBoxes![3], const TextBox.fromLTRBD(318, 0, 368, 30, TextDirection.ltr)); expect(painter.inlinePlaceholderBoxes![4], const TextBox.fromLTRBD(368, 0, 418, 30, TextDirection.ltr)); expect(painter.inlinePlaceholderBoxes![5], const TextBox.fromLTRBD(418, 0, 468, 30, TextDirection.ltr)); // line should break here expect(painter.inlinePlaceholderBoxes![6], const TextBox.fromLTRBD(0, 30, 50, 60, TextDirection.ltr)); expect(painter.inlinePlaceholderBoxes![7], const TextBox.fromLTRBD(50, 30, 100, 60, TextDirection.ltr)); expect(painter.inlinePlaceholderBoxes![10], const TextBox.fromLTRBD(200, 30, 250, 60, TextDirection.ltr)); expect(painter.inlinePlaceholderBoxes![11], const TextBox.fromLTRBD(250, 30, 300, 60, TextDirection.ltr)); expect(painter.inlinePlaceholderBoxes![12], const TextBox.fromLTRBD(300, 30, 351, 60, TextDirection.ltr)); expect(painter.inlinePlaceholderBoxes![13], const TextBox.fromLTRBD(351, 30, 401, 60, TextDirection.ltr)); painter.dispose(); }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/87540 // Null values are valid. See https://github.com/flutter/flutter/pull/48346#issuecomment-584839221 test('TextPainter set TextHeightBehavior null test', () { final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr; painter.textHeightBehavior = const TextHeightBehavior(); painter.textHeightBehavior = null; painter.dispose(); }); test('TextPainter line metrics', () { final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr; const String text = 'test1\nhello line two really long for soft break\nfinal line 4'; painter.text = const TextSpan( text: text, ); painter.layout(maxWidth: 300); expect(painter.text, const TextSpan(text: text)); expect(painter.preferredLineHeight, 14); final List<ui.LineMetrics> lines = painter.computeLineMetrics(); expect(lines.length, 4); expect(lines[0].hardBreak, true); expect(lines[1].hardBreak, false); expect(lines[2].hardBreak, true); expect(lines[3].hardBreak, true); expect(lines[0].ascent, 10.5); expect(lines[1].ascent, 10.5); expect(lines[2].ascent, 10.5); expect(lines[3].ascent, 10.5); expect(lines[0].descent, 3.5); expect(lines[1].descent, 3.5); expect(lines[2].descent, 3.5); expect(lines[3].descent, 3.5); expect(lines[0].unscaledAscent, 10.5); expect(lines[1].unscaledAscent, 10.5); expect(lines[2].unscaledAscent, 10.5); expect(lines[3].unscaledAscent, 10.5); expect(lines[0].baseline, 10.5); expect(lines[1].baseline, 24.5); expect(lines[2].baseline, 38.5); expect(lines[3].baseline, 52.5); expect(lines[0].height, 14); expect(lines[1].height, 14); expect(lines[2].height, 14); expect(lines[3].height, 14); expect(lines[0].width, 70); expect(lines[1].width, 294); expect(lines[2].width, 266); expect(lines[3].width, 168); expect(lines[0].left, 0); expect(lines[1].left, 0); expect(lines[2].left, 0); expect(lines[3].left, 0); expect(lines[0].lineNumber, 0); expect(lines[1].lineNumber, 1); expect(lines[2].lineNumber, 2); expect(lines[3].lineNumber, 3); painter.dispose(); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/122066 group('TextPainter line-height', () { test('half-leading', () { const TextStyle style = TextStyle( height: 20, fontSize: 1, leadingDistribution: TextLeadingDistribution.even, ); final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr ..text = const TextSpan(text: 'A', style: style) ..layout(); final Rect glyphBox = painter.getBoxesForSelection( const TextSelection(baseOffset: 0, extentOffset: 1), ).first.toRect(); final RelativeRect insets = RelativeRect.fromSize(glyphBox, painter.size); // The glyph box is centered. expect(insets.top, insets.bottom); // The glyph box is exactly 1 logical pixel high. expect(insets.top, (20 - 1) / 2); painter.dispose(); }); test('half-leading with small height', () { const TextStyle style = TextStyle( height: 0.1, fontSize: 10, leadingDistribution: TextLeadingDistribution.even, ); final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr ..text = const TextSpan(text: 'A', style: style) ..layout(); final Rect glyphBox = painter.getBoxesForSelection( const TextSelection(baseOffset: 0, extentOffset: 1), ).first.toRect(); final RelativeRect insets = RelativeRect.fromSize(glyphBox, painter.size); // The glyph box is still centered. expect(insets.top, insets.bottom); // The glyph box is exactly 10 logical pixel high (the height multiplier // does not scale the glyph). Negative leading. expect(insets.top, (1 - 10) / 2); painter.dispose(); }); test('half-leading with leading trim', () { const TextStyle style = TextStyle( height: 0.1, fontSize: 10, leadingDistribution: TextLeadingDistribution.even, ); final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr ..text = const TextSpan(text: 'A', style: style) ..textHeightBehavior = const TextHeightBehavior( applyHeightToFirstAscent: false, applyHeightToLastDescent: false, ) ..layout(); final Rect glyphBox = painter.getBoxesForSelection( const TextSelection(baseOffset: 0, extentOffset: 1), ).first.toRect(); expect(painter.size, glyphBox.size); // The glyph box is still centered. expect(glyphBox.topLeft, Offset.zero); painter.dispose(); }); test('TextLeadingDistribution falls back to paragraph style', () { const TextStyle style = TextStyle(height: 20, fontSize: 1); final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr ..text = const TextSpan(text: 'A', style: style) ..textHeightBehavior = const TextHeightBehavior( leadingDistribution: TextLeadingDistribution.even, ) ..layout(); final Rect glyphBox = painter.getBoxesForSelection( const TextSelection(baseOffset: 0, extentOffset: 1), ).first.toRect(); // Still uses half-leading. final RelativeRect insets = RelativeRect.fromSize(glyphBox, painter.size); expect(insets.top, insets.bottom); expect(insets.top, (20 - 1) / 2); painter.dispose(); }); test('TextLeadingDistribution does nothing if height multiplier is null', () { const TextStyle style = TextStyle(fontSize: 1); final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr ..text = const TextSpan(text: 'A', style: style) ..textHeightBehavior = const TextHeightBehavior( leadingDistribution: TextLeadingDistribution.even, ) ..layout(); final Rect glyphBox = painter.getBoxesForSelection( const TextSelection(baseOffset: 0, extentOffset: 1), ).first.toRect(); painter.textHeightBehavior = const TextHeightBehavior(); painter.layout(); final Rect newGlyphBox = painter.getBoxesForSelection( const TextSelection(baseOffset: 0, extentOffset: 1), ).first.toRect(); expect(glyphBox, newGlyphBox); painter.dispose(); }); }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/87543 test('TextPainter handles invalid UTF-16', () { FlutterErrorDetails? error; FlutterError.onError = (FlutterErrorDetails details) { error = details; }; final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr; const String text = 'Hello\uD83DWorld'; const double fontSize = 20.0; painter.text = const TextSpan(text: text, style: TextStyle(fontSize: fontSize)); painter.layout(); // The layout should include one replacement character. expect(painter.width, equals(fontSize)); expect(error!.exception, isNotNull); expect(error!.silent, isTrue); painter.dispose(); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/87544 test('Diacritic', () { final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr; // Two letters followed by a diacritic const String text = 'ฟห้'; painter.text = const TextSpan(text: text); painter.layout(); final ui.Offset caretOffset = painter.getOffsetForCaret( const ui.TextPosition( offset: text.length, affinity: TextAffinity.upstream), ui.Rect.zero); expect(caretOffset.dx, painter.width); painter.dispose(); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/87545 test('TextPainter line metrics update after layout', () { final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr; const String text = 'word1 word2 word3'; painter.text = const TextSpan( text: text, ); painter.layout(maxWidth: 80); List<ui.LineMetrics> lines = painter.computeLineMetrics(); expect(lines.length, 3); painter.layout(maxWidth: 1000); lines = painter.computeLineMetrics(); expect(lines.length, 1); painter.dispose(); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/62819 test('TextPainter throws with stack trace when accessing text layout', () { final TextPainter painter = TextPainter() ..text = const TextSpan(text: 'TEXT') ..textDirection = TextDirection.ltr; expect( () => painter.getPositionForOffset(Offset.zero), throwsA(isA<FlutterError>().having( (FlutterError error) => error.message, 'message', contains('The TextPainter has never been laid out.'), )), ); expect( () { painter.layout(); painter.getPositionForOffset(Offset.zero); }, returnsNormally, ); expect( () { painter.markNeedsLayout(); painter.getPositionForOffset(Offset.zero); }, throwsA(isA<FlutterError>().having( (FlutterError error) => error.message, 'message', contains('The calls that first invalidated the text layout were:'), )), ); painter.dispose(); }); test('TextPainter requires layout after providing different placeholder dimensions', () { final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr; painter.text = const TextSpan(children: <InlineSpan>[ TextSpan(text: 'before'), WidgetSpan(child: Text('widget1')), WidgetSpan(child: Text('widget2')), WidgetSpan(child: Text('widget3')), TextSpan(text: 'after'), ]); painter.setPlaceholderDimensions(const <PlaceholderDimensions>[ PlaceholderDimensions(size: Size(30, 30), alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(40, 30), alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(50, 30), alignment: ui.PlaceholderAlignment.bottom), ]); painter.layout(); painter.setPlaceholderDimensions(const <PlaceholderDimensions>[ PlaceholderDimensions(size: Size(30, 30), alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(40, 20), alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(50, 30), alignment: ui.PlaceholderAlignment.bottom), ]); expect( () => painter.paint(MockCanvas(), Offset.zero), throwsA(isA<StateError>().having( (StateError error) => error.message, 'message', contains('TextPainter.paint called when text geometry was not yet calculated'), )), ); painter.dispose(); }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 test('TextPainter does not require layout after providing identical placeholder dimensions', () { final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr; painter.text = const TextSpan(children: <InlineSpan>[ TextSpan(text: 'before'), WidgetSpan(child: Text('widget1')), WidgetSpan(child: Text('widget2')), WidgetSpan(child: Text('widget3')), TextSpan(text: 'after'), ]); painter.setPlaceholderDimensions(const <PlaceholderDimensions>[ PlaceholderDimensions(size: Size(30, 30), alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(40, 30), alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(50, 30), alignment: ui.PlaceholderAlignment.bottom), ]); painter.layout(); painter.setPlaceholderDimensions(const <PlaceholderDimensions>[ PlaceholderDimensions(size: Size(30, 30), alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(40, 30), alignment: ui.PlaceholderAlignment.bottom), PlaceholderDimensions(size: Size(50, 30), alignment: ui.PlaceholderAlignment.bottom), ]); // In tests, paint() will throw an UnimplementedError due to missing drawParagraph method. expect( () => painter.paint(MockCanvas(), Offset.zero), isNot(throwsA(isA<StateError>().having( (StateError error) => error.message, 'message', contains('TextPainter.paint called when text geometry was not yet calculated'), ))), ); painter.dispose(); }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 test('TextPainter - debugDisposed', () { final TextPainter painter = TextPainter(); expect(painter.debugDisposed, false); painter.dispose(); expect(painter.debugDisposed, true); }); test('TextPainter - asserts if disposed more than once', () { final TextPainter painter = TextPainter()..dispose(); expect(painter.debugDisposed, isTrue); expect(painter.dispose, throwsAssertionError); }); test('TextPainter computeWidth', () { const InlineSpan text = TextSpan(text: 'foobar'); final TextPainter painter = TextPainter(text: text, textDirection: TextDirection.ltr); painter.layout(); expect(painter.width, TextPainter.computeWidth(text: text, textDirection: TextDirection.ltr)); painter.layout(minWidth: 500); expect(painter.width, TextPainter.computeWidth(text: text, textDirection: TextDirection.ltr, minWidth: 500)); painter.dispose(); }); test('TextPainter computeMaxIntrinsicWidth', () { const InlineSpan text = TextSpan(text: 'foobar'); final TextPainter painter = TextPainter(text: text, textDirection: TextDirection.ltr); painter.layout(); expect(painter.maxIntrinsicWidth, TextPainter.computeMaxIntrinsicWidth(text: text, textDirection: TextDirection.ltr)); painter.layout(minWidth: 500); expect(painter.maxIntrinsicWidth, TextPainter.computeMaxIntrinsicWidth(text: text, textDirection: TextDirection.ltr, minWidth: 500)); painter.dispose(); }); test('TextPainter.getWordBoundary works', (){ // Regression test for https://github.com/flutter/flutter/issues/93493 . const String testCluster = '👨‍👩‍👦👨‍👩‍👦👨‍👩‍👦'; // 8 * 3 final TextPainter textPainter = TextPainter( text: const TextSpan(text: testCluster), textDirection: TextDirection.ltr, ); textPainter.layout(); expect( textPainter.getWordBoundary(const TextPosition(offset: 8)), const TextRange(start: 8, end: 16), ); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/61017 test('TextHeightBehavior with strut on empty paragraph', () { // Regression test for https://github.com/flutter/flutter/issues/112123 const TextStyle style = TextStyle(height: 11, fontSize: 7); const TextSpan simple = TextSpan(text: 'x', style: style); const TextSpan emptyString = TextSpan(text: '', style: style); const TextSpan emptyParagraph = TextSpan(style: style); final TextPainter painter = TextPainter( textDirection: TextDirection.ltr, strutStyle: StrutStyle.fromTextStyle(style, forceStrutHeight: true), textHeightBehavior: const TextHeightBehavior(applyHeightToFirstAscent: false, applyHeightToLastDescent: false), ); painter.text = simple; painter.layout(); final double height = painter.height; for (final TextSpan span in <TextSpan>[simple, emptyString, emptyParagraph]) { painter.text = span; painter.layout(); expect(painter.height, height, reason: '$span is expected to have a height of $height'); expect(painter.preferredLineHeight, height, reason: '$span is expected to have a height of $height'); } }); test('TextPainter plainText getter', () { final TextPainter painter = TextPainter() ..textDirection = TextDirection.ltr; expect(painter.plainText, ''); painter.text = const TextSpan(children: <InlineSpan>[ TextSpan(text: 'before\n'), WidgetSpan(child: Text('widget')), TextSpan(text: 'after'), ]); expect(painter.plainText, 'before\n\uFFFCafter'); painter.setPlaceholderDimensions(const <PlaceholderDimensions>[ PlaceholderDimensions(size: Size(50, 30), alignment: ui.PlaceholderAlignment.bottom), ]); painter.layout(); expect(painter.plainText, 'before\n\uFFFCafter'); painter.text = const TextSpan(children: <InlineSpan>[ TextSpan(text: 'be\nfo\nre\n'), WidgetSpan(child: Text('widget')), TextSpan(text: 'af\nter'), ]); expect(painter.plainText, 'be\nfo\nre\n\uFFFCaf\nter'); painter.layout(); expect(painter.plainText, 'be\nfo\nre\n\uFFFCaf\nter'); painter.dispose(); }); test('TextPainter infinite width - centered', () { final TextPainter painter = TextPainter() ..textAlign = TextAlign.center ..textDirection = TextDirection.ltr; painter.text = const TextSpan(text: 'A', style: TextStyle(fontSize: 10)); MockCanvasWithDrawParagraph mockCanvas = MockCanvasWithDrawParagraph(); painter.layout(minWidth: double.infinity); expect(painter.width, double.infinity); expect(() => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), returnsNormally); expect(mockCanvas.centerX, isNull); painter.layout(); expect(painter.width, 10); expect(() => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), returnsNormally); expect(mockCanvas.centerX, 5); painter.layout(minWidth: 100); expect(painter.width, 100); expect(() => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), returnsNormally); expect(mockCanvas.centerX, 50); painter.dispose(); }); test('TextPainter infinite width - LTR justified', () { final TextPainter painter = TextPainter() ..textAlign = TextAlign.justify ..textDirection = TextDirection.ltr; painter.text = const TextSpan(text: 'A', style: TextStyle(fontSize: 10)); MockCanvasWithDrawParagraph mockCanvas = MockCanvasWithDrawParagraph(); painter.layout(minWidth: double.infinity); expect(painter.width, double.infinity); expect(() => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), returnsNormally); expect(mockCanvas.offsetX, 0); painter.layout(); expect(painter.width, 10); expect(() => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), returnsNormally); expect(mockCanvas.offsetX, 0); painter.layout(minWidth: 100); expect(painter.width, 100); expect(() => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), returnsNormally); expect(mockCanvas.offsetX, 0); painter.dispose(); }); test('LongestLine TextPainter properly relayout when maxWidth changes.', () { // Regression test for https://github.com/flutter/flutter/issues/142309. final TextPainter painter = TextPainter() ..textAlign = TextAlign.justify ..textWidthBasis = TextWidthBasis.longestLine ..textDirection = TextDirection.ltr ..text = TextSpan(text: 'A' * 100, style: const TextStyle(fontSize: 10)); painter.layout(maxWidth: 1000); expect(painter.width, 1000); painter.layout(maxWidth: 100); expect(painter.width, 100); painter.layout(maxWidth: 1000); expect(painter.width, 1000); }); test('TextPainter line breaking does not round to integers', () { const double fontSize = 1.25; const String text = '12345'; assert((fontSize * text.length).truncate() != fontSize * text.length); final TextPainter painter = TextPainter( textDirection: TextDirection.ltr, text: const TextSpan(text: text, style: TextStyle(fontSize: fontSize)), )..layout(maxWidth: text.length * fontSize); expect(painter.maxIntrinsicWidth, text.length * fontSize); switch (painter.computeLineMetrics()) { case [ui.LineMetrics(width: final double width)]: expect(width, text.length * fontSize); case final List<ui.LineMetrics> metrics: expect(metrics, hasLength(1)); } }, skip: kIsWeb && !isCanvasKit); // [intended] Browsers seem to always round font/glyph metrics. group('strut style', () { test('strut style applies when the span has no style', () { const StrutStyle strut = StrutStyle(height: 10, fontSize: 10); final TextPainter painter = TextPainter( textDirection: TextDirection.ltr, text: const TextSpan(), strutStyle: strut, )..layout(); expect(painter.height, 100); }); test('strut style leading is a fontSize multiplier', () { const StrutStyle strut = StrutStyle(height: 10, fontSize: 10, leading: 2); final TextPainter painter = TextPainter( textDirection: TextDirection.ltr, text: const TextSpan(), strutStyle: strut, )..layout(); expect(painter.height, 100 + 20); // Top leading + scaled ascent. expect(painter.computeDistanceToActualBaseline(TextBaseline.alphabetic), 10 + 10 * 7.5); }); test('strut no half leading + force strut height', () { const StrutStyle strut = StrutStyle(height: 10, fontSize: 10, forceStrutHeight: true); final TextPainter painter = TextPainter( textDirection: TextDirection.ltr, text: const TextSpan(text: 'A', style: TextStyle(fontSize: 20)), strutStyle: strut, )..layout(); expect(painter.height, 100); const double baseline = 75; expect( painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 1)), const <ui.TextBox>[TextBox.fromLTRBD(0, baseline - 15, 20, baseline + 5, TextDirection.ltr)], ); }); test('strut half leading + force strut height', () { const StrutStyle strut = StrutStyle(height: 10, fontSize: 10, forceStrutHeight: true, leadingDistribution: TextLeadingDistribution.even); final TextPainter painter = TextPainter( textDirection: TextDirection.ltr, text: const TextSpan(text: 'A', style: TextStyle(fontSize: 20)), strutStyle: strut, )..layout(); expect(painter.height, 100); const double baseline = 45 + 7.5; expect( painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 1)), const <ui.TextBox>[TextBox.fromLTRBD(0, baseline - 15, 20, baseline + 5, TextDirection.ltr)], ); }); test('force strut height applies to widget spans', () { const Size placeholderSize = Size(1000, 1000); const StrutStyle strut = StrutStyle(height: 10, fontSize: 10, forceStrutHeight: true); final TextPainter painter = TextPainter( textDirection: TextDirection.ltr, text: const WidgetSpan(child: SizedBox()), strutStyle: strut, ) ..setPlaceholderDimensions(const <PlaceholderDimensions>[PlaceholderDimensions(size: placeholderSize, alignment: PlaceholderAlignment.bottom)]) ..layout(); expect(painter.height, 100); }); }, skip: kIsWeb && !isCanvasKit); // [intended] strut spport for HTML renderer https://github.com/flutter/flutter/issues/32243. test('TextPainter dispatches memory events', () async { await expectLater( await memoryEvents(() => TextPainter().dispose(), TextPainter), areCreateAndDispose, ); }); } class MockCanvas extends Fake implements Canvas { } class MockCanvasWithDrawParagraph extends Fake implements Canvas { double? centerX; double? offsetX; @override void drawParagraph(ui.Paragraph paragraph, Offset offset) { offsetX = offset.dx; centerX = offset.dx + paragraph.width / 2; } }
flutter/packages/flutter/test/painting/text_painter_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/text_painter_test.dart", "repo_id": "flutter", "token_count": 26912 }
680
// 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 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'rendering_tester.dart'; void main() { MyTestRenderingFlutterBinding.ensureInitialized(); tearDown(() { final List<PipelineOwner> children = <PipelineOwner>[]; RendererBinding.instance.rootPipelineOwner.visitChildren((PipelineOwner child) { children.add(child); }); children.forEach(RendererBinding.instance.rootPipelineOwner.dropChild); }); test("BindingPipelineManifold notifies binding if render object managed by binding's PipelineOwner tree needs visual update", () { final PipelineOwner child = PipelineOwner(); RendererBinding.instance.rootPipelineOwner.adoptChild(child); final RenderObject renderObject = TestRenderObject(); child.rootNode = renderObject; renderObject.scheduleInitialLayout(); RendererBinding.instance.rootPipelineOwner.flushLayout(); MyTestRenderingFlutterBinding.instance.ensureVisualUpdateCount = 0; renderObject.markNeedsLayout(); expect(MyTestRenderingFlutterBinding.instance.ensureVisualUpdateCount, 1); }); test('Turning global semantics on/off creates semantics owners in PipelineOwner tree', () { final PipelineOwner child = PipelineOwner( onSemanticsUpdate: (_) { }, ); RendererBinding.instance.rootPipelineOwner.adoptChild(child); expect(child.semanticsOwner, isNull); expect(RendererBinding.instance.rootPipelineOwner.semanticsOwner, isNull); final SemanticsHandle handle = SemanticsBinding.instance.ensureSemantics(); expect(child.semanticsOwner, isNotNull); expect(RendererBinding.instance.rootPipelineOwner.semanticsOwner, isNotNull); handle.dispose(); expect(child.semanticsOwner, isNull); expect(RendererBinding.instance.rootPipelineOwner.semanticsOwner, isNull); }); } class MyTestRenderingFlutterBinding extends TestRenderingFlutterBinding { static MyTestRenderingFlutterBinding get instance => BindingBase.checkInstance(_instance); static MyTestRenderingFlutterBinding? _instance; static MyTestRenderingFlutterBinding ensureInitialized() { return _instance ?? MyTestRenderingFlutterBinding(); } @override void initInstances() { super.initInstances(); _instance = this; } int ensureVisualUpdateCount = 0; @override void ensureVisualUpdate() { super.ensureVisualUpdate(); ensureVisualUpdateCount++; } } class TestRenderObject extends RenderObject { @override void debugAssertDoesMeetConstraints() { } @override Rect get paintBounds => Rect.zero; @override void performLayout() { } @override void performResize() { } @override Rect get semanticBounds => Rect.zero; }
flutter/packages/flutter/test/rendering/binding_pipeline_manifold_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/binding_pipeline_manifold_test.dart", "repo_id": "flutter", "token_count": 926 }
681
// 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:ui' as ui show Image; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'rendering_tester.dart'; Future<void> main() async { TestRenderingFlutterBinding.ensureInitialized(); final ui.Image squareImage = await createTestImage(width: 10, height: 10); final ui.Image wideImage = await createTestImage(width: 20, height: 10); final ui.Image tallImage = await createTestImage(width: 10, height: 20); test('Image sizing', () { RenderImage image; image = RenderImage(image: squareImage); layout(image, constraints: const BoxConstraints( minWidth: 25.0, minHeight: 25.0, maxWidth: 100.0, maxHeight: 100.0, )); expect(image.size.width, equals(25.0)); expect(image.size.height, equals(25.0)); expect(image, hasAGoodToStringDeep); expect( image.toStringDeep(minLevel: DiagnosticLevel.info), equalsIgnoringHashCodes( 'RenderImage#00000 relayoutBoundary=up2 NEEDS-PAINT\n' ' parentData: <none> (can use size)\n' ' constraints: BoxConstraints(25.0<=w<=100.0, 25.0<=h<=100.0)\n' ' size: Size(25.0, 25.0)\n' ' image: $squareImage\n' ' alignment: Alignment.center\n' ' invertColors: false\n' ' filterQuality: low\n', ), ); image = RenderImage(image: wideImage); layout(image, constraints: const BoxConstraints( minWidth: 5.0, minHeight: 30.0, maxWidth: 100.0, maxHeight: 100.0, )); expect(image.size.width, equals(60.0)); expect(image.size.height, equals(30.0)); image = RenderImage(image: tallImage); layout(image, constraints: const BoxConstraints( minWidth: 50.0, minHeight: 5.0, maxWidth: 75.0, maxHeight: 75.0, )); expect(image.size.width, equals(50.0)); expect(image.size.height, equals(75.0)); image = RenderImage(image: wideImage); layout(image, constraints: const BoxConstraints( minWidth: 5.0, minHeight: 5.0, maxWidth: 100.0, maxHeight: 100.0, )); expect(image.size.width, equals(20.0)); expect(image.size.height, equals(10.0)); image = RenderImage(image: wideImage); layout(image, constraints: const BoxConstraints( minWidth: 5.0, minHeight: 5.0, maxWidth: 16.0, maxHeight: 16.0, )); expect(image.size.width, equals(16.0)); expect(image.size.height, equals(8.0)); image = RenderImage(image: tallImage); layout(image, constraints: const BoxConstraints( minWidth: 5.0, minHeight: 5.0, maxWidth: 16.0, maxHeight: 16.0, )); expect(image.size.width, equals(8.0)); expect(image.size.height, equals(16.0)); image = RenderImage(image: squareImage); layout(image, constraints: const BoxConstraints( minWidth: 4.0, minHeight: 4.0, maxWidth: 8.0, maxHeight: 8.0, )); expect(image.size.width, equals(8.0)); expect(image.size.height, equals(8.0)); image = RenderImage(image: wideImage); layout(image, constraints: const BoxConstraints( minWidth: 20.0, minHeight: 20.0, maxWidth: 30.0, maxHeight: 30.0, )); expect(image.size.width, equals(30.0)); expect(image.size.height, equals(20.0)); image = RenderImage(image: tallImage); layout(image, constraints: const BoxConstraints( minWidth: 20.0, minHeight: 20.0, maxWidth: 30.0, maxHeight: 30.0, )); expect(image.size.width, equals(20.0)); expect(image.size.height, equals(30.0)); }); test('Null image sizing', () { RenderImage image; image = RenderImage(); layout(image, constraints: const BoxConstraints( minWidth: 25.0, minHeight: 25.0, maxWidth: 100.0, maxHeight: 100.0, )); expect(image.size.width, equals(25.0)); expect(image.size.height, equals(25.0)); image = RenderImage(width: 50.0); layout(image, constraints: const BoxConstraints( minWidth: 25.0, minHeight: 25.0, maxWidth: 100.0, maxHeight: 100.0, )); expect(image.size.width, equals(50.0)); expect(image.size.height, equals(25.0)); image = RenderImage(height: 50.0); layout(image, constraints: const BoxConstraints( minWidth: 25.0, minHeight: 25.0, maxWidth: 100.0, maxHeight: 100.0, )); expect(image.size.width, equals(25.0)); expect(image.size.height, equals(50.0)); image = RenderImage(width: 100.0, height: 100.0); layout(image, constraints: const BoxConstraints( minWidth: 25.0, minHeight: 25.0, maxWidth: 75.0, maxHeight: 75.0, )); expect(image.size.width, equals(75.0)); expect(image.size.height, equals(75.0)); }); test('update image colorBlendMode', () { final RenderImage image = RenderImage(); expect(image.colorBlendMode, isNull); image.colorBlendMode = BlendMode.color; expect(image.colorBlendMode, BlendMode.color); }); test('RenderImage disposes its image', () async { final ui.Image image = await createTestImage(width: 10, height: 10, cache: false); expect(image.debugGetOpenHandleStackTraces()!.length, 1); final RenderImage renderImage = RenderImage(image: image.clone()); expect(image.debugGetOpenHandleStackTraces()!.length, 2); renderImage.image = image.clone(); expect(image.debugGetOpenHandleStackTraces()!.length, 2); renderImage.image = null; expect(image.debugGetOpenHandleStackTraces()!.length, 1); image.dispose(); expect(image.debugGetOpenHandleStackTraces()!.length, 0); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/87442 test('RenderImage does not dispose its image if setting the same image twice', () async { final ui.Image image = await createTestImage(width: 10, height: 10, cache: false); expect(image.debugGetOpenHandleStackTraces()!.length, 1); final RenderImage renderImage = RenderImage(image: image.clone()); expect(image.debugGetOpenHandleStackTraces()!.length, 2); // Testing short-circuit logic of setter. renderImage.image = renderImage.image; // ignore: no_self_assignments expect(image.debugGetOpenHandleStackTraces()!.length, 2); renderImage.image = null; expect(image.debugGetOpenHandleStackTraces()!.length, 1); image.dispose(); expect(image.debugGetOpenHandleStackTraces()!.length, 0); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/87442 test('Render image disposes its image when it is disposed', () async { final ui.Image image = await createTestImage(width: 10, height: 10, cache: false); expect(image.debugGetOpenHandleStackTraces()!.length, 1); final RenderImage renderImage = RenderImage(image: image.clone()); expect(image.debugGetOpenHandleStackTraces()!.length, 2); renderImage.dispose(); expect(image.debugGetOpenHandleStackTraces()!.length, 1); expect(renderImage.image, null); image.dispose(); expect(image.debugGetOpenHandleStackTraces()!.length, 0); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/87442 }
flutter/packages/flutter/test/rendering/image_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/image_test.dart", "repo_id": "flutter", "token_count": 2892 }
682
// 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 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'rendering_tester.dart'; void main() { TestRenderingFlutterBinding.ensureInitialized(); test('offstage', () { RenderBox child; bool painted = false; // incoming constraints are tight 800x600 final RenderBox root = RenderPositionedBox( child: RenderConstrainedBox( additionalConstraints: const BoxConstraints.tightFor(width: 800.0), child: RenderOffstage( child: RenderCustomPaint( painter: TestCallbackPainter( onPaint: () { painted = true; }, ), child: child = RenderConstrainedBox( additionalConstraints: const BoxConstraints.tightFor(height: 10.0, width: 10.0), ), ), ), ), ); expect(child.hasSize, isFalse); expect(painted, isFalse); layout(root, phase: EnginePhase.paint); expect(child.hasSize, isTrue); expect(painted, isFalse); expect(child.size, equals(const Size(800.0, 10.0))); }); }
flutter/packages/flutter/test/rendering/offstage_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/offstage_test.dart", "repo_id": "flutter", "token_count": 492 }
683
// 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 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('repaint boundary with constraint changes', (WidgetTester tester) async { // Regression test for as https://github.com/flutter/flutter/issues/39151. await tester.pumpWidget(const RelayoutBoundariesCrash()); tester.state<RelayoutBoundariesCrashState>(find.byType(RelayoutBoundariesCrash))._toggleMode(); await tester.pump(); }); } class RelayoutBoundariesCrash extends StatefulWidget { const RelayoutBoundariesCrash({super.key}); @override RelayoutBoundariesCrashState createState() => RelayoutBoundariesCrashState(); } class RelayoutBoundariesCrashState extends State<RelayoutBoundariesCrash> { bool _mode = true; void _toggleMode() { setState(() { _mode = !_mode; }); } @override Widget build(BuildContext context) { return Center( child: SizedBox( // when _mode is true, constraints are tight, otherwise constraints are loose width: !_mode ? 100.0 : null, height: !_mode ? 100.0 : null, child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { // Make the outer SizedBoxes relayout without making the Placeholders relayout. final double dimension = !_mode ? 10.0 : 20.0; return Column( children: <Widget>[ SizedBox( width: dimension, height: dimension, child: const Placeholder(), ), SizedBox( width: dimension, height: dimension, child: const Placeholder(), ), ], ); }, ), ), ); } }
flutter/packages/flutter/test/rendering/repaint_boundary_2_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/repaint_boundary_2_test.dart", "repo_id": "flutter", "token_count": 824 }
684
// 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 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'rendering_tester.dart'; RenderBox sizedBox(double width, double height) { return RenderConstrainedBox( additionalConstraints: BoxConstraints.tight(Size(width, height)), ); } void main() { TestRenderingFlutterBinding.ensureInitialized(); test('Table control test; tight', () { RenderTable table; layout(table = RenderTable(textDirection: TextDirection.ltr)); expect(table.size.width, equals(800.0)); expect(table.size.height, equals(600.0)); expect(table, hasAGoodToStringDeep); expect( table.toStringDeep(minLevel: DiagnosticLevel.info), equalsIgnoringHashCodes( 'RenderTable#00000 NEEDS-PAINT\n' ' │ parentData: <none>\n' ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' ' │ size: Size(800.0, 600.0)\n' ' │ default column width: FlexColumnWidth(1.0)\n' ' │ table size: 0×0\n' ' │ column offsets: unknown\n' ' │ row offsets: []\n' ' │\n' ' └─table is empty\n', ), ); }); test('Table control test; loose', () { RenderTable table; layout(RenderPositionedBox(child: table = RenderTable(textDirection: TextDirection.ltr))); expect(table.size, equals(Size.zero)); }); test('Table control test: constrained flex columns', () { final RenderTable table = RenderTable(textDirection: TextDirection.ltr); final List<RenderBox> children = List<RenderBox>.generate(6, (_) => RenderPositionedBox()); table.setFlatChildren(6, children); layout(table, constraints: const BoxConstraints.tightFor(width: 100.0)); const double expectedWidth = 100.0 / 6; for (final RenderBox child in children) { expect(child.size.width, moreOrLessEquals(expectedWidth)); } }); test('Table test: combinations', () { RenderTable table; layout(RenderPositionedBox(child: table = RenderTable( columns: 5, rows: 5, defaultColumnWidth: const IntrinsicColumnWidth(), textDirection: TextDirection.ltr, defaultVerticalAlignment: TableCellVerticalAlignment.baseline, textBaseline: TextBaseline.alphabetic, ))); expect(table.size, equals(Size.zero)); table.setChild(2, 4, sizedBox(100.0, 200.0)); pumpFrame(); expect(table.size, equals(const Size(100.0, 200.0))); table.setChild(0, 0, sizedBox(10.0, 30.0)); table.setChild(1, 0, sizedBox(20.0, 20.0)); table.setChild(2, 0, sizedBox(30.0, 10.0)); pumpFrame(); expect(table.size, equals(const Size(130.0, 230.0))); expect(table, hasAGoodToStringDeep); expect( table.toStringDeep(minLevel: DiagnosticLevel.info), equalsIgnoringHashCodes( 'RenderTable#00000 relayoutBoundary=up1 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE\n' ' │ parentData: offset=Offset(335.0, 185.0) (can use size)\n' ' │ constraints: BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0)\n' ' │ size: Size(130.0, 230.0)\n' ' │ default column width: IntrinsicColumnWidth(flex: null)\n' ' │ table size: 5×5\n' ' │ column offsets: 0.0, 10.0, 30.0, 130.0, 130.0\n' ' │ row offsets: 0.0, 30.0, 30.0, 30.0, 30.0, 230.0\n' ' │\n' ' ├─child (0, 0): RenderConstrainedBox#00000 relayoutBoundary=up2 NEEDS-PAINT\n' ' │ parentData: offset=Offset(0.0, 0.0); default vertical alignment\n' ' │ (can use size)\n' ' │ constraints: BoxConstraints(w=10.0, 0.0<=h<=Infinity)\n' ' │ size: Size(10.0, 30.0)\n' ' │ additionalConstraints: BoxConstraints(w=10.0, h=30.0)\n' ' │\n' ' ├─child (1, 0): RenderConstrainedBox#00000 relayoutBoundary=up2 NEEDS-PAINT\n' ' │ parentData: offset=Offset(10.0, 0.0); default vertical alignment\n' ' │ (can use size)\n' ' │ constraints: BoxConstraints(w=20.0, 0.0<=h<=Infinity)\n' ' │ size: Size(20.0, 20.0)\n' ' │ additionalConstraints: BoxConstraints(w=20.0, h=20.0)\n' ' │\n' ' ├─child (2, 0): RenderConstrainedBox#00000 relayoutBoundary=up2 NEEDS-PAINT\n' ' │ parentData: offset=Offset(30.0, 0.0); default vertical alignment\n' ' │ (can use size)\n' ' │ constraints: BoxConstraints(w=100.0, 0.0<=h<=Infinity)\n' ' │ size: Size(100.0, 10.0)\n' ' │ additionalConstraints: BoxConstraints(w=30.0, h=10.0)\n' ' │\n' ' ├─child (3, 0) is null\n' ' ├─child (4, 0) is null\n' ' ├─child (0, 1) is null\n' ' ├─child (1, 1) is null\n' ' ├─child (2, 1) is null\n' ' ├─child (3, 1) is null\n' ' ├─child (4, 1) is null\n' ' ├─child (0, 2) is null\n' ' ├─child (1, 2) is null\n' ' ├─child (2, 2) is null\n' ' ├─child (3, 2) is null\n' ' ├─child (4, 2) is null\n' ' ├─child (0, 3) is null\n' ' ├─child (1, 3) is null\n' ' ├─child (2, 3) is null\n' ' ├─child (3, 3) is null\n' ' ├─child (4, 3) is null\n' ' ├─child (0, 4) is null\n' ' ├─child (1, 4) is null\n' ' ├─child (2, 4): RenderConstrainedBox#00000 relayoutBoundary=up2 NEEDS-PAINT\n' ' │ parentData: offset=Offset(30.0, 30.0); default vertical alignment\n' ' │ (can use size)\n' ' │ constraints: BoxConstraints(w=100.0, 0.0<=h<=Infinity)\n' ' │ size: Size(100.0, 200.0)\n' ' │ additionalConstraints: BoxConstraints(w=100.0, h=200.0)\n' ' │\n' ' ├─child (3, 4) is null\n' ' └─child (4, 4) is null\n', ), ); }); test('Table test: removing cells', () { RenderTable table; RenderBox child; table = RenderTable( columns: 5, rows: 5, textDirection: TextDirection.ltr, ); table.setChild(4, 4, child = sizedBox(10.0, 10.0)); layout(table); expect(child.attached, isTrue); table.rows = 4; expect(child.attached, isFalse); }); test('Table test: replacing cells', () { RenderTable table; final RenderBox child1 = RenderPositionedBox(); final RenderBox child2 = RenderPositionedBox(); final RenderBox child3 = RenderPositionedBox(); table = RenderTable(textDirection: TextDirection.ltr); table.setFlatChildren(3, <RenderBox>[ child1, RenderPositionedBox(), child2, RenderPositionedBox(), child3, RenderPositionedBox(), ]); expect(table.rows, equals(2)); layout(table); table.setFlatChildren(3, <RenderBox>[ RenderPositionedBox(), child1, RenderPositionedBox(), child2, RenderPositionedBox(), child3, ]); pumpFrame(); table.setFlatChildren(3, <RenderBox>[ RenderPositionedBox(), child1, RenderPositionedBox(), child2, RenderPositionedBox(), child3, ]); pumpFrame(); expect(table.columns, equals(3)); expect(table.rows, equals(2)); }); test('Table border painting', () { final RenderTable table = RenderTable( textDirection: TextDirection.rtl, border: TableBorder.all(), ); layout(table); table.setFlatChildren(1, <RenderBox>[ ]); pumpFrame(); expect(table, paints..path()..path()..path()..path()); table.setFlatChildren(1, <RenderBox>[ RenderPositionedBox() ]); pumpFrame(); expect(table, paints..path()..path()..path()..path()); table.setFlatChildren(1, <RenderBox>[ RenderPositionedBox(), RenderPositionedBox() ]); pumpFrame(); expect(table, paints..path()..path()..path()..path()..path()); table.setFlatChildren(2, <RenderBox>[ RenderPositionedBox(), RenderPositionedBox() ]); pumpFrame(); expect(table, paints..path()..path()..path()..path()..path()); table.setFlatChildren(2, <RenderBox>[ RenderPositionedBox(), RenderPositionedBox(), RenderPositionedBox(), RenderPositionedBox(), ]); pumpFrame(); expect(table, paints..path()..path()..path()..path()..path()..path()); table.setFlatChildren(3, <RenderBox>[ RenderPositionedBox(), RenderPositionedBox(), RenderPositionedBox(), RenderPositionedBox(), RenderPositionedBox(), RenderPositionedBox(), ]); pumpFrame(); expect(table, paints..path()..path()..path()..path()..path()..path()); }); test('Table flex sizing', () { const BoxConstraints cellConstraints = BoxConstraints.tightFor(width: 100, height: 100); final RenderTable table = RenderTable( textDirection: TextDirection.rtl, children: <List<RenderBox>>[ List<RenderBox>.generate( 7, (int _) => RenderConstrainedBox(additionalConstraints: cellConstraints), ), ], columnWidths: const <int, TableColumnWidth>{ 0: FlexColumnWidth(), 1: FlexColumnWidth(0.123), 2: FlexColumnWidth(0.123), 3: FlexColumnWidth(0.123), 4: FlexColumnWidth(0.123), 5: FlexColumnWidth(0.123), 6: FlexColumnWidth(0.123), }, ); layout(table, constraints: BoxConstraints.tight(const Size(800.0, 600.0))); expect(table.hasSize, true); }); test('Table paints a borderRadius', () { final RenderTable table = RenderTable( textDirection: TextDirection.ltr, border: TableBorder.all(borderRadius: const BorderRadius.all(Radius.circular(8.0))), ); layout(table); table.setFlatChildren(2, <RenderBox>[ RenderPositionedBox(), RenderPositionedBox(), RenderPositionedBox(), RenderPositionedBox(), ]); pumpFrame(); expect(table, paints ..path() ..path() ..drrect( outer: RRect.fromLTRBR(0.0, 0.0, 800.0, 0.0, const Radius.circular(8.0)), inner: RRect.fromLTRBR(1.0, 1.0, 799.0, -1.0, const Radius.circular(7.0)), ) ); }); test('MaxColumnWidth.flex returns the correct result', () { MaxColumnWidth columnWidth = const MaxColumnWidth( FixedColumnWidth(100), // returns null from .flex FlexColumnWidth(), // returns 1 from .flex ); final double? flexValue = columnWidth.flex(<RenderBox>[]); expect(flexValue, 1.0); // Swap a and b, check for same result. columnWidth = const MaxColumnWidth( FlexColumnWidth(), // returns 1 from .flex FixedColumnWidth(100), // returns null from .flex ); // Same result. expect(columnWidth.flex(<RenderBox>[]), flexValue); }); test('MinColumnWidth.flex returns the correct result', () { MinColumnWidth columnWidth = const MinColumnWidth( FixedColumnWidth(100), // returns null from .flex FlexColumnWidth(), // returns 1 from .flex ); final double? flexValue = columnWidth.flex(<RenderBox>[]); expect(flexValue, 1.0); // Swap a and b, check for same result. columnWidth = const MinColumnWidth( FlexColumnWidth(), // returns 1 from .flex FixedColumnWidth(100), // returns null from .flex ); // Same result. expect(columnWidth.flex(<RenderBox>[]), flexValue); }); test('TableRows with different constraints, but vertically with intrinsicHeight', () { const BoxConstraints firstConstraints = BoxConstraints.tightFor(width: 100, height: 100); const BoxConstraints secondConstraints = BoxConstraints.tightFor(width: 200, height: 200); final RenderTable table = RenderTable( textDirection: TextDirection.rtl, defaultVerticalAlignment: TableCellVerticalAlignment.intrinsicHeight, children: <List<RenderBox>>[ <RenderBox>[ RenderConstrainedBox(additionalConstraints: firstConstraints), RenderConstrainedBox(additionalConstraints: secondConstraints), ] ], columnWidths: const <int, TableColumnWidth>{ 0: FlexColumnWidth(), 1: FlexColumnWidth(), }, ); const Size size = Size(300.0, 300.0); // Layout the table with a fixed size. layout(table, constraints: BoxConstraints.tight(size)); // Make sure the table has a size and that the children are filled vertically to the highest cell. expect(table.size, equals(size)); expect(table.defaultVerticalAlignment, TableCellVerticalAlignment.intrinsicHeight); }); }
flutter/packages/flutter/test/rendering/table_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/table_test.dart", "repo_id": "flutter", "token_count": 5115 }
685
// 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 'package:flutter/foundation.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; void main() { Future<void> setAppLifeCycleState(AppLifecycleState state) async { final ByteData? message = const StringCodec().encodeMessage(state.toString()); await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .handlePlatformMessage('flutter/lifecycle', message, (_) {}); } testWidgets('Ticker mute control test', (WidgetTester tester) async { int tickCount = 0; void handleTick(Duration duration) { tickCount += 1; } final Ticker ticker = Ticker(handleTick); addTearDown(ticker.dispose); expect(ticker.isTicking, isFalse); expect(ticker.isActive, isFalse); ticker.start(); expect(ticker.isTicking, isTrue); expect(ticker.isActive, isTrue); expect(tickCount, equals(0)); FlutterError? error; try { ticker.start(); } on FlutterError catch (e) { error = e; } expect(error, isNotNull); expect(error!.diagnostics.length, 3); expect(error.diagnostics.last, isA<DiagnosticsProperty<Ticker>>()); expect( error.toStringDeep(), startsWith( 'FlutterError\n' ' A ticker was started twice.\n' ' A ticker that is already active cannot be started again without\n' ' first stopping it.\n' ' The affected ticker was:\n' ' Ticker()\n', ), ); await tester.pump(const Duration(milliseconds: 10)); expect(tickCount, equals(1)); ticker.muted = true; await tester.pump(const Duration(milliseconds: 10)); expect(tickCount, equals(1)); expect(ticker.isTicking, isFalse); expect(ticker.isActive, isTrue); ticker.muted = false; await tester.pump(const Duration(milliseconds: 10)); expect(tickCount, equals(2)); expect(ticker.isTicking, isTrue); expect(ticker.isActive, isTrue); ticker.muted = true; await tester.pump(const Duration(milliseconds: 10)); expect(tickCount, equals(2)); expect(ticker.isTicking, isFalse); expect(ticker.isActive, isTrue); ticker.stop(); expect(tickCount, equals(2)); expect(ticker.isTicking, isFalse); expect(ticker.isActive, isFalse); ticker.muted = false; expect(tickCount, equals(2)); expect(ticker.isTicking, isFalse); expect(ticker.isActive, isFalse); await tester.pump(const Duration(milliseconds: 10)); expect(tickCount, equals(2)); expect(ticker.isTicking, isFalse); expect(ticker.isActive, isFalse); }); testWidgets('Ticker control test', (WidgetTester tester) async { late Ticker ticker; addTearDown(() => ticker.dispose()); void testFunction() { ticker = Ticker((Duration _) { }); } testFunction(); expect(ticker, hasOneLineDescription); expect(ticker.toString(debugIncludeStack: true), contains('testFunction')); }); testWidgets('Ticker can be sped up with time dilation', (WidgetTester tester) async { timeDilation = 0.5; // Move twice as fast. late Duration lastDuration; void handleTick(Duration duration) { lastDuration = duration; } final Ticker ticker = Ticker(handleTick); ticker.start(); await tester.pump(const Duration(milliseconds: 10)); await tester.pump(const Duration(milliseconds: 10)); expect(lastDuration, const Duration(milliseconds: 20)); ticker.dispose(); timeDilation = 1.0; // restore time dilation, or it will affect other tests }); testWidgets('Ticker can be slowed down with time dilation', (WidgetTester tester) async { timeDilation = 2.0; // Move half as fast. late Duration lastDuration; void handleTick(Duration duration) { lastDuration = duration; } final Ticker ticker = Ticker(handleTick); ticker.start(); await tester.pump(const Duration(milliseconds: 10)); await tester.pump(const Duration(milliseconds: 10)); expect(lastDuration, const Duration(milliseconds: 5)); ticker.dispose(); timeDilation = 1.0; // restore time dilation, or it will affect other tests }); testWidgets('Ticker stops ticking when application is paused', (WidgetTester tester) async { int tickCount = 0; void handleTick(Duration duration) { tickCount += 1; } final Ticker ticker = Ticker(handleTick); addTearDown(ticker.dispose); ticker.start(); expect(ticker.isTicking, isTrue); expect(ticker.isActive, isTrue); expect(tickCount, equals(0)); setAppLifeCycleState(AppLifecycleState.paused); expect(ticker.isTicking, isFalse); expect(ticker.isActive, isTrue); ticker.stop(); setAppLifeCycleState(AppLifecycleState.resumed); }); testWidgets('Ticker can be created before application unpauses', (WidgetTester tester) async { setAppLifeCycleState(AppLifecycleState.paused); int tickCount = 0; void handleTick(Duration duration) { tickCount += 1; } final Ticker ticker = Ticker(handleTick); addTearDown(ticker.dispose); ticker.start(); expect(tickCount, equals(0)); expect(ticker.isTicking, isFalse); await tester.pump(const Duration(milliseconds: 10)); expect(tickCount, equals(0)); expect(ticker.isTicking, isFalse); setAppLifeCycleState(AppLifecycleState.resumed); await tester.pump(const Duration(milliseconds: 10)); expect(tickCount, equals(1)); expect(ticker.isTicking, isTrue); ticker.stop(); }); test('Ticker dispatches memory events', () async { await expectLater( await memoryEvents(() => Ticker((_) {}).dispose(), Ticker,), areCreateAndDispose, ); }); }
flutter/packages/flutter/test/scheduler/ticker_test.dart/0
{ "file_path": "flutter/packages/flutter/test/scheduler/ticker_test.dart", "repo_id": "flutter", "token_count": 2243 }
686
// 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:convert'; import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; class TestChannelBuffersFlutterBinding extends BindingBase with SchedulerBinding, ServicesBinding { } void main() { ByteData makeByteData(String str) { return ByteData.sublistView(utf8.encode(str)); } String getString(ByteData data) { return utf8.decode(Uint8List.sublistView(data)); } test('does drain channel buffers', () async { const String channel = 'foo'; final TestChannelBuffersFlutterBinding binding = TestChannelBuffersFlutterBinding(); expect(binding.defaultBinaryMessenger, isNotNull); bool didCallCallback = false; void callback(ByteData? responseData) { didCallCallback = true; } const String payload = 'bar'; final ByteData data = makeByteData(payload); ui.channelBuffers.push(channel, data, callback); bool didDrainData = false; binding.defaultBinaryMessenger.setMessageHandler(channel, (ByteData? message) async { expect(getString(message!), payload); didDrainData = true; return null; }); // Flush the event queue. await Future<void>((){}); expect(didDrainData, isTrue); expect(didCallCallback, isTrue); }); }
flutter/packages/flutter/test/services/channel_buffers_test.dart/0
{ "file_path": "flutter/packages/flutter/test/services/channel_buffers_test.dart", "repo_id": "flutter", "token_count": 512 }
687
// 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 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('BasicMessageChannel', () { const MessageCodec<String?> string = StringCodec(); const BasicMessageChannel<String?> channel = BasicMessageChannel<String?>('ch', string); test('can send string message and get reply', () async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( 'ch', (ByteData? message) async => string.encodeMessage('${string.decodeMessage(message)!} world'), ); final String? reply = await channel.send('hello'); expect(reply, equals('hello world')); }); test('can receive string message and send reply', () async { channel.setMessageHandler((String? message) async => '${message!} world'); String? reply; await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( 'ch', const StringCodec().encodeMessage('hello'), (ByteData? replyBinary) { reply = string.decodeMessage(replyBinary); }, ); expect(reply, equals('hello world')); }); }); group('MethodChannel', () { const MessageCodec<dynamic> jsonMessage = JSONMessageCodec(); const MethodCodec jsonMethod = JSONMethodCodec(); const MethodChannel channel = MethodChannel('ch7', jsonMethod); const OptionalMethodChannel optionalMethodChannel = OptionalMethodChannel('ch8', jsonMethod); tearDown(() { channel.setMethodCallHandler(null); optionalMethodChannel.setMethodCallHandler(null); }); test('can invoke method and get result', () async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( 'ch7', (ByteData? message) async { final Map<dynamic, dynamic> methodCall = jsonMessage.decodeMessage(message) as Map<dynamic, dynamic>; if (methodCall['method'] == 'sayHello') { return jsonMessage.encodeMessage(<dynamic>['${methodCall['args']} world']); } else { return jsonMessage.encodeMessage(<dynamic>['unknown', null, null]); } }, ); final String? result = await channel.invokeMethod('sayHello', 'hello'); expect(result, equals('hello world')); }); test('can invoke list method and get result', () async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( 'ch7', (ByteData? message) async { final Map<dynamic, dynamic> methodCall = jsonMessage.decodeMessage(message) as Map<dynamic, dynamic>; if (methodCall['method'] == 'sayHello') { return jsonMessage.encodeMessage(<dynamic>[<String>['${methodCall['args']}', 'world']]); } else { return jsonMessage.encodeMessage(<dynamic>['unknown', null, null]); } }, ); expect(channel.invokeMethod<List<String>>('sayHello', 'hello'), throwsA(isA<TypeError>())); expect(await channel.invokeListMethod<String>('sayHello', 'hello'), <String>['hello', 'world']); }); test('can invoke list method and get null result', () async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( 'ch7', (ByteData? message) async { final Map<dynamic, dynamic> methodCall = jsonMessage.decodeMessage(message) as Map<dynamic, dynamic>; if (methodCall['method'] == 'sayHello') { return jsonMessage.encodeMessage(<dynamic>[null]); } else { return jsonMessage.encodeMessage(<dynamic>['unknown', null, null]); } }, ); expect(await channel.invokeListMethod<String>('sayHello', 'hello'), null); }); test('can invoke map method and get result', () async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( 'ch7', (ByteData? message) async { final Map<dynamic, dynamic> methodCall = jsonMessage.decodeMessage(message) as Map<dynamic, dynamic>; if (methodCall['method'] == 'sayHello') { return jsonMessage.encodeMessage(<dynamic>[<String, String>{'${methodCall['args']}': 'world'}]); } else { return jsonMessage.encodeMessage(<dynamic>['unknown', null, null]); } }, ); expect(channel.invokeMethod<Map<String, String>>('sayHello', 'hello'), throwsA(isA<TypeError>())); expect(await channel.invokeMapMethod<String, String>('sayHello', 'hello'), <String, String>{'hello': 'world'}); }); test('can invoke map method and get null result', () async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( 'ch7', (ByteData? message) async { final Map<dynamic, dynamic> methodCall = jsonMessage.decodeMessage(message) as Map<dynamic, dynamic>; if (methodCall['method'] == 'sayHello') { return jsonMessage.encodeMessage(<dynamic>[null]); } else { return jsonMessage.encodeMessage(<dynamic>['unknown', null, null]); } }, ); expect(await channel.invokeMapMethod<String, String>('sayHello', 'hello'), null); }); test('can invoke method and get error', () async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( 'ch7', (ByteData? message) async { return jsonMessage.encodeMessage(<dynamic>[ 'bad', 'Something happened', <String, dynamic>{'a': 42, 'b': 3.14}, ]); }, ); expect( () => channel.invokeMethod<dynamic>('sayHello', 'hello'), throwsA( isA<PlatformException>() .having((PlatformException e) => e.code, 'code', equals('bad')) .having((PlatformException e) => e.message, 'message', equals('Something happened')) .having((PlatformException e) => e.details, 'details', equals(<String, dynamic>{'a': 42, 'b': 3.14})), ), ); }); test('can invoke unimplemented method', () async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( 'ch7', (ByteData? message) async => null, ); expect( () => channel.invokeMethod<void>('sayHello', 'hello'), throwsA( isA<MissingPluginException>() .having((MissingPluginException e) => e.message, 'message', allOf( contains('sayHello'), contains('ch7'), )), ), ); }); test('can invoke unimplemented method (optional)', () async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( 'ch8', (ByteData? message) async => null, ); final String? result = await optionalMethodChannel.invokeMethod<String>('sayHello', 'hello'); expect(result, isNull); }); test('can handle method call with no registered plugin (setting before)', () async { channel.setMethodCallHandler(null); final ByteData call = jsonMethod.encodeMethodCall(const MethodCall('sayHello', 'hello')); ByteData? envelope; await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage('ch7', call, (ByteData? result) { envelope = result; }); await null; // just in case there's something async happening expect(envelope, isNull); }); test('can handle method call with no registered plugin (setting after)', () async { final ByteData call = jsonMethod.encodeMethodCall(const MethodCall('sayHello', 'hello')); ByteData? envelope; await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage('ch7', call, (ByteData? result) { envelope = result; }); channel.setMethodCallHandler(null); await null; // just in case there's something async happening expect(envelope, isNull); }); test('can handle method call of unimplemented method', () async { channel.setMethodCallHandler((MethodCall call) async { throw MissingPluginException(); }); final ByteData call = jsonMethod.encodeMethodCall(const MethodCall('sayHello', 'hello')); ByteData? envelope; await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage('ch7', call, (ByteData? result) { envelope = result; }); expect(envelope, isNull); }); test('can handle method call with successful result', () async { channel.setMethodCallHandler((MethodCall call) async => '${call.arguments}, world'); final ByteData call = jsonMethod.encodeMethodCall(const MethodCall('sayHello', 'hello')); ByteData? envelope; await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage('ch7', call, (ByteData? result) { envelope = result; }); expect(jsonMethod.decodeEnvelope(envelope!), equals('hello, world')); }); test('can handle method call with expressive error result', () async { channel.setMethodCallHandler((MethodCall call) async { throw PlatformException(code: 'bad', message: 'sayHello failed'); }); final ByteData call = jsonMethod.encodeMethodCall(const MethodCall('sayHello', 'hello')); ByteData? envelope; await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage('ch7', call, (ByteData? result) { envelope = result; }); expect( () => jsonMethod.decodeEnvelope(envelope!), throwsA( isA<PlatformException>() .having((PlatformException e) => e.code, 'code', equals('bad')) .having((PlatformException e) => e.message, 'message', equals('sayHello failed')), ), ); }); test('can handle method call with other error result', () async { channel.setMethodCallHandler((MethodCall call) async { throw ArgumentError('bad'); }); final ByteData call = jsonMethod.encodeMethodCall(const MethodCall('sayHello', 'hello')); ByteData? envelope; await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage('ch7', call, (ByteData? result) { envelope = result; }); expect( () => jsonMethod.decodeEnvelope(envelope!), throwsA( isA<PlatformException>() .having((PlatformException e) => e.code, 'code', equals('error')) .having((PlatformException e) => e.message, 'message', equals('Invalid argument(s): bad')), ), ); }); test('can check the mock handler', () async { Future<dynamic> handler(MethodCall call) => Future<dynamic>.value(); const MethodChannel channel = MethodChannel('test_handler'); expect(TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler(channel.name, null), true); expect(TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler(channel.name, handler), false); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(channel, handler); expect(TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler(channel.name, handler), true); }); }); group('EventChannel', () { const MethodCodec jsonMethod = JSONMethodCodec(); const EventChannel channel = EventChannel('ch', jsonMethod); test('can receive event stream', () async { bool canceled = false; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockStreamHandler( channel, MockStreamHandler.inline( onListen: (Object? arguments, MockStreamHandlerEventSink events) { events.success('${arguments}1'); events.success('${arguments}2'); events.endOfStream(); }, onCancel: (Object? arguments) { canceled = true; }, ), ); final List<Object?> events = await channel.receiveBroadcastStream('hello').toList(); expect(events, orderedEquals(<String>['hello1', 'hello2'])); await Future<void>.delayed(Duration.zero); expect(canceled, isTrue); }); test('can receive error event', () async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockStreamHandler( channel, MockStreamHandler.inline( onListen: (Object? arguments, MockStreamHandlerEventSink events) { events.error(code: '404', message: 'Not Found.', details: arguments); }, ), ); final List<Object?> events = <Object?>[]; final List<Object?> errors = <Object?>[]; channel.receiveBroadcastStream('hello').listen(events.add, onError: errors.add); await Future<void>.delayed(Duration.zero); expect(events, isEmpty); expect(errors, hasLength(1)); expect(errors[0], isA<PlatformException>()); final PlatformException? error = errors[0] as PlatformException?; expect(error?.code, '404'); expect(error?.message, 'Not Found.'); expect(error?.details, 'hello'); }); }); }
flutter/packages/flutter/test/services/platform_channel_test.dart/0
{ "file_path": "flutter/packages/flutter/test/services/platform_channel_test.dart", "repo_id": "flutter", "token_count": 5124 }
688
// 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:convert' show utf8; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; class FakeTextChannel implements MethodChannel { FakeTextChannel(this.outgoing); Future<dynamic> Function(MethodCall) outgoing; Future<void> Function(MethodCall)? incoming; List<MethodCall> outgoingCalls = <MethodCall>[]; @override BinaryMessenger get binaryMessenger => throw UnimplementedError(); @override MethodCodec get codec => const JSONMethodCodec(); @override Future<List<T>> invokeListMethod<T>(String method, [dynamic arguments]) => throw UnimplementedError(); @override Future<Map<K, V>> invokeMapMethod<K, V>(String method, [dynamic arguments]) => throw UnimplementedError(); @override Future<T> invokeMethod<T>(String method, [dynamic arguments]) async { final MethodCall call = MethodCall(method, arguments); outgoingCalls.add(call); return await outgoing(call) as T; } @override String get name => 'flutter/textinput'; @override void setMethodCallHandler(Future<void> Function(MethodCall call)? handler) => incoming = handler; void validateOutgoingMethodCalls(List<MethodCall> calls) { expect(outgoingCalls.length, calls.length); final StringBuffer output = StringBuffer(); bool hasError = false; for (int i = 0; i < calls.length; i++) { final ByteData outgoingData = codec.encodeMethodCall(outgoingCalls[i]); final ByteData expectedData = codec.encodeMethodCall(calls[i]); final String outgoingString = utf8.decode(outgoingData.buffer.asUint8List()); final String expectedString = utf8.decode(expectedData.buffer.asUint8List()); if (outgoingString != expectedString) { output.writeln( 'Index $i did not match:\n' ' actual: $outgoingString\n' ' expected: $expectedString', ); hasError = true; } } if (hasError) { fail('Calls did not match:\n$output'); } } } class FakeScribbleElement implements ScribbleClient { FakeScribbleElement({required String elementIdentifier, Rect bounds = Rect.zero}) : _elementIdentifier = elementIdentifier, _bounds = bounds; final String _elementIdentifier; final Rect _bounds; String latestMethodCall = ''; @override Rect get bounds => _bounds; @override String get elementIdentifier => _elementIdentifier; @override bool isInScribbleRect(Rect rect) { return _bounds.overlaps(rect); } @override void onScribbleFocus(Offset offset) { latestMethodCall = 'onScribbleFocus'; } }
flutter/packages/flutter/test/services/text_input_utils.dart/0
{ "file_path": "flutter/packages/flutter/test/services/text_input_utils.dart", "repo_id": "flutter", "token_count": 931 }
689
// 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 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('AnimatedSwitcher fades in a new child.', (WidgetTester tester) async { final UniqueKey containerOne = UniqueKey(); final UniqueKey containerTwo = UniqueKey(); final UniqueKey containerThree = UniqueKey(); await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), child: Container(key: containerOne, color: const Color(0x00000000)), ), ); expect(find.byType(FadeTransition), findsOneWidget); FadeTransition transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, equals(1.0)); await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), child: Container(key: containerTwo, color: const Color(0xff000000)), ), ); await tester.pump(const Duration(milliseconds: 50)); expect(find.byType(FadeTransition), findsNWidgets(2)); transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, equals(0.5)); await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), child: Container(key: containerThree, color: const Color(0xffff0000)), ), ); await tester.pump(const Duration(milliseconds: 10)); transition = tester.widget(find.byType(FadeTransition).at(0)); expect(transition.opacity.value, moreOrLessEquals(0.4, epsilon: 0.01)); transition = tester.widget(find.byType(FadeTransition).at(1)); expect(transition.opacity.value, moreOrLessEquals(0.4, epsilon: 0.01)); transition = tester.widget(find.byType(FadeTransition).at(2)); expect(transition.opacity.value, moreOrLessEquals(0.1, epsilon: 0.01)); await tester.pumpAndSettle(); }); testWidgets('AnimatedSwitcher can handle back-to-back changes.', (WidgetTester tester) async { final UniqueKey container1 = UniqueKey(); final UniqueKey container2 = UniqueKey(); final UniqueKey container3 = UniqueKey(); await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), child: Container(key: container1), ), ); expect(find.byKey(container1), findsOneWidget); expect(find.byKey(container2), findsNothing); expect(find.byKey(container3), findsNothing); await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), child: Container(key: container2), ), ); expect(find.byKey(container1), findsOneWidget); expect(find.byKey(container2), findsOneWidget); expect(find.byKey(container3), findsNothing); await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), child: Container(key: container3), ), ); expect(find.byKey(container1), findsOneWidget); expect(find.byKey(container2), findsNothing); expect(find.byKey(container3), findsOneWidget); }); testWidgets("AnimatedSwitcher doesn't transition in a new child of the same type.", (WidgetTester tester) async { await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), child: Container(color: const Color(0x00000000)), ), ); expect(find.byType(FadeTransition), findsOneWidget); FadeTransition transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, equals(1.0)); await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), child: Container(color: const Color(0xff000000)), ), ); await tester.pump(const Duration(milliseconds: 50)); expect(find.byType(FadeTransition), findsOneWidget); transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, equals(1.0)); await tester.pumpAndSettle(); }); testWidgets('AnimatedSwitcher handles null children.', (WidgetTester tester) async { await tester.pumpWidget( const AnimatedSwitcher( duration: Duration(milliseconds: 100), ), ); expect(find.byType(FadeTransition), findsNothing); await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), child: Container(color: const Color(0xff000000)), ), ); await tester.pump(const Duration(milliseconds: 50)); FadeTransition transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, equals(0.5)); await tester.pumpAndSettle(); await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), child: Container(color: const Color(0x00000000)), ), ); expect(find.byType(FadeTransition), findsOneWidget); transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, equals(1.0)); await tester.pumpWidget( const AnimatedSwitcher( duration: Duration(milliseconds: 100), ), ); await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, equals(0.5)); await tester.pumpWidget( const AnimatedSwitcher( duration: Duration(milliseconds: 100), ), ); await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, equals(0.0)); await tester.pumpAndSettle(); }); testWidgets("AnimatedSwitcher doesn't start any animations after dispose.", (WidgetTester tester) async { await tester.pumpWidget(AnimatedSwitcher( duration: const Duration(milliseconds: 100), child: Container(color: const Color(0xff000000)), )); await tester.pump(const Duration(milliseconds: 50)); // Change the widget tree in the middle of the animation. await tester.pumpWidget(Container(color: const Color(0xffff0000))); expect(await tester.pumpAndSettle(), equals(1)); }); testWidgets('AnimatedSwitcher uses custom layout.', (WidgetTester tester) async { Widget newLayoutBuilder(Widget? currentChild, List<Widget> previousChildren) { return Column( children: <Widget>[ ...previousChildren, if (currentChild != null) currentChild, ], ); } await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), layoutBuilder: newLayoutBuilder, child: Container(color: const Color(0x00000000)), ), ); expect(find.byType(Column), findsOneWidget); }); testWidgets('AnimatedSwitcher uses custom transitions.', (WidgetTester tester) async { late List<Widget> foundChildren; Widget newLayoutBuilder(Widget? currentChild, List<Widget> previousChildren) { foundChildren = <Widget>[ if (currentChild != null) currentChild, ...previousChildren, ]; return Column(children: foundChildren); } Widget newTransitionBuilder(Widget child, Animation<double> animation) { return SizeTransition( sizeFactor: animation, child: child, ); } await tester.pumpWidget( Directionality( textDirection: TextDirection.rtl, child: AnimatedSwitcher( duration: const Duration(milliseconds: 100), layoutBuilder: newLayoutBuilder, transitionBuilder: newTransitionBuilder, child: Container(color: const Color(0x00000000)), ), ), ); expect(find.byType(Column), findsOneWidget); for (final Widget child in foundChildren) { expect(child, isA<KeyedSubtree>()); } await tester.pumpWidget( Directionality( textDirection: TextDirection.rtl, child: AnimatedSwitcher( duration: const Duration(milliseconds: 100), layoutBuilder: newLayoutBuilder, transitionBuilder: newTransitionBuilder, ), ), ); await tester.pump(const Duration(milliseconds: 50)); for (final Widget child in foundChildren) { expect(child, isA<KeyedSubtree>()); expect( find.descendant(of: find.byWidget(child), matching: find.byType(SizeTransition)), findsOneWidget, ); } }); testWidgets("AnimatedSwitcher doesn't reset state of the children in transitions.", (WidgetTester tester) async { final UniqueKey statefulOne = UniqueKey(); final UniqueKey statefulTwo = UniqueKey(); final UniqueKey statefulThree = UniqueKey(); StatefulTestState.generation = 0; await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), child: StatefulTest(key: statefulOne), ), ); expect(find.byType(FadeTransition), findsOneWidget); FadeTransition transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, equals(1.0)); expect(StatefulTestState.generation, equals(1)); await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), child: StatefulTest(key: statefulTwo), ), ); await tester.pump(const Duration(milliseconds: 50)); expect(find.byType(FadeTransition), findsNWidgets(2)); transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, equals(0.5)); expect(StatefulTestState.generation, equals(2)); await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), child: StatefulTest(key: statefulThree), ), ); await tester.pump(const Duration(milliseconds: 10)); expect(StatefulTestState.generation, equals(3)); transition = tester.widget(find.byType(FadeTransition).at(0)); expect(transition.opacity.value, moreOrLessEquals(0.4, epsilon: 0.01)); transition = tester.widget(find.byType(FadeTransition).at(1)); expect(transition.opacity.value, moreOrLessEquals(0.4, epsilon: 0.01)); transition = tester.widget(find.byType(FadeTransition).at(2)); expect(transition.opacity.value, moreOrLessEquals(0.1, epsilon: 0.01)); await tester.pumpAndSettle(); expect(StatefulTestState.generation, equals(3)); }); testWidgets('AnimatedSwitcher updates widgets without animating if they are isomorphic.', (WidgetTester tester) async { Future<void> pumpChild(Widget child) async { return tester.pumpWidget( Directionality( textDirection: TextDirection.rtl, child: AnimatedSwitcher( duration: const Duration(milliseconds: 100), child: child, ), ), ); } await pumpChild(const Text('1')); await tester.pump(const Duration(milliseconds: 10)); FadeTransition transition = tester.widget(find.byType(FadeTransition).first); expect(transition.opacity.value, equals(1.0)); expect(find.text('1'), findsOneWidget); expect(find.text('2'), findsNothing); await pumpChild(const Text('2')); transition = tester.widget(find.byType(FadeTransition).first); await tester.pump(const Duration(milliseconds: 20)); expect(transition.opacity.value, equals(1.0)); expect(find.text('1'), findsNothing); expect(find.text('2'), findsOneWidget); }); testWidgets('AnimatedSwitcher updates previous child transitions if the transitionBuilder changes.', (WidgetTester tester) async { final UniqueKey containerOne = UniqueKey(); final UniqueKey containerTwo = UniqueKey(); final UniqueKey containerThree = UniqueKey(); late List<Widget> foundChildren; Widget newLayoutBuilder(Widget? currentChild, List<Widget> previousChildren) { foundChildren = <Widget>[ if (currentChild != null) currentChild, ...previousChildren, ]; return Column(children: foundChildren); } // Insert three unique children so that we have some previous children. await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), layoutBuilder: newLayoutBuilder, child: Container(key: containerOne, color: const Color(0xFFFF0000)), ), ); await tester.pump(const Duration(milliseconds: 10)); await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), layoutBuilder: newLayoutBuilder, child: Container(key: containerTwo, color: const Color(0xFF00FF00)), ), ); await tester.pump(const Duration(milliseconds: 10)); await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), layoutBuilder: newLayoutBuilder, child: Container(key: containerThree, color: const Color(0xFF0000FF)), ), ); await tester.pump(const Duration(milliseconds: 10)); expect(foundChildren.length, equals(3)); for (final Widget child in foundChildren) { expect(child, isA<KeyedSubtree>()); expect( find.descendant(of: find.byWidget(child), matching: find.byType(FadeTransition)), findsOneWidget, ); } Widget newTransitionBuilder(Widget child, Animation<double> animation) { return ScaleTransition( scale: animation, child: child, ); } // Now set a new transition builder and make sure all the previous // transitions are replaced. await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), layoutBuilder: newLayoutBuilder, transitionBuilder: newTransitionBuilder, child: Container(color: const Color(0x00000000)), ), ); await tester.pump(const Duration(milliseconds: 10)); expect(foundChildren.length, equals(3)); for (final Widget child in foundChildren) { expect(child, isA<KeyedSubtree>()); expect( find.descendant(of: find.byWidget(child), matching: find.byType(ScaleTransition)), findsOneWidget, ); } }); testWidgets('AnimatedSwitcher does not duplicate animations if the same child is entered twice.', (WidgetTester tester) async { Future<void> pumpChild(Widget child) async { return tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: AnimatedSwitcher( duration: const Duration(milliseconds: 1000), child: child, ), ), ); } await pumpChild(const Text('1', key: Key('1'))); await pumpChild(const Text('2', key: Key('2'))); await pumpChild(const Text('1', key: Key('1'))); await tester.pump(const Duration(milliseconds: 1000)); expect(find.text('1'), findsOneWidget); }); } class StatefulTest extends StatefulWidget { const StatefulTest({super.key}); @override StatefulTestState createState() => StatefulTestState(); } class StatefulTestState extends State<StatefulTest> { StatefulTestState(); static int generation = 0; @override void initState() { super.initState(); generation++; } @override Widget build(BuildContext context) => Container(); }
flutter/packages/flutter/test/widgets/animated_switcher_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/animated_switcher_test.dart", "repo_id": "flutter", "token_count": 5764 }
690
// 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. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'dart:math' as math; import 'dart:ui' as ui; import 'dart:ui'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { group('RawImage', () { testWidgets('properties', (WidgetTester tester) async { final ui.Image image1 = (await tester.runAsync<ui.Image>(() => createTestImage()))!; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: RawImage(image: image1), ), ); final RenderImage renderObject = tester.firstRenderObject<RenderImage>(find.byType(RawImage)); // Expect default values expect(renderObject.image!.isCloneOf(image1), true); expect(renderObject.debugImageLabel, null); expect(renderObject.width, null); expect(renderObject.height, null); expect(renderObject.scale, 1.0); expect(renderObject.color, null); expect(renderObject.opacity, null); expect(renderObject.colorBlendMode, null); expect(renderObject.fit, null); expect(renderObject.alignment, Alignment.center); expect(renderObject.repeat, ImageRepeat.noRepeat); expect(renderObject.centerSlice, null); expect(renderObject.matchTextDirection, false); expect(renderObject.invertColors, false); expect(renderObject.filterQuality, FilterQuality.low); expect(renderObject.isAntiAlias, false); final ui.Image image2 = (await tester.runAsync<ui.Image>(() => createTestImage(width: 2, height: 2)))!; const String debugImageLabel = 'debugImageLabel'; const double width = 1; const double height = 1; const double scale = 2.0; const Color color = Colors.black; const Animation<double> opacity = AlwaysStoppedAnimation<double>(0.0); const BlendMode colorBlendMode = BlendMode.difference; const BoxFit fit = BoxFit.contain; const AlignmentGeometry alignment = Alignment.topCenter; const ImageRepeat repeat = ImageRepeat.repeat; const Rect centerSlice = Rect.fromLTWH(0, 0, width, height); const bool matchTextDirection = true; const bool invertColors = true; const FilterQuality filterQuality = FilterQuality.high; const bool isAntiAlias = true; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: RawImage( image: image2, debugImageLabel: debugImageLabel, width: width, height: height, scale: scale, color: color, opacity: opacity, colorBlendMode: colorBlendMode, fit: fit, alignment: alignment, repeat: repeat, centerSlice: centerSlice, matchTextDirection: matchTextDirection, invertColors: invertColors, filterQuality: filterQuality, isAntiAlias: isAntiAlias, ), ), ); expect(renderObject.image!.isCloneOf(image2), true); expect(renderObject.debugImageLabel, debugImageLabel); expect(renderObject.width, width); expect(renderObject.height, height); expect(renderObject.scale, scale); expect(renderObject.color, color); expect(renderObject.opacity, opacity); expect(renderObject.colorBlendMode, colorBlendMode); expect(renderObject.fit, fit); expect(renderObject.alignment, alignment); expect(renderObject.repeat, repeat); expect(renderObject.centerSlice, centerSlice); expect(renderObject.matchTextDirection, matchTextDirection); expect(renderObject.invertColors, invertColors); expect(renderObject.filterQuality, filterQuality); expect(renderObject.isAntiAlias, isAntiAlias); }); }); group('PhysicalShape', () { testWidgets('properties', (WidgetTester tester) async { await tester.pumpWidget( const PhysicalShape( clipper: ShapeBorderClipper(shape: CircleBorder()), elevation: 2.0, color: Color(0xFF0000FF), shadowColor: Color(0xFF00FF00), ), ); final RenderPhysicalShape renderObject = tester.renderObject(find.byType(PhysicalShape)); expect(renderObject.clipper, const ShapeBorderClipper(shape: CircleBorder())); expect(renderObject.color, const Color(0xFF0000FF)); expect(renderObject.shadowColor, const Color(0xFF00FF00)); expect(renderObject.elevation, 2.0); }); testWidgets('hit test', (WidgetTester tester) async { await tester.pumpWidget( PhysicalShape( clipper: const ShapeBorderClipper(shape: CircleBorder()), elevation: 2.0, color: const Color(0xFF0000FF), shadowColor: const Color(0xFF00FF00), child: Container(color: const Color(0xFF0000FF)), ), ); final RenderPhysicalShape renderPhysicalShape = tester.renderObject(find.byType(PhysicalShape)); // The viewport is 800x600, the CircleBorder is centered and fits // the shortest edge, so we get a circle of radius 300, centered at // (400, 300). // // We test by sampling a few points around the left-most point of the // circle (100, 300). expect(tester.hitTestOnBinding(const Offset(99.0, 300.0)), doesNotHit(renderPhysicalShape)); expect(tester.hitTestOnBinding(const Offset(100.0, 300.0)), hits(renderPhysicalShape)); expect(tester.hitTestOnBinding(const Offset(100.0, 299.0)), doesNotHit(renderPhysicalShape)); expect(tester.hitTestOnBinding(const Offset(100.0, 301.0)), doesNotHit(renderPhysicalShape)); }); }); group('FractionalTranslation', () { testWidgets('hit test - entirely inside the bounding box', (WidgetTester tester) async { final GlobalKey key1 = GlobalKey(); bool pointerDown = false; await tester.pumpWidget( Center( child: FractionalTranslation( translation: Offset.zero, child: Listener( onPointerDown: (PointerDownEvent event) { pointerDown = true; }, child: SizedBox( key: key1, width: 100.0, height: 100.0, child: Container( color: const Color(0xFF0000FF), ), ), ), ), ), ); expect(pointerDown, isFalse); await tester.tap(find.byKey(key1)); expect(pointerDown, isTrue); }); testWidgets('hit test - partially inside the bounding box', (WidgetTester tester) async { final GlobalKey key1 = GlobalKey(); bool pointerDown = false; await tester.pumpWidget( Center( child: FractionalTranslation( translation: const Offset(0.5, 0.5), child: Listener( onPointerDown: (PointerDownEvent event) { pointerDown = true; }, child: SizedBox( key: key1, width: 100.0, height: 100.0, child: Container( color: const Color(0xFF0000FF), ), ), ), ), ), ); expect(pointerDown, isFalse); await tester.tap(find.byKey(key1)); expect(pointerDown, isTrue); }); testWidgets('hit test - completely outside the bounding box', (WidgetTester tester) async { final GlobalKey key1 = GlobalKey(); bool pointerDown = false; await tester.pumpWidget( Center( child: FractionalTranslation( translation: const Offset(1.0, 1.0), child: Listener( onPointerDown: (PointerDownEvent event) { pointerDown = true; }, child: SizedBox( key: key1, width: 100.0, height: 100.0, child: Container( color: const Color(0xFF0000FF), ), ), ), ), ), ); expect(pointerDown, isFalse); await tester.tap(find.byKey(key1)); expect(pointerDown, isTrue); }); testWidgets('semantics bounds are updated', (WidgetTester tester) async { final GlobalKey fractionalTranslationKey = GlobalKey(); final GlobalKey textKey = GlobalKey(); Offset offset = const Offset(0.4, 0.4); await tester.pumpWidget( StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Directionality( textDirection: TextDirection.ltr, child: Center( child: Semantics( explicitChildNodes: true, child: FractionalTranslation( key: fractionalTranslationKey, translation: offset, child: GestureDetector( onTap: () { setState(() { offset = const Offset(0.8, 0.8); }); }, child: SizedBox( width: 100.0, height: 100.0, child: Text( 'foo', key: textKey, ), ), ), ), ), ), ); }, ), ); expect( tester.getSemantics(find.byKey(textKey)).transform, Matrix4( 3.0, 0.0, 0.0, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1170.0, 870.0, 0.0, 1.0, ), ); await tester.tap(find.byKey(fractionalTranslationKey), warnIfMissed: false); // RenderFractionalTranslation can't be hit await tester.pump(); expect( tester.getSemantics(find.byKey(textKey)).transform, Matrix4( 3.0, 0.0, 0.0, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1290.0, 990.0, 0.0, 1.0, ), ); }); }); group('Semantics', () { testWidgets('Semantics can set attributed Text', (WidgetTester tester) async { final UniqueKey key = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Semantics( key: key, attributedLabel: AttributedString( 'label', attributes: <StringAttribute>[ SpellOutStringAttribute(range: const TextRange(start: 0, end: 5)), ], ), attributedValue: AttributedString( 'value', attributes: <StringAttribute>[ LocaleStringAttribute(range: const TextRange(start: 0, end: 5), locale: const Locale('en', 'MX')), ], ), attributedHint: AttributedString( 'hint', attributes: <StringAttribute>[ SpellOutStringAttribute(range: const TextRange(start: 1, end: 2)), ], ), child: const Placeholder(), ) ), ) ); final AttributedString attributedLabel = tester.getSemantics(find.byKey(key)).attributedLabel; expect(attributedLabel.string, 'label'); expect(attributedLabel.attributes.length, 1); expect(attributedLabel.attributes[0] is SpellOutStringAttribute, isTrue); expect(attributedLabel.attributes[0].range, const TextRange(start:0, end: 5)); final AttributedString attributedValue = tester.getSemantics(find.byKey(key)).attributedValue; expect(attributedValue.string, 'value'); expect(attributedValue.attributes.length, 1); expect(attributedValue.attributes[0] is LocaleStringAttribute, isTrue); final LocaleStringAttribute valueLocale = attributedValue.attributes[0] as LocaleStringAttribute; expect(valueLocale.range, const TextRange(start:0, end: 5)); expect(valueLocale.locale, const Locale('en', 'MX')); final AttributedString attributedHint = tester.getSemantics(find.byKey(key)).attributedHint; expect(attributedHint.string, 'hint'); expect(attributedHint.attributes.length, 1); expect(attributedHint.attributes[0] is SpellOutStringAttribute, isTrue); expect(attributedHint.attributes[0].range, const TextRange(start:1, end: 2)); }); testWidgets('Semantics can merge attributed strings', (WidgetTester tester) async { final UniqueKey key = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Semantics( key: key, attributedLabel: AttributedString( 'label', attributes: <StringAttribute>[ SpellOutStringAttribute(range: const TextRange(start: 0, end: 5)), ], ), attributedHint: AttributedString( 'hint', attributes: <StringAttribute>[ SpellOutStringAttribute(range: const TextRange(start: 1, end: 2)), ], ), child: Semantics( attributedLabel: AttributedString( 'label', attributes: <StringAttribute>[ SpellOutStringAttribute(range: const TextRange(start: 0, end: 5)), ], ), attributedHint: AttributedString( 'hint', attributes: <StringAttribute>[ SpellOutStringAttribute(range: const TextRange(start: 1, end: 2)), ], ), child: const Placeholder(), ) ) ), ) ); final AttributedString attributedLabel = tester.getSemantics(find.byKey(key)).attributedLabel; expect(attributedLabel.string, 'label\nlabel'); expect(attributedLabel.attributes.length, 2); expect(attributedLabel.attributes[0] is SpellOutStringAttribute, isTrue); expect(attributedLabel.attributes[0].range, const TextRange(start:0, end: 5)); expect(attributedLabel.attributes[1] is SpellOutStringAttribute, isTrue); expect(attributedLabel.attributes[1].range, const TextRange(start:6, end: 11)); final AttributedString attributedHint = tester.getSemantics(find.byKey(key)).attributedHint; expect(attributedHint.string, 'hint\nhint'); expect(attributedHint.attributes.length, 2); expect(attributedHint.attributes[0] is SpellOutStringAttribute, isTrue); expect(attributedHint.attributes[0].range, const TextRange(start:1, end: 2)); expect(attributedHint.attributes[1] is SpellOutStringAttribute, isTrue); expect(attributedHint.attributes[1].range, const TextRange(start:6, end: 7)); }); testWidgets('Semantics can merge attributed strings with non attributed string', (WidgetTester tester) async { final UniqueKey key = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Semantics( key: key, attributedLabel: AttributedString( 'label1', attributes: <StringAttribute>[ SpellOutStringAttribute(range: const TextRange(start: 0, end: 5)), ], ), child: Semantics( label: 'label2', child: Semantics( attributedLabel: AttributedString( 'label3', attributes: <StringAttribute>[ SpellOutStringAttribute(range: const TextRange(start: 1, end: 3)), ], ), child: const Placeholder(), ), ) ) ), ) ); final AttributedString attributedLabel = tester.getSemantics(find.byKey(key)).attributedLabel; expect(attributedLabel.string, 'label1\nlabel2\nlabel3'); expect(attributedLabel.attributes.length, 2); expect(attributedLabel.attributes[0] is SpellOutStringAttribute, isTrue); expect(attributedLabel.attributes[0].range, const TextRange(start:0, end: 5)); expect(attributedLabel.attributes[1] is SpellOutStringAttribute, isTrue); expect(attributedLabel.attributes[1].range, const TextRange(start:15, end: 17)); }); }); group('Row', () { testWidgets('multiple baseline aligned children', (WidgetTester tester) async { final UniqueKey key1 = UniqueKey(); final UniqueKey key2 = UniqueKey(); // The point size of the font must be a multiple of 4 until // https://github.com/flutter/flutter/issues/122066 is resolved. const double fontSize1 = 52; const double fontSize2 = 12; await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: <Widget>[ Text('big text', key: key1, style: const TextStyle(fontFamily: 'FlutterTest', fontSize: fontSize1, height: 1.0), ), Text('one\ntwo\nthree\nfour\nfive\nsix\nseven', key: key2, style: const TextStyle(fontFamily: 'FlutterTest', fontSize: fontSize2, height: 1.0), ), ], ), ), ), ); final RenderBox textBox1 = tester.renderObject(find.byKey(key1)); final RenderBox textBox2 = tester.renderObject(find.byKey(key2)); final RenderBox rowBox = tester.renderObject(find.byType(Row)); // The two Texts are baseline aligned, so some portion of them extends // both above and below the baseline. The first has a huge font size, so // it extends higher above the baseline than usual. The second has many // lines, but being aligned by the first line's baseline, they hang far // below the baseline. The size of the parent row is just enough to // contain both of them. const double ascentRatio = 0.75; const double aboveBaseline1 = fontSize1 * ascentRatio; const double belowBaseline1 = fontSize1 * (1 - ascentRatio); const double aboveBaseline2 = fontSize2 * ascentRatio; const double belowBaseline2 = fontSize2 * (1 - ascentRatio) + fontSize2 * 6; final double aboveBaseline = math.max(aboveBaseline1, aboveBaseline2); final double belowBaseline = math.max(belowBaseline1, belowBaseline2); expect(rowBox.size.height, greaterThan(textBox1.size.height)); expect(rowBox.size.height, greaterThan(textBox2.size.height)); expect(rowBox.size.height, aboveBaseline + belowBaseline, ); expect(tester.getTopLeft(find.byKey(key1)).dy, 0); expect(tester.getTopLeft(find.byKey(key2)).dy, aboveBaseline1 - aboveBaseline2); }); testWidgets('baseline aligned children account for a larger, no-baseline child size', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/58898 final UniqueKey key1 = UniqueKey(); final UniqueKey key2 = UniqueKey(); // The point size of the font must be a multiple of 4 until // https://github.com/flutter/flutter/issues/122066 is resolved. const double fontSize1 = 52; const double fontSize2 = 12; await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: <Widget>[ Text('big text', key: key1, style: const TextStyle(fontFamily: 'FlutterTest', fontSize: fontSize1, height: 1.0), ), Text('one\ntwo\nthree\nfour\nfive\nsix\nseven', key: key2, style: const TextStyle(fontFamily: 'FlutterTest', fontSize: fontSize2, height: 1.0), ), const FlutterLogo(size: 250), ], ), ), ), ); final RenderBox textBox1 = tester.renderObject(find.byKey(key1)); final RenderBox textBox2 = tester.renderObject(find.byKey(key2)); final RenderBox rowBox = tester.renderObject(find.byType(Row)); // The two Texts are baseline aligned, so some portion of them extends // both above and below the baseline. The first has a huge font size, so // it extends higher above the baseline than usual. The second has many // lines, but being aligned by the first line's baseline, they hang far // below the baseline. The FlutterLogo extends further than both Texts, // so the size of the parent row should contain the FlutterLogo as well. const double ascentRatio = 0.75; const double aboveBaseline1 = fontSize1 * ascentRatio; const double aboveBaseline2 = fontSize2 * ascentRatio; expect(rowBox.size.height, greaterThan(textBox1.size.height)); expect(rowBox.size.height, greaterThan(textBox2.size.height)); expect(rowBox.size.height, 250); expect(tester.getTopLeft(find.byKey(key1)).dy, 0); expect( tester.getTopLeft(find.byKey(key2)).dy, aboveBaseline1 - aboveBaseline2, ); }); }); test('UnconstrainedBox toString', () { expect( const UnconstrainedBox(constrainedAxis: Axis.vertical).toString(), equals('UnconstrainedBox(alignment: Alignment.center, constrainedAxis: vertical)'), ); expect( const UnconstrainedBox(constrainedAxis: Axis.horizontal, textDirection: TextDirection.rtl, alignment: Alignment.topRight).toString(), equals('UnconstrainedBox(alignment: Alignment.topRight, constrainedAxis: horizontal, textDirection: rtl)'), ); }); testWidgets('UnconstrainedBox can set and update clipBehavior', (WidgetTester tester) async { await tester.pumpWidget(const UnconstrainedBox()); final RenderConstraintsTransformBox renderObject = tester.allRenderObjects.whereType<RenderConstraintsTransformBox>().first; expect(renderObject.clipBehavior, equals(Clip.none)); await tester.pumpWidget(const UnconstrainedBox(clipBehavior: Clip.antiAlias)); expect(renderObject.clipBehavior, equals(Clip.antiAlias)); }); testWidgets('UnconstrainedBox warns only when clipBehavior is Clip.none', (WidgetTester tester) async { for (final Clip? clip in <Clip?>[null, ...Clip.values]) { // Clear any render objects that were there before so that we can see more // than one error. Otherwise, it just throws the first one and skips the // rest, since the render objects haven't changed. await tester.pumpWidget(const SizedBox()); await tester.pumpWidget( Center( child: ConstrainedBox( constraints: const BoxConstraints(maxHeight: 200, maxWidth: 200), child: clip == null ? const UnconstrainedBox(child: SizedBox(width: 400, height: 400)) : UnconstrainedBox( clipBehavior: clip, child: const SizedBox(width: 400, height: 400), ), ), ), ); final RenderConstraintsTransformBox renderObject = tester.allRenderObjects.whereType<RenderConstraintsTransformBox>().first; // Defaults to Clip.none expect(renderObject.clipBehavior, equals(clip ?? Clip.none), reason: 'for clip = $clip'); switch (clip) { case null: case Clip.none: // the UnconstrainedBox overflows. final dynamic exception = tester.takeException(); expect(exception, isFlutterError, reason: 'for clip = $clip'); // ignore: avoid_dynamic_calls expect(exception.diagnostics.first.level, DiagnosticLevel.summary, reason: 'for clip = $clip'); expect( // ignore: avoid_dynamic_calls exception.diagnostics.first.toString(), startsWith('A RenderConstraintsTransformBox overflowed'), reason: 'for clip = $clip', ); case Clip.hardEdge: case Clip.antiAlias: case Clip.antiAliasWithSaveLayer: expect(tester.takeException(), isNull, reason: 'for clip = $clip'); } } }); group('ConstraintsTransformBox', () { test('toString', () { expect( const ConstraintsTransformBox( constraintsTransform: ConstraintsTransformBox.unconstrained, ).toString(), equals('ConstraintsTransformBox(alignment: Alignment.center, constraints transform: unconstrained)'), ); expect( const ConstraintsTransformBox( textDirection: TextDirection.rtl, alignment: Alignment.topRight, constraintsTransform: ConstraintsTransformBox.widthUnconstrained, ).toString(), equals('ConstraintsTransformBox(alignment: Alignment.topRight, textDirection: rtl, constraints transform: width constraints removed)'), ); }); }); group('ColoredBox', () { late _MockCanvas mockCanvas; late _MockPaintingContext mockContext; const Color colorToPaint = Color(0xFFABCDEF); setUp(() { mockContext = _MockPaintingContext(); mockCanvas = mockContext.canvas; }); testWidgets('ColoredBox - no size, no child', (WidgetTester tester) async { await tester.pumpWidget(const Flex( direction: Axis.horizontal, textDirection: TextDirection.ltr, children: <Widget>[ SizedBox.shrink( child: ColoredBox(color: colorToPaint), ), ], )); expect(find.byType(ColoredBox), findsOneWidget); final RenderObject renderColoredBox = tester.renderObject(find.byType(ColoredBox)); renderColoredBox.paint(mockContext, Offset.zero); expect(mockCanvas.rects, isEmpty); expect(mockCanvas.paints, isEmpty); expect(mockContext.children, isEmpty); expect(mockContext.offsets, isEmpty); }); testWidgets('ColoredBox - no size, child', (WidgetTester tester) async { const ValueKey<int> key = ValueKey<int>(0); const Widget child = SizedBox.expand(key: key); await tester.pumpWidget(const Flex( direction: Axis.horizontal, textDirection: TextDirection.ltr, children: <Widget>[ SizedBox.shrink( child: ColoredBox(color: colorToPaint, child: child), ), ], )); expect(find.byType(ColoredBox), findsOneWidget); final RenderObject renderColoredBox = tester.renderObject(find.byType(ColoredBox)); final RenderObject renderSizedBox = tester.renderObject(find.byKey(key)); renderColoredBox.paint(mockContext, Offset.zero); expect(mockCanvas.rects, isEmpty); expect(mockCanvas.paints, isEmpty); expect(mockContext.children.single, renderSizedBox); expect(mockContext.offsets.single, Offset.zero); }); testWidgets('ColoredBox - size, no child', (WidgetTester tester) async { await tester.pumpWidget(const ColoredBox(color: colorToPaint)); expect(find.byType(ColoredBox), findsOneWidget); final RenderObject renderColoredBox = tester.renderObject(find.byType(ColoredBox)); renderColoredBox.paint(mockContext, Offset.zero); expect(mockCanvas.rects.single, const Rect.fromLTWH(0, 0, 800, 600)); expect(mockCanvas.paints.single.color, colorToPaint); expect(mockContext.children, isEmpty); expect(mockContext.offsets, isEmpty); }); testWidgets('ColoredBox - size, child', (WidgetTester tester) async { const ValueKey<int> key = ValueKey<int>(0); const Widget child = SizedBox.expand(key: key); await tester.pumpWidget(const ColoredBox(color: colorToPaint, child: child)); expect(find.byType(ColoredBox), findsOneWidget); final RenderObject renderColoredBox = tester.renderObject(find.byType(ColoredBox)); final RenderObject renderSizedBox = tester.renderObject(find.byKey(key)); renderColoredBox.paint(mockContext, Offset.zero); expect(mockCanvas.rects.single, const Rect.fromLTWH(0, 0, 800, 600)); expect(mockCanvas.paints.single.color, colorToPaint); expect(mockContext.children.single, renderSizedBox); expect(mockContext.offsets.single, Offset.zero); }); testWidgets('ColoredBox - debugFillProperties', (WidgetTester tester) async { const ColoredBox box = ColoredBox(color: colorToPaint); final DiagnosticPropertiesBuilder properties = DiagnosticPropertiesBuilder(); box.debugFillProperties(properties); expect(properties.properties.first.value, colorToPaint); }); }); testWidgets('Inconsequential golden test', (WidgetTester tester) async { // The test validates the Flutter Gold integration. Any changes to the // golden file can be approved at any time. await tester.pumpWidget(RepaintBoundary( child: Container( color: const Color(0xFFF40125), ), )); await tester.pumpAndSettle(); await expectLater( find.byType(RepaintBoundary), matchesGoldenFile('inconsequential_golden_file.png'), ); }); testWidgets('IgnorePointer ignores pointers', (WidgetTester tester) async { final List<String> logs = <String>[]; Widget target({required bool ignoring}) => Align( alignment: Alignment.topLeft, child: Directionality( textDirection: TextDirection.ltr, child: SizedBox( width: 100, height: 100, child: Listener( onPointerDown: (_) { logs.add('down1'); }, child: MouseRegion( onEnter: (_) { logs.add('enter1'); }, onExit: (_) { logs.add('exit1'); }, cursor: SystemMouseCursors.forbidden, child: Stack( children: <Widget>[ Listener( onPointerDown: (_) { logs.add('down2'); }, child: MouseRegion( cursor: SystemMouseCursors.click, onEnter: (_) { logs.add('enter2'); }, onExit: (_) { logs.add('exit2'); }, ), ), IgnorePointer( ignoring: ignoring, child: Listener( onPointerDown: (_) { logs.add('down3'); }, child: MouseRegion( cursor: SystemMouseCursors.text, onEnter: (_) { logs.add('enter3'); }, onExit: (_) { logs.add('exit3'); }, ), ), ), ], ), ), ), ), ), ); final TestGesture gesture = await tester.createGesture(pointer: 1, kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(200, 200)); await tester.pumpWidget(target(ignoring: true)); expect(logs, isEmpty); await gesture.moveTo(const Offset(50, 50)); expect(logs, <String>['enter1', 'enter2']); logs.clear(); await gesture.down(const Offset(50, 50)); expect(logs, <String>['down2', 'down1']); logs.clear(); await gesture.up(); expect(logs, isEmpty); await tester.pumpWidget(target(ignoring: false)); expect(logs, <String>['exit2', 'enter3']); logs.clear(); await gesture.down(const Offset(50, 50)); expect(logs, <String>['down3', 'down1']); logs.clear(); await gesture.up(); expect(logs, isEmpty); await tester.pumpWidget(target(ignoring: true)); expect(logs, <String>['exit3', 'enter2']); logs.clear(); }); group('IgnorePointer semantics', () { testWidgets('does not change semantics when not ignoring', (WidgetTester tester) async { final UniqueKey key = UniqueKey(); await tester.pumpWidget( MaterialApp( home: IgnorePointer( ignoring: false, child: ElevatedButton( key: key, onPressed: () { }, child: const Text('button'), ), ), ), ); expect( tester.getSemantics(find.byKey(key)), matchesSemantics( label: 'button', hasTapAction: true, isButton: true, isFocusable: true, hasEnabledState: true, isEnabled: true, ), ); }); testWidgets('can toggle the ignoring.', (WidgetTester tester) async { final UniqueKey key1 = UniqueKey(); final UniqueKey key2 = UniqueKey(); final UniqueKey key3 = UniqueKey(); await tester.pumpWidget( MaterialApp( home: TestIgnorePointer( child: Semantics( key: key1, label: '1', onTap: (){ }, container: true, child: Semantics( key: key2, label: '2', onTap: (){ }, container: true, child: Semantics( key: key3, label: '3', onTap: (){ }, container: true, child: const SizedBox(width: 10, height: 10), ), ), ), ), ), ); expect( tester.getSemantics(find.byKey(key1)), matchesSemantics( label: '1', ), ); expect( tester.getSemantics(find.byKey(key2)), matchesSemantics( label: '2', ), ); expect( tester.getSemantics(find.byKey(key3)), matchesSemantics( label: '3', ), ); final TestIgnorePointerState state = tester.state<TestIgnorePointerState>(find.byType(TestIgnorePointer)); state.setIgnore(false); await tester.pump(); expect( tester.getSemantics(find.byKey(key1)), matchesSemantics( label: '1', hasTapAction: true, ), ); expect( tester.getSemantics(find.byKey(key2)), matchesSemantics( label: '2', hasTapAction: true, ), ); expect( tester.getSemantics(find.byKey(key3)), matchesSemantics( label: '3', hasTapAction: true, ), ); state.setIgnore(true); await tester.pump(); expect( tester.getSemantics(find.byKey(key1)), matchesSemantics( label: '1', ), ); expect( tester.getSemantics(find.byKey(key2)), matchesSemantics( label: '2', ), ); expect( tester.getSemantics(find.byKey(key3)), matchesSemantics( label: '3', ), ); state.setIgnore(false); await tester.pump(); expect( tester.getSemantics(find.byKey(key1)), matchesSemantics( label: '1', hasTapAction: true, ), ); expect( tester.getSemantics(find.byKey(key2)), matchesSemantics( label: '2', hasTapAction: true, ), ); expect( tester.getSemantics(find.byKey(key3)), matchesSemantics( label: '3', hasTapAction: true, ), ); }); testWidgets('drops semantics when its ignoringSemantics is true', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final UniqueKey key = UniqueKey(); await tester.pumpWidget( MaterialApp( home: IgnorePointer( ignoringSemantics: true, child: ElevatedButton( key: key, onPressed: () { }, child: const Text('button'), ), ), ), ); expect(semantics, isNot(includesNodeWith(label: 'button'))); semantics.dispose(); }); testWidgets('ignores user interactions', (WidgetTester tester) async { final UniqueKey key = UniqueKey(); await tester.pumpWidget( MaterialApp( home: IgnorePointer( child: ElevatedButton( key: key, onPressed: () { }, child: const Text('button'), ), ), ), ); expect( tester.getSemantics(find.byKey(key)), // Tap action is blocked. matchesSemantics( label: 'button', isButton: true, isFocusable: true, hasEnabledState: true, isEnabled: true, ), ); }); }); testWidgets('AbsorbPointer absorbs pointers', (WidgetTester tester) async { final List<String> logs = <String>[]; Widget target({required bool absorbing}) => Align( alignment: Alignment.topLeft, child: Directionality( textDirection: TextDirection.ltr, child: SizedBox( width: 100, height: 100, child: Listener( onPointerDown: (_) { logs.add('down1'); }, child: MouseRegion( onEnter: (_) { logs.add('enter1'); }, onExit: (_) { logs.add('exit1'); }, cursor: SystemMouseCursors.forbidden, child: Stack( children: <Widget>[ Listener( onPointerDown: (_) { logs.add('down2'); }, child: MouseRegion( cursor: SystemMouseCursors.click, onEnter: (_) { logs.add('enter2'); }, onExit: (_) { logs.add('exit2'); }, ), ), AbsorbPointer( absorbing: absorbing, child: Listener( onPointerDown: (_) { logs.add('down3'); }, child: MouseRegion( cursor: SystemMouseCursors.text, onEnter: (_) { logs.add('enter3'); }, onExit: (_) { logs.add('exit3'); }, ), ), ), ], ), ), ), ), ), ); final TestGesture gesture = await tester.createGesture(pointer: 1, kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(200, 200)); await tester.pumpWidget(target(absorbing: true)); expect(logs, isEmpty); await gesture.moveTo(const Offset(50, 50)); expect(logs, <String>['enter1']); logs.clear(); await gesture.down(const Offset(50, 50)); expect(logs, <String>['down1']); logs.clear(); await gesture.up(); expect(logs, isEmpty); await tester.pumpWidget(target(absorbing: false)); expect(logs, <String>['enter3']); logs.clear(); await gesture.down(const Offset(50, 50)); expect(logs, <String>['down3', 'down1']); logs.clear(); await gesture.up(); expect(logs, isEmpty); await tester.pumpWidget(target(absorbing: true)); expect(logs, <String>['exit3']); logs.clear(); }); testWidgets('Wrap implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const Wrap( spacing: 8.0, // gap between adjacent Text widget runSpacing: 4.0, // gap between lines textDirection: TextDirection.ltr, verticalDirection: VerticalDirection.up, children: <Widget>[ Text('Hamilton'), Text('Lafayette'), Text('Mulligan'), ], ).debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description, unorderedMatches(<dynamic>[ contains('direction: horizontal'), contains('alignment: start'), contains('spacing: 8.0'), contains('runAlignment: start'), contains('runSpacing: 4.0'), contains('crossAxisAlignment: start'), contains('textDirection: ltr'), contains('verticalDirection: up'), ])); }); testWidgets('Row and IgnoreBaseline (control -- with baseline)', (WidgetTester tester) async { await tester.pumpWidget( const Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, textDirection: TextDirection.ltr, children: <Widget>[ Text( 'a', textDirection: TextDirection.ltr, style: TextStyle(fontSize: 128.0, fontFamily: 'FlutterTest'), // places baseline at y=96 ), Text( 'b', textDirection: TextDirection.ltr, style: TextStyle(fontSize: 32.0, fontFamily: 'FlutterTest'), // 24 above baseline, 8 below baseline ), ], ), ); final Offset aPos = tester.getTopLeft(find.text('a')); final Offset bPos = tester.getTopLeft(find.text('b')); expect(aPos.dy, 0.0); expect(bPos.dy, 96.0 - 24.0); }); testWidgets('Row and IgnoreBaseline (with ignored baseline)', (WidgetTester tester) async { await tester.pumpWidget( const Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, textDirection: TextDirection.ltr, children: <Widget>[ IgnoreBaseline( child: Text( 'a', textDirection: TextDirection.ltr, style: TextStyle(fontSize: 128.0, fontFamily: 'FlutterTest'), // places baseline at y=96 ), ), Text( 'b', textDirection: TextDirection.ltr, style: TextStyle(fontSize: 32.0, fontFamily: 'FlutterTest'), // 24 above baseline, 8 below baseline ), ], ), ); final Offset aPos = tester.getTopLeft(find.text('a')); final Offset bPos = tester.getTopLeft(find.text('b')); expect(aPos.dy, 0.0); expect(bPos.dy, 0.0); }); } HitsRenderBox hits(RenderBox renderBox) => HitsRenderBox(renderBox); class HitsRenderBox extends Matcher { const HitsRenderBox(this.renderBox); final RenderBox renderBox; @override Description describe(Description description) => description.add('hit test result contains ').addDescriptionOf(renderBox); @override bool matches(dynamic item, Map<dynamic, dynamic> matchState) { final HitTestResult hitTestResult = item as HitTestResult; return hitTestResult.path.where( (HitTestEntry entry) => entry.target == renderBox, ).isNotEmpty; } } DoesNotHitRenderBox doesNotHit(RenderBox renderBox) => DoesNotHitRenderBox(renderBox); class DoesNotHitRenderBox extends Matcher { const DoesNotHitRenderBox(this.renderBox); final RenderBox renderBox; @override Description describe(Description description) => description.add("hit test result doesn't contain ").addDescriptionOf(renderBox); @override bool matches(dynamic item, Map<dynamic, dynamic> matchState) { final HitTestResult hitTestResult = item as HitTestResult; return hitTestResult.path.where( (HitTestEntry entry) => entry.target == renderBox, ).isEmpty; } } class _MockPaintingContext extends Fake implements PaintingContext { final List<RenderObject> children = <RenderObject>[]; final List<Offset> offsets = <Offset>[]; @override final _MockCanvas canvas = _MockCanvas(); @override void paintChild(RenderObject child, Offset offset) { children.add(child); offsets.add(offset); } } class _MockCanvas extends Fake implements Canvas { final List<Rect> rects = <Rect>[]; final List<Paint> paints = <Paint>[]; bool didPaint = false; @override void drawRect(Rect rect, Paint paint) { rects.add(rect); paints.add(paint); } } class TestIgnorePointer extends StatefulWidget { const TestIgnorePointer({super.key, required this.child}); final Widget child; @override State<StatefulWidget> createState() => TestIgnorePointerState(); } class TestIgnorePointerState extends State<TestIgnorePointer> { bool ignore = true; void setIgnore(bool newIgnore) { setState(() { ignore = newIgnore; }); } @override Widget build(BuildContext context) { return IgnorePointer( ignoring: ignore, child: widget.child, ); } }
flutter/packages/flutter/test/widgets/basic_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/basic_test.dart", "repo_id": "flutter", "token_count": 20635 }
691
// 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. // reduced-test-set: // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'test_border.dart' show TestBorder; final List<String> log = <String>[]; class PathClipper extends CustomClipper<Path> { @override Path getClip(Size size) { log.add('getClip'); return Path() ..addRect(const Rect.fromLTWH(50.0, 50.0, 100.0, 100.0)); } @override bool shouldReclip(PathClipper oldClipper) => false; } class ValueClipper<T> extends CustomClipper<T> { ValueClipper(this.message, this.value); final String message; final T value; @override T getClip(Size size) { log.add(message); return value; } @override bool shouldReclip(ValueClipper<T> oldClipper) { return oldClipper.message != message || oldClipper.value != value; } } class NotifyClipper<T> extends CustomClipper<T> { NotifyClipper({required this.clip}) : super(reclip: clip); final ValueNotifier<T> clip; @override T getClip(Size size) => clip.value; @override bool shouldReclip(NotifyClipper<T> oldClipper) => clip != oldClipper.clip; } void main() { testWidgets('ClipRect with a FittedBox child sized to zero works with semantics', (WidgetTester tester) async { await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: ClipRect( child: FittedBox( child: SizedBox.fromSize( size: Size.zero, child: Semantics( image: true, label: 'Image', ), ), ), ), ), ); expect(find.byType(FittedBox), findsOneWidget); }); testWidgets('ClipRect updates clipBehavior in updateRenderObject', (WidgetTester tester) async { await tester.pumpWidget(const ClipRect()); final RenderClipRect renderClip = tester.allRenderObjects.whereType<RenderClipRect>().first; expect(renderClip.clipBehavior, equals(Clip.hardEdge)); await tester.pumpWidget(const ClipRect(clipBehavior: Clip.antiAlias)); expect(renderClip.clipBehavior, equals(Clip.antiAlias)); await tester.pumpWidget(const ClipRect(clipBehavior: Clip.none)); expect(renderClip.clipBehavior, equals(Clip.none)); }); test('ClipRRect constructs with the right default values', () { const ClipRRect clipRRect = ClipRRect(); expect(clipRRect.clipBehavior, equals(Clip.antiAlias)); expect(clipRRect.borderRadius, equals(BorderRadius.zero)); }); testWidgets('ClipRRect updates clipBehavior in updateRenderObject', (WidgetTester tester) async { await tester.pumpWidget(const ClipRRect()); final RenderClipRRect renderClip = tester.allRenderObjects.whereType<RenderClipRRect>().first; expect(renderClip.clipBehavior, equals(Clip.antiAlias)); await tester.pumpWidget(const ClipRRect(clipBehavior: Clip.hardEdge)); expect(renderClip.clipBehavior, equals(Clip.hardEdge)); await tester.pumpWidget(const ClipRRect(clipBehavior: Clip.none)); expect(renderClip.clipBehavior, equals(Clip.none)); }); testWidgets('ClipOval updates clipBehavior in updateRenderObject', (WidgetTester tester) async { await tester.pumpWidget(const ClipOval()); final RenderClipOval renderClip = tester.allRenderObjects.whereType<RenderClipOval>().first; expect(renderClip.clipBehavior, equals(Clip.antiAlias)); await tester.pumpWidget(const ClipOval(clipBehavior: Clip.hardEdge)); expect(renderClip.clipBehavior, equals(Clip.hardEdge)); await tester.pumpWidget(const ClipOval(clipBehavior: Clip.none)); expect(renderClip.clipBehavior, equals(Clip.none)); }); testWidgets('ClipPath updates clipBehavior in updateRenderObject', (WidgetTester tester) async { await tester.pumpWidget(const ClipPath()); final RenderClipPath renderClip = tester.allRenderObjects.whereType<RenderClipPath>().first; expect(renderClip.clipBehavior, equals(Clip.antiAlias)); await tester.pumpWidget(const ClipPath(clipBehavior: Clip.hardEdge)); expect(renderClip.clipBehavior, equals(Clip.hardEdge)); await tester.pumpWidget(const ClipPath(clipBehavior: Clip.none)); expect(renderClip.clipBehavior, equals(Clip.none)); }); testWidgets('ClipPath', (WidgetTester tester) async { await tester.pumpWidget( ClipPath( clipper: PathClipper(), child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { log.add('tap'); }, ), ), ); expect(log, equals(<String>['getClip'])); await tester.tapAt(const Offset(10.0, 10.0)); expect(log, equals(<String>['getClip'])); log.clear(); await tester.tapAt(const Offset(100.0, 100.0)); expect(log, equals(<String>['tap'])); log.clear(); }); testWidgets('ClipOval', (WidgetTester tester) async { await tester.pumpWidget( ClipOval( child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { log.add('tap'); }, ), ), ); expect(log, equals(<String>[])); await tester.tapAt(const Offset(10.0, 10.0)); expect(log, equals(<String>[])); log.clear(); await tester.tapAt(const Offset(400.0, 300.0)); expect(log, equals(<String>['tap'])); log.clear(); }); testWidgets('Transparent ClipOval hit test', (WidgetTester tester) async { await tester.pumpWidget( Opacity( opacity: 0.0, child: ClipOval( child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { log.add('tap'); }, ), ), ), ); expect(log, equals(<String>[])); await tester.tapAt(const Offset(10.0, 10.0)); expect(log, equals(<String>[])); log.clear(); await tester.tapAt(const Offset(400.0, 300.0)); expect(log, equals(<String>['tap'])); log.clear(); }); testWidgets('ClipRect', (WidgetTester tester) async { await tester.pumpWidget( Align( alignment: Alignment.topLeft, child: SizedBox( width: 100.0, height: 100.0, child: ClipRect( clipper: ValueClipper<Rect>('a', const Rect.fromLTWH(5.0, 5.0, 10.0, 10.0)), child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { log.add('tap'); }, ), ), ), ), ); expect(log, equals(<String>['a'])); await tester.tapAt(const Offset(10.0, 10.0)); expect(log, equals(<String>['a', 'tap'])); await tester.tapAt(const Offset(100.0, 100.0)); expect(log, equals(<String>['a', 'tap'])); await tester.pumpWidget( Align( alignment: Alignment.topLeft, child: SizedBox( width: 100.0, height: 100.0, child: ClipRect( clipper: ValueClipper<Rect>('a', const Rect.fromLTWH(5.0, 5.0, 10.0, 10.0)), child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { log.add('tap'); }, ), ), ), ), ); expect(log, equals(<String>['a', 'tap'])); await tester.pumpWidget( Align( alignment: Alignment.topLeft, child: SizedBox( width: 200.0, height: 200.0, child: ClipRect( clipper: ValueClipper<Rect>('a', const Rect.fromLTWH(5.0, 5.0, 10.0, 10.0)), child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { log.add('tap'); }, ), ), ), ), ); expect(log, equals(<String>['a', 'tap', 'a'])); await tester.pumpWidget( Align( alignment: Alignment.topLeft, child: SizedBox( width: 200.0, height: 200.0, child: ClipRect( clipper: ValueClipper<Rect>('a', const Rect.fromLTWH(5.0, 5.0, 10.0, 10.0)), child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { log.add('tap'); }, ), ), ), ), ); expect(log, equals(<String>['a', 'tap', 'a'])); await tester.pumpWidget( Align( alignment: Alignment.topLeft, child: SizedBox( width: 200.0, height: 200.0, child: ClipRect( clipper: ValueClipper<Rect>('b', const Rect.fromLTWH(5.0, 5.0, 10.0, 10.0)), child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { log.add('tap'); }, ), ), ), ), ); expect(log, equals(<String>['a', 'tap', 'a', 'b'])); await tester.pumpWidget( Align( alignment: Alignment.topLeft, child: SizedBox( width: 200.0, height: 200.0, child: ClipRect( clipper: ValueClipper<Rect>('c', const Rect.fromLTWH(25.0, 25.0, 10.0, 10.0)), child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { log.add('tap'); }, ), ), ), ), ); expect(log, equals(<String>['a', 'tap', 'a', 'b', 'c'])); await tester.tapAt(const Offset(30.0, 30.0)); expect(log, equals(<String>['a', 'tap', 'a', 'b', 'c', 'tap'])); await tester.tapAt(const Offset(100.0, 100.0)); expect(log, equals(<String>['a', 'tap', 'a', 'b', 'c', 'tap'])); log.clear(); }); testWidgets('debugPaintSizeEnabled', (WidgetTester tester) async { await tester.pumpWidget( const ClipRect( child: Placeholder(), ), ); expect(tester.renderObject(find.byType(ClipRect)).paint, paints ..save() ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0)) ..save() ..path() // Placeholder ..restore() ..restore(), ); debugPaintSizeEnabled = true; expect(tester.renderObject(find.byType(ClipRect)).debugPaint, paints ..rect(rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0)) ..paragraph(), ); debugPaintSizeEnabled = false; }); testWidgets('ClipRect painting', (WidgetTester tester) async { await tester.pumpWidget( Center( child: RepaintBoundary( child: ColoredBox( color: Colors.white, child: Padding( padding: const EdgeInsets.all(100.0), child: SizedBox( height: 100.0, width: 100.0, child: Transform.rotate( angle: 1.0, // radians child: ClipRect( child: ColoredBox( color: Colors.red, child: ColoredBox( color: Colors.white, child: RepaintBoundary( child: Center( child: Container( color: Colors.black, height: 10.0, width: 10.0, ), ), ), ), ), ), ), ), ), ), ), ), ); await expectLater( find.byType(RepaintBoundary).first, matchesGoldenFile('clip.ClipRect.png'), ); }); testWidgets('ClipRect save, overlay, and antialiasing', (WidgetTester tester) async { await tester.pumpWidget( RepaintBoundary( child: Stack( textDirection: TextDirection.ltr, children: <Widget>[ Positioned( top: 0.0, left: 0.0, width: 100.0, height: 100.0, child: ClipRect( child: Container( color: Colors.blue, ), ), ), Positioned( top: 50.0, left: 50.0, width: 100.0, height: 100.0, child: Transform.rotate( angle: 1.0, child: Container( color: Colors.red, ), ), ), ], ), ), ); await expectLater( find.byType(RepaintBoundary).first, matchesGoldenFile('clip.ClipRectOverlay.png'), ); }); testWidgets('ClipRRect painting', (WidgetTester tester) async { await tester.pumpWidget( Center( child: RepaintBoundary( child: ColoredBox( color: Colors.white, child: Padding( padding: const EdgeInsets.all(100.0), child: SizedBox( height: 100.0, width: 100.0, child: Transform.rotate( angle: 1.0, // radians child: ClipRRect( borderRadius: const BorderRadius.only( topLeft: Radius.elliptical(10.0, 20.0), topRight: Radius.elliptical(5.0, 30.0), bottomLeft: Radius.elliptical(2.5, 12.0), bottomRight: Radius.elliptical(15.0, 6.0), ), child: ColoredBox( color: Colors.red, child: ColoredBox( color: Colors.white, child: RepaintBoundary( child: Center( child: Container( color: Colors.black, height: 10.0, width: 10.0, ), ), ), ), ), ), ), ), ), ), ), ), ); await expectLater( find.byType(RepaintBoundary).first, matchesGoldenFile('clip.ClipRRect.png'), ); }); testWidgets('ClipOval painting', (WidgetTester tester) async { await tester.pumpWidget( Center( child: RepaintBoundary( child: ColoredBox( color: Colors.white, child: Padding( padding: const EdgeInsets.all(100.0), child: SizedBox( height: 100.0, width: 100.0, child: Transform.rotate( angle: 1.0, // radians child: ClipOval( child: ColoredBox( color: Colors.red, child: ColoredBox( color: Colors.white, child: RepaintBoundary( child: Center( child: Container( color: Colors.black, height: 10.0, width: 10.0, ), ), ), ), ), ), ), ), ), ), ), ), ); await expectLater( find.byType(RepaintBoundary).first, matchesGoldenFile('clip.ClipOval.png'), ); }); testWidgets('ClipPath painting', (WidgetTester tester) async { await tester.pumpWidget( Center( child: RepaintBoundary( child: ColoredBox( color: Colors.white, child: Padding( padding: const EdgeInsets.all(100.0), child: SizedBox( height: 100.0, width: 100.0, child: Transform.rotate( angle: 1.0, // radians child: ClipPath( clipper: const ShapeBorderClipper( shape: BeveledRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(20.0)), ), ), child: ColoredBox( color: Colors.red, child: ColoredBox( color: Colors.white, child: RepaintBoundary( child: Center( child: Container( color: Colors.black, height: 10.0, width: 10.0, ), ), ), ), ), ), ), ), ), ), ), ), ); await expectLater( find.byType(RepaintBoundary).first, matchesGoldenFile('clip.ClipPath.png'), ); }); Center genPhysicalModel(Clip clipBehavior) { return Center( child: RepaintBoundary( child: ColoredBox( color: Colors.white, child: Padding( padding: const EdgeInsets.all(100.0), child: SizedBox( height: 100.0, width: 100.0, child: Transform.rotate( angle: 1.0, // radians child: PhysicalModel( borderRadius: const BorderRadius.all(Radius.circular(20.0)), color: Colors.red, clipBehavior: clipBehavior, child: ColoredBox( color: Colors.white, child: RepaintBoundary( child: Center( child: Container( color: Colors.black, height: 10.0, width: 10.0, ), ), ), ), ), ), ), ), ), ), ); } testWidgets('PhysicalModel painting with Clip.antiAlias', (WidgetTester tester) async { await tester.pumpWidget(genPhysicalModel(Clip.antiAlias)); await expectLater( find.byType(RepaintBoundary).first, matchesGoldenFile('clip.PhysicalModel.antiAlias.png'), ); }); testWidgets('PhysicalModel painting with Clip.hardEdge', (WidgetTester tester) async { await tester.pumpWidget(genPhysicalModel(Clip.hardEdge)); await expectLater( find.byType(RepaintBoundary).first, matchesGoldenFile('clip.PhysicalModel.hardEdge.png'), ); }); // There will be bleeding edges on the rect edges, but there shouldn't be any bleeding edges on the // round corners. testWidgets('PhysicalModel painting with Clip.antiAliasWithSaveLayer', (WidgetTester tester) async { await tester.pumpWidget(genPhysicalModel(Clip.antiAliasWithSaveLayer)); await expectLater( find.byType(RepaintBoundary).first, matchesGoldenFile('clip.PhysicalModel.antiAliasWithSaveLayer.png'), ); }); testWidgets('Default PhysicalModel painting', (WidgetTester tester) async { await tester.pumpWidget( Center( child: RepaintBoundary( child: ColoredBox( color: Colors.white, child: Padding( padding: const EdgeInsets.all(100.0), child: SizedBox( height: 100.0, width: 100.0, child: Transform.rotate( angle: 1.0, // radians child: PhysicalModel( borderRadius: const BorderRadius.all(Radius.circular(20.0)), color: Colors.red, child: ColoredBox( color: Colors.white, child: RepaintBoundary( child: Center( child: Container( color: Colors.black, height: 10.0, width: 10.0, ), ), ), ), ), ), ), ), ), ), ), ); await expectLater( find.byType(RepaintBoundary).first, matchesGoldenFile('clip.PhysicalModel.default.png'), ); }); Center genPhysicalShape(Clip clipBehavior) { return Center( child: RepaintBoundary( child: ColoredBox( color: Colors.white, child: Padding( padding: const EdgeInsets.all(100.0), child: SizedBox( height: 100.0, width: 100.0, child: Transform.rotate( angle: 1.0, // radians child: PhysicalShape( clipper: const ShapeBorderClipper( shape: BeveledRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(20.0)), ), ), clipBehavior: clipBehavior, color: Colors.red, child: ColoredBox( color: Colors.white, child: RepaintBoundary( child: Center( child: Container( color: Colors.black, height: 10.0, width: 10.0, ), ), ), ), ), ), ), ), ), ), ); } testWidgets('PhysicalShape painting with Clip.antiAlias', (WidgetTester tester) async { await tester.pumpWidget(genPhysicalShape(Clip.antiAlias)); await expectLater( find.byType(RepaintBoundary).first, matchesGoldenFile('clip.PhysicalShape.antiAlias.png'), ); }); testWidgets('PhysicalShape painting with Clip.hardEdge', (WidgetTester tester) async { await tester.pumpWidget(genPhysicalShape(Clip.hardEdge)); await expectLater( find.byType(RepaintBoundary).first, matchesGoldenFile('clip.PhysicalShape.hardEdge.png'), ); }); testWidgets('PhysicalShape painting with Clip.antiAliasWithSaveLayer', (WidgetTester tester) async { await tester.pumpWidget(genPhysicalShape(Clip.antiAliasWithSaveLayer)); await expectLater( find.byType(RepaintBoundary).first, matchesGoldenFile('clip.PhysicalShape.antiAliasWithSaveLayer.png'), ); }); testWidgets('PhysicalShape painting', (WidgetTester tester) async { await tester.pumpWidget( Center( child: RepaintBoundary( child: ColoredBox( color: Colors.white, child: Padding( padding: const EdgeInsets.all(100.0), child: SizedBox( height: 100.0, width: 100.0, child: Transform.rotate( angle: 1.0, // radians child: PhysicalShape( clipper: const ShapeBorderClipper( shape: BeveledRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(20.0)), ), ), color: Colors.red, child: ColoredBox( color: Colors.white, child: RepaintBoundary( child: Center( child: Container( color: Colors.black, height: 10.0, width: 10.0, ), ), ), ), ), ), ), ), ), ), ), ); await expectLater( find.byType(RepaintBoundary).first, matchesGoldenFile('clip.PhysicalShape.default.png'), ); }); testWidgets('ClipPath.shape', (WidgetTester tester) async { final List<String> logs = <String>[]; final ShapeBorder shape = TestBorder((String message) { logs.add(message); }); Widget buildClipPath() { return ClipPath.shape( shape: shape, child: const SizedBox(width: 100.0, height: 100.0), ); } final Widget clipPath = buildClipPath(); // verify that a regular clip works as one would expect logs.add('--0'); await tester.pumpWidget(clipPath); // verify that pumping again doesn't recompute the clip // even though the widget itself is new (the shape doesn't change identity) logs.add('--1'); await tester.pumpWidget(buildClipPath()); // verify that ClipPath passes the TextDirection on to its shape logs.add('--2'); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: clipPath, )); // verify that changing the text direction from LTR to RTL has an effect // even though the widget itself is identical logs.add('--3'); await tester.pumpWidget(Directionality( textDirection: TextDirection.rtl, child: clipPath, )); // verify that pumping again with a text direction has no effect logs.add('--4'); await tester.pumpWidget(Directionality( textDirection: TextDirection.rtl, child: buildClipPath(), )); logs.add('--5'); // verify that changing the text direction and the widget at the same time // works as expected await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: clipPath, )); expect(logs, <String>[ '--0', 'getOuterPath Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) null', '--1', '--2', 'getOuterPath Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) TextDirection.ltr', '--3', 'getOuterPath Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) TextDirection.rtl', '--4', '--5', 'getOuterPath Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) TextDirection.ltr', ]); }); testWidgets('CustomClipper reclips when notified', (WidgetTester tester) async { final ValueNotifier<Rect> clip = ValueNotifier<Rect>(const Rect.fromLTWH(50.0, 50.0, 100.0, 100.0)); addTearDown(clip.dispose); await tester.pumpWidget( ClipRect( clipper: NotifyClipper<Rect>(clip: clip), child: const Placeholder(), ), ); expect(tester.renderObject(find.byType(ClipRect)).paint, paints ..save() ..clipRect(rect: const Rect.fromLTWH(50.0, 50.0, 100.0, 100.0)) ..save() ..path() // Placeholder ..restore() ..restore(), ); expect(tester.renderObject(find.byType(ClipRect)).debugNeedsPaint, isFalse); clip.value = const Rect.fromLTWH(50.0, 50.0, 150.0, 100.0); expect(tester.renderObject(find.byType(ClipRect)).debugNeedsPaint, isTrue); expect(tester.renderObject(find.byType(ClipRect)).paint, paints ..save() ..clipRect(rect: const Rect.fromLTWH(50.0, 50.0, 150.0, 100.0)) ..save() ..path() // Placeholder ..restore() ..restore(), ); }); testWidgets('ClipRRect supports BorderRadiusDirectional', (WidgetTester tester) async { const Radius startRadius = Radius.circular(15.0); const Radius endRadius = Radius.circular(30.0); Widget buildClipRRect(TextDirection textDirection) { return Directionality( textDirection: textDirection, child: const ClipRRect( borderRadius: BorderRadiusDirectional.horizontal( start: startRadius, end: endRadius, ), ), ); } for (final TextDirection textDirection in TextDirection.values) { await tester.pumpWidget(buildClipRRect(textDirection)); final RenderClipRRect renderClip = tester.allRenderObjects.whereType<RenderClipRRect>().first; final bool isRtl = textDirection == TextDirection.rtl; expect(renderClip.borderRadius.resolve(textDirection).topLeft, isRtl ? endRadius : startRadius); expect(renderClip.borderRadius.resolve(textDirection).topRight, isRtl ? startRadius : endRadius); expect(renderClip.borderRadius.resolve(textDirection).bottomLeft, isRtl ? endRadius : startRadius); expect(renderClip.borderRadius.resolve(textDirection).bottomRight, isRtl ? startRadius : endRadius); } }); testWidgets('ClipRRect is direction-aware', (WidgetTester tester) async { const Radius startRadius = Radius.circular(15.0); const Radius endRadius = Radius.circular(30.0); TextDirection textDirection = TextDirection.ltr; Widget buildClipRRect(TextDirection textDirection) { return Directionality( textDirection: textDirection, child: const ClipRRect( borderRadius: BorderRadiusDirectional.horizontal( start: startRadius, end: endRadius, ), ), ); } Widget buildStatefulClipRRect() { return StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Directionality( textDirection: textDirection, child: SizedBox( width: 100.0, height: 100.0, child: ClipRRect( borderRadius: const BorderRadiusDirectional.horizontal( start: startRadius, end: endRadius, ), child: GestureDetector( onTap: () { setState(() { textDirection = TextDirection.rtl; }); }, ), ), ), ); }, ); } for (final TextDirection textDirection in TextDirection.values) { await tester.pumpWidget(buildClipRRect(textDirection)); final RenderClipRRect renderClip = tester.allRenderObjects.whereType<RenderClipRRect>().first; final bool isRtl = textDirection == TextDirection.rtl; expect(renderClip.textDirection, isRtl ? TextDirection.rtl : TextDirection.ltr); } await tester.pumpWidget(buildStatefulClipRRect()); final RenderClipRRect renderClip = tester.allRenderObjects.whereType<RenderClipRRect>().first; expect(renderClip.textDirection, TextDirection.ltr); await tester.tapAt(Offset.zero); await tester.pump(); expect(renderClip.textDirection, TextDirection.rtl); }); }
flutter/packages/flutter/test/widgets/clip_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/clip_test.dart", "repo_id": "flutter", "token_count": 15754 }
692
// 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:typed_data'; import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../impeller_test_helpers.dart'; const double _crispText = 100.0; // this font size is selected to avoid needing any antialiasing. const String _expText = 'Éxp'; // renders in the test font as: // ######## // ######## // ######## // ######## // // ÉÉÉÉxxxxpppp void main() { testWidgets('Default background', (WidgetTester tester) async { await tester.pumpWidget(const Align( alignment: Alignment.topLeft, child: Text(_expText, textDirection: TextDirection.ltr, style: TextStyle(color: Color(0xFF345678), fontSize: _crispText))), ); await _expectColors( tester, find.byType(Align), <Color>{ const Color(0x00000000), const Color(0xFF345678) }, <Offset, Color>{ Offset.zero: const Color(0xFF345678), // the text const Offset(10, 10): const Color(0xFF345678), // the text const Offset(50, 95): const Color(0x00000000), // the background (under the É) const Offset(250, 50): const Color(0x00000000), // the text (above the p) const Offset(250, 95): const Color(0xFF345678), // the text (the p) const Offset(400, 400): const Color(0x00000000), // the background const Offset(799, 599): const Color(0x00000000), // the background }, ); }, skip: !canCaptureImage || impellerEnabled); // [intended] Test relies on captureImage, which is not supported on web currently. testWidgets('Default text color', (WidgetTester tester) async { await tester.pumpWidget(const ColoredBox( color: Color(0xFFABCDEF), child: Align( alignment: Alignment.topLeft, child: Text('Éxp', textDirection: TextDirection.ltr, style: TextStyle(fontSize: _crispText)), ), ), ); await _expectColors( tester, find.byType(Align), <Color>{ const Color(0xFFABCDEF), const Color(0xFFFFFFFF) }, <Offset, Color>{ Offset.zero: const Color(0xFFFFFFFF), // the text const Offset(10, 10): const Color(0xFFFFFFFF), // the text const Offset(50, 95): const Color(0xFFABCDEF), // the background (under the É) const Offset(250, 50): const Color(0xFFABCDEF), // the text (above the p) const Offset(250, 95): const Color(0xFFFFFFFF), // the text (the p) const Offset(400, 400): const Color(0xFFABCDEF), // the background const Offset(799, 599): const Color(0xFFABCDEF), // the background }, ); }, skip: !canCaptureImage || impellerEnabled); // [intended] Test relies on captureImage, which is not supported on web currently. testWidgets('Default text selection color', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); final OverlayEntry overlayEntry = OverlayEntry( builder: (BuildContext context) => SelectableRegion( focusNode: focusNode, selectionControls: emptyTextSelectionControls, child: Align( key: key, alignment: Alignment.topLeft, child: const Text('Éxp', textDirection: TextDirection.ltr, style: TextStyle(fontSize: _crispText, color: Color(0xFF000000))), ), ), ); addTearDown(() => overlayEntry..remove()..dispose()); await tester.pumpWidget( ColoredBox( color: const Color(0xFFFFFFFF), child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: Overlay( initialEntries: <OverlayEntry>[overlayEntry], ), ), ), ), ); await tester.pumpAndSettle(); await _expectColors( tester, find.byType(Align), <Color>{ const Color(0xFFFFFFFF), const Color(0xFF000000) }, ); // fake a "select all" event to select the text Actions.invoke(key.currentContext!, const SelectAllTextIntent(SelectionChangedCause.keyboard)); await tester.pump(); await _expectColors( tester, find.byType(Align), <Color>{ const Color(0xFFFFFFFF), const Color(0xFF000000), const Color(0xFFBFBFBF) }, // 0x80808080 blended with 0xFFFFFFFF <Offset, Color>{ Offset.zero: const Color(0xFF000000), // the selected text const Offset(10, 10): const Color(0xFF000000), // the selected text const Offset(50, 95): const Color(0xFFBFBFBF), // the selected background (under the É) const Offset(250, 50): const Color(0xFFBFBFBF), // the selected background (above the p) const Offset(250, 95): const Color(0xFF000000), // the selected text (the p) const Offset(400, 400): const Color(0xFFFFFFFF), // the background const Offset(799, 599): const Color(0xFFFFFFFF), // the background }, ); }, skip: !canCaptureImage || impellerEnabled); // [intended] Test relies on captureImage, which is not supported on web currently. } Color _getPixel(ByteData bytes, int x, int y, int width) { final int offset = (x + y * width) * 4; return Color.fromARGB( bytes.getUint8(offset + 3), bytes.getUint8(offset + 0), bytes.getUint8(offset + 1), bytes.getUint8(offset + 2), ); } Future<void> _expectColors(WidgetTester tester, Finder finder, Set<Color> allowedColors, [ Map<Offset, Color>? spotChecks ]) async { final TestWidgetsFlutterBinding binding = tester.binding; final ui.Image image = (await binding.runAsync<ui.Image>(() => captureImage(finder.evaluate().single)))!; addTearDown(image.dispose); final ByteData bytes = (await binding.runAsync<ByteData?>(() => image.toByteData(format: ui.ImageByteFormat.rawStraightRgba)))!; final Set<int> actualColorValues = <int>{}; for (int offset = 0; offset < bytes.lengthInBytes; offset += 4) { actualColorValues.add((bytes.getUint8(offset + 3) << 24) + (bytes.getUint8(offset + 0) << 16) + (bytes.getUint8(offset + 1) << 8) + (bytes.getUint8(offset + 2))); } final Set<Color> actualColors = actualColorValues.map((int value) => Color(value)).toSet(); expect(actualColors, allowedColors); spotChecks?.forEach((Offset position, Color expected) { assert(position.dx.round() >= 0); assert(position.dx.round() < image.width); assert(position.dy.round() >= 0); assert(position.dy.round() < image.height); final Offset precisePosition = position * tester.view.devicePixelRatio; final Color actual = _getPixel(bytes, precisePosition.dx.round(), precisePosition.dy.round(), image.width); expect(actual, expected, reason: 'Pixel at $position is $actual but expected $expected.'); }); }
flutter/packages/flutter/test/widgets/default_colors_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/default_colors_test.dart", "repo_id": "flutter", "token_count": 2701 }
693
// 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 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/src/foundation/constants.dart'; import 'package:flutter_test/flutter_test.dart'; class _TestSliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate { _TestSliverPersistentHeaderDelegate({ required this.minExtent, required this.maxExtent, required this.child, this.vsync = const TestVSync(), }); final Widget child; @override final double maxExtent; @override final double minExtent; @override final TickerProvider? vsync; @override final PersistentHeaderShowOnScreenConfiguration showOnScreenConfiguration = const PersistentHeaderShowOnScreenConfiguration(); @override Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) => child; @override bool shouldRebuild(_TestSliverPersistentHeaderDelegate oldDelegate) => true; } void main() { const TextStyle textStyle = TextStyle(); const Color cursorColor = Color.fromARGB(0xFF, 0xFF, 0x00, 0x00); late TextEditingController controller; late FocusNode focusNode; setUp(() { controller = TextEditingController(); focusNode = FocusNode(); }); tearDown(() { controller.dispose(); focusNode.dispose(); }); testWidgets('tapping on a partly visible editable brings it fully on screen', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget(MaterialApp( home: Center( child: SizedBox( height: 300.0, child: ListView( controller: scrollController, children: <Widget>[ EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), const SizedBox( height: 350.0, ), ], ), ), ), )); // Scroll the EditableText half off screen. final RenderBox render = tester.renderObject(find.byType(EditableText)); scrollController.jumpTo(render.size.height / 2); await tester.pumpAndSettle(); expect(scrollController.offset, render.size.height / 2); await tester.showKeyboard(find.byType(EditableText)); await tester.pumpAndSettle(); expect(scrollController.offset, 0.0); }); testWidgets('tapping on a partly visible editable brings it fully on screen with scrollInsets', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget(MaterialApp( home: Center( child: SizedBox( height: 300.0, child: ListView( controller: scrollController, children: <Widget>[ const SizedBox( height: 200.0, ), EditableText( backgroundCursorColor: Colors.grey, scrollPadding: const EdgeInsets.all(50.0), controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), const SizedBox( height: 850.0, ), ], ), ), ), )); // Scroll the EditableText half off screen. final RenderBox render = tester.renderObject(find.byType(EditableText)); scrollController.jumpTo(200 + render.size.height / 2); await tester.pumpAndSettle(); expect(scrollController.offset, 200 + render.size.height / 2); await tester.showKeyboard(find.byType(EditableText)); await tester.pumpAndSettle(); // Container above the text is 200 in height, the scrollInsets are 50 // Tolerance of 5 units (The actual value was 152.0 in the current tests instead of 150.0) expect(scrollController.offset, lessThan(200.0 - 50.0 + 5.0)); expect(scrollController.offset, greaterThan(200.0 - 50.0 - 5.0)); }); testWidgets('editable comes back on screen when entering text while it is off-screen', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(initialScrollOffset: 100.0); addTearDown(scrollController.dispose); await tester.pumpWidget(MaterialApp( home: Center( child: SizedBox( height: 300.0, child: ListView( controller: scrollController, children: <Widget>[ const SizedBox( height: 350.0, ), EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), const SizedBox( height: 350.0, ), ], ), ), ), )); // Focus the EditableText and scroll it off screen. await tester.showKeyboard(find.byType(EditableText)); await tester.pumpAndSettle(); expect(focusNode.hasFocus, isTrue); scrollController.jumpTo(0.0); await tester.pumpAndSettle(); expect(scrollController.offset, 0.0); expect(find.byType(EditableText), findsNothing); // Entering text brings it back on screen. tester.testTextInput.enterText('Hello'); await tester.pumpAndSettle(); expect(scrollController.offset, greaterThan(0.0)); expect(find.byType(EditableText), findsOneWidget); }); testWidgets('entering text does not scroll when scrollPhysics.allowImplicitScrolling = false', (WidgetTester tester) async { // regression test for https://github.com/flutter/flutter/issues/19523 final ScrollController scrollController = ScrollController(initialScrollOffset: 100.0); addTearDown(scrollController.dispose); await tester.pumpWidget(MaterialApp( home: Center( child: SizedBox( height: 300.0, child: ListView( physics: const NoImplicitScrollPhysics(), controller: scrollController, children: <Widget>[ const SizedBox( height: 350.0, ), EditableText( backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), const SizedBox( height: 350.0, ), ], ), ), ), )); // Focus the EditableText and scroll it off screen. await tester.showKeyboard(find.byType(EditableText)); await tester.pumpAndSettle(); expect(focusNode.hasFocus, isTrue); scrollController.jumpTo(0.0); await tester.pumpAndSettle(); expect(scrollController.offset, 0.0); expect(find.byType(EditableText), findsNothing); // Entering text brings it not back on screen. tester.testTextInput.enterText('Hello'); await tester.pumpAndSettle(); expect(scrollController.offset, 0.0); expect(find.byType(EditableText), findsNothing); }); testWidgets('entering text does not scroll a surrounding PageView', (WidgetTester tester) async { // regression test for https://github.com/flutter/flutter/issues/19523 final PageController pageController = PageController(initialPage: 1); addTearDown(pageController.dispose); await tester.pumpWidget( MaterialApp( home: MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Material( child: PageView( controller: pageController, children: <Widget>[ Container( color: Colors.red, ), ColoredBox( color: Colors.green, child: TextField( controller: controller, ), ), Container( color: Colors.red, ), ], ), ), ), ), ), ); await tester.showKeyboard(find.byType(EditableText)); await tester.pumpAndSettle(); expect(controller.text, ''); tester.testTextInput.enterText('H'); final int frames = await tester.pumpAndSettle(); // The text input should not trigger any animations, which would indicate // that the surrounding PageView is incorrectly scrolling back-and-forth. expect(frames, 1); expect(controller.text, 'H'); }); testWidgets('focused multi-line editable scrolls caret back into view when typing', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); controller.text = "Start${'\n' * 39}End"; await tester.pumpWidget(MaterialApp( home: Center( child: SizedBox( height: 300.0, child: ListView( controller: scrollController, children: <Widget>[ EditableText( backgroundCursorColor: Colors.grey, maxLines: null, // multiline controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ], ), ), ), )); // Bring keyboard up and verify that end of EditableText is not on screen. await tester.showKeyboard(find.byType(EditableText)); await tester.pumpAndSettle(); scrollController.jumpTo(0.0); await tester.pumpAndSettle(); final RenderBox render = tester.renderObject(find.byType(EditableText)); expect(render.size.height, greaterThan(500.0)); expect(scrollController.offset, 0.0); // Enter text at end, which is off-screen. final String textToEnter = '${controller.text} HELLO'; tester.testTextInput.updateEditingValue(TextEditingValue( text: textToEnter, selection: TextSelection.collapsed(offset: textToEnter.length), )); await tester.pumpAndSettle(); // Caret scrolls into view. expect(find.byType(EditableText), findsOneWidget); expect(render.size.height, greaterThan(500.0)); expect(scrollController.offset, greaterThan(0.0)); }); testWidgets('focused multi-line editable does not scroll to old position when non-collapsed selection set', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); final String text = "Start${'\n' * 39}End"; controller.value = TextEditingValue(text: text, selection: TextSelection.collapsed(offset: text.length - 3)); await tester.pumpWidget(MaterialApp( home: Center( child: SizedBox( height: 300.0, child: ListView( controller: scrollController, children: <Widget>[ EditableText( backgroundCursorColor: Colors.grey, maxLines: null, // multiline controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ], ), ), ), )); // Bring keyboard up and verify that end of EditableText is not on screen. await tester.showKeyboard(find.byType(EditableText)); await tester.pumpAndSettle(); scrollController.jumpTo(0.0); await tester.pumpAndSettle(); final RenderBox render = tester.renderObject(find.byType(EditableText)); expect(render.size.height, greaterThan(500.0)); expect(scrollController.offset, 0.0); // Change selection to non-collapsed so that cursor isn't shown // and the location requires a bit of scroll. tester.testTextInput.updateEditingValue(TextEditingValue( text: text, selection: const TextSelection(baseOffset: 26, extentOffset: 27), )); await tester.pumpAndSettle(); // Selection extent scrolls into view. expect(find.byType(EditableText), findsOneWidget); expect(render.size.height, greaterThan(500.0)); expect(scrollController.offset, 28.0); }); testWidgets('scrolls into view with scrollInserts after the keyboard pops up', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); const Key container = Key('container'); await tester.pumpWidget(MaterialApp( home: Align( alignment: Alignment.bottomCenter, child: SizedBox( height: 300.0, child: ListView( controller: scrollController, children: <Widget>[ const SizedBox( key: container, height: 200.0, ), EditableText( backgroundCursorColor: Colors.grey, scrollPadding: const EdgeInsets.only(bottom: 300.0), controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), const SizedBox( height: 400.0, ), ], ), ), ), )); expect(scrollController.offset, 0.0); await tester.showKeyboard(find.byType(EditableText)); await tester.pumpAndSettle(); expect(scrollController.offset, greaterThan(0.0)); expect(find.byKey(container), findsNothing); }); testWidgets( 'A pinned persistent header should not scroll when its descendant EditableText gains focus', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/25507. final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); const Key headerKey = Key('header'); await tester.pumpWidget( MaterialApp( home: Center( child: SizedBox( height: 600.0, width: 600.0, child: CustomScrollView( controller: scrollController, slivers: List<Widget>.generate(50, (int i) { return i == 10 ? SliverPersistentHeader( pinned: true, delegate: _TestSliverPersistentHeaderDelegate( minExtent: 50, maxExtent: 50, child: Container( alignment: Alignment.topCenter, child: EditableText( key: headerKey, backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ) : SliverToBoxAdapter( child: SizedBox( height: 100.0, child: Text('Tile $i'), ), ); }), ), ), ), ), ); // The persistent header should now be pinned at the top. scrollController.jumpTo(100.0 * 15); await tester.pumpAndSettle(); expect(scrollController.offset, 100.0 * 15); focusNode.requestFocus(); await tester.pumpAndSettle(); // The scroll offset should remain the same. expect(scrollController.offset, 100.0 * 15); }, ); testWidgets( 'A pinned persistent header should not scroll when its descendant EditableText gains focus (no animation)', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/25507. final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); const Key headerKey = Key('header'); await tester.pumpWidget( MaterialApp( home: Center( child: SizedBox( height: 600.0, width: 600.0, child: CustomScrollView( controller: scrollController, slivers: List<Widget>.generate(50, (int i) { return i == 10 ? SliverPersistentHeader( pinned: true, delegate: _TestSliverPersistentHeaderDelegate( minExtent: 50, maxExtent: 50, vsync: null, child: Container( alignment: Alignment.topCenter, child: EditableText( key: headerKey, backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ) : SliverToBoxAdapter( child: SizedBox( height: 100.0, child: Text('Tile $i'), ), ); }), ), ), ), ), ); // The persistent header should now be pinned at the top. scrollController.jumpTo(100.0 * 15); await tester.pumpAndSettle(); expect(scrollController.offset, 100.0 * 15); focusNode.requestFocus(); await tester.pumpAndSettle(); // The scroll offset should remain the same. expect(scrollController.offset, 100.0 * 15); }, ); void testShowCaretOnScreen({ required bool readOnly }) { group('EditableText._showCaretOnScreen, readOnly=$readOnly', () { final TextInputFormatter rejectEverythingFormatter = TextInputFormatter.withFunction((TextEditingValue old, TextEditingValue value) => old); bool isCaretOnScreen(WidgetTester tester) { final EditableTextState state = tester.state<EditableTextState>( find.byType(EditableText, skipOffstage: false), ); final RenderEditable renderEditable = state.renderEditable; final Rect localRect = renderEditable.getLocalRectForCaret(state.textEditingValue.selection.base); final Offset caretOrigin = renderEditable.localToGlobal(localRect.topLeft); final Rect caretRect = caretOrigin & localRect.size; return const Rect.fromLTWH(0, 0, 800, 600).intersect(caretRect) == caretRect; } Widget buildEditableText({ required bool rejectUserInputs, ScrollController? scrollController, ScrollController? editableScrollController, }) { return MaterialApp( home: Scaffold( body: ListView( controller: scrollController, cacheExtent: 1000, children: <Widget>[ // The text field is not fully visible. const SizedBox(height: 599), EditableText( backgroundCursorColor: Colors.grey, controller: controller, scrollController: editableScrollController, inputFormatters: <TextInputFormatter>[if (rejectUserInputs) rejectEverythingFormatter], focusNode: focusNode, style: textStyle, cursorColor: cursorColor, readOnly: readOnly, ), ], ), ), ); } testWidgets('focus-triggered showCaretOnScreen', (WidgetTester tester) async { controller.text = 'a' * 100; controller.selection = const TextSelection.collapsed(offset: 100); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); final ScrollController editableScrollController = ScrollController(); addTearDown(editableScrollController.dispose); await tester.pumpWidget( buildEditableText( rejectUserInputs: false, scrollController: scrollController, editableScrollController: editableScrollController, ), ); focusNode.requestFocus(); await tester.pumpAndSettle(); if (kIsWeb) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); } // On web, the entire field is selected, and only part of that selection // is visible on the screen. expect(isCaretOnScreen(tester), !readOnly && !kIsWeb); expect(scrollController.offset, readOnly ? 0.0 : greaterThan(0.0)); expect(editableScrollController.offset, readOnly ? 0.0 : greaterThan(0.0)); }); testWidgets('selection-triggered showCaretOnScreen: virtual keyboard', (WidgetTester tester) async { controller.text = 'a' * 100; controller.selection = const TextSelection.collapsed(offset: 80); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); final ScrollController editableScrollController = ScrollController(); addTearDown(editableScrollController.dispose); await tester.pumpWidget( buildEditableText( rejectUserInputs: false, scrollController: scrollController, editableScrollController: editableScrollController, ), ); focusNode.requestFocus(); await tester.pumpAndSettle(); // Ensure the caret is not fully visible and the text field is focused. scrollController.jumpTo(0); editableScrollController.jumpTo(0); await tester.pumpAndSettle(); expect(isCaretOnScreen(tester), isFalse); final EditableTextState state = tester.state<EditableTextState>( find.byType(EditableText, skipOffstage: false), ); // Change the selection. Show caret on screen when readyOnly is true, // as a read-only text field rejects everything from the software // keyboard (except for web). state.updateEditingValue(state.textEditingValue.copyWith(selection: const TextSelection.collapsed(offset: 90))); await tester.pumpAndSettle(); expect(isCaretOnScreen(tester), !readOnly || kIsWeb); expect(scrollController.offset, readOnly && !kIsWeb ? 0.0 : greaterThan(0.0)); expect(editableScrollController.offset, readOnly && !kIsWeb ? 0.0 : greaterThan(0.0)); // Reject user input. await tester.pumpWidget( buildEditableText( rejectUserInputs: true, scrollController: scrollController, editableScrollController: editableScrollController, ), ); // Ensure the caret is not fully visible and the text field is focused. scrollController.jumpTo(0); editableScrollController.jumpTo(0); await tester.pumpAndSettle(); expect(isCaretOnScreen(tester), isFalse); state.updateEditingValue(state.textEditingValue.copyWith(selection: const TextSelection.collapsed(offset: 100))); await tester.pumpAndSettle(); expect(isCaretOnScreen(tester), !readOnly || kIsWeb); expect(scrollController.offset, readOnly && !kIsWeb ? 0.0 : greaterThan(0.0)); expect(editableScrollController.offset, readOnly && !kIsWeb ? 0.0 : greaterThan(0.0)); }); testWidgets('selection-triggered showCaretOnScreen: text selection delegate', (WidgetTester tester) async { controller.text = 'a' * 100; controller.selection = const TextSelection.collapsed(offset: 80); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); final ScrollController editableScrollController = ScrollController(); addTearDown(editableScrollController.dispose); await tester.pumpWidget( buildEditableText( rejectUserInputs: false, scrollController: scrollController, editableScrollController: editableScrollController, ), ); focusNode.requestFocus(); await tester.pumpAndSettle(); // Ensure the caret is not fully visible and the text field is focused. scrollController.jumpTo(0); editableScrollController.jumpTo(0); await tester.pumpAndSettle(); expect(isCaretOnScreen(tester), isFalse); final EditableTextState state = tester.state<EditableTextState>( find.byType(EditableText, skipOffstage: false), ); // Change the selection. Show caret on screen even when readyOnly is // false. state.userUpdateTextEditingValue( state.textEditingValue.copyWith(selection: const TextSelection.collapsed(offset: 90)), null, ); await tester.pumpAndSettle(); expect(isCaretOnScreen(tester), isTrue); expect(scrollController.offset, greaterThan(0.0)); expect(editableScrollController.offset, greaterThan(0.0)); // Rejects user input. await tester.pumpWidget( buildEditableText( rejectUserInputs: true, scrollController: scrollController, editableScrollController: editableScrollController, ), ); // Ensure the caret is not fully visible and the text field is focused. scrollController.jumpTo(0); editableScrollController.jumpTo(0); await tester.pumpAndSettle(); expect(isCaretOnScreen(tester), isFalse); state.userUpdateTextEditingValue( state.textEditingValue.copyWith(selection: const TextSelection.collapsed(offset: 100)), null, ); await tester.pumpAndSettle(); expect(isCaretOnScreen(tester), isTrue); expect(scrollController.offset, greaterThan(0.0)); expect(editableScrollController.offset, greaterThan(0.0)); }); // Regression text for https://github.com/flutter/flutter/pull/74722. testWidgets('does NOT randomly trigger when cursor blinks', (WidgetTester tester) async { controller.text = 'a' * 100; controller.selection = const TextSelection.collapsed(offset: 0); final ScrollController editableScrollController = ScrollController(); addTearDown(editableScrollController.dispose); final bool deterministicCursor = EditableText.debugDeterministicCursor; EditableText.debugDeterministicCursor = false; await tester.pumpWidget( MaterialApp( home: Scaffold( body: EditableText( backgroundCursorColor: Colors.grey, controller: controller, scrollController: editableScrollController, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, ), ), ), ); final EditableTextState state = tester.state<EditableTextState>( find.byType(EditableText, skipOffstage: false), ); // Ensure the text was initially visible. expect(isCaretOnScreen(tester), true); expect(editableScrollController.offset, 0.0); // Change the text but keep the cursor location. state.updateEditingValue(controller.value.copyWith( text: 'a' * 101, )); await tester.pumpAndSettle(); // The caret should stay where it was, since the selection didn't change. expect(isCaretOnScreen(tester), true); expect(editableScrollController.offset, 0.0); // Now move to hide the cursor. editableScrollController.jumpTo(100.0); // Does not trigger showCaretOnScreen. await tester.pump(); await tester.pumpAndSettle(); expect(editableScrollController.offset, 100.0); expect(isCaretOnScreen(tester), isFalse); EditableText.debugDeterministicCursor = deterministicCursor; }); }); } testShowCaretOnScreen(readOnly: true); testShowCaretOnScreen(readOnly: false); } class NoImplicitScrollPhysics extends AlwaysScrollableScrollPhysics { const NoImplicitScrollPhysics({ super.parent }); @override bool get allowImplicitScrolling => false; @override NoImplicitScrollPhysics applyTo(ScrollPhysics? ancestor) { return NoImplicitScrollPhysics(parent: buildParent(ancestor)); } }
flutter/packages/flutter/test/widgets/editable_text_show_on_screen_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/editable_text_show_on_screen_test.dart", "repo_id": "flutter", "token_count": 12843 }
694
// 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 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker_testing/leak_tracker_testing.dart'; typedef ElementRebuildCallback = void Function(StatefulElement element); class TestState extends State<StatefulWidget> { @override Widget build(BuildContext context) => const SizedBox(); } @optionalTypeArgs class _MyGlobalObjectKey<T extends State<StatefulWidget>> extends GlobalObjectKey<T> { const _MyGlobalObjectKey(super.value); } void main() { testWidgets('UniqueKey control test', (WidgetTester tester) async { final Key key = UniqueKey(); expect(key, hasOneLineDescription); expect(key, isNot(equals(UniqueKey()))); }); testWidgets('ObjectKey control test', (WidgetTester tester) async { final Object a = Object(); final Object b = Object(); final Key keyA = ObjectKey(a); final Key keyA2 = ObjectKey(a); final Key keyB = ObjectKey(b); expect(keyA, hasOneLineDescription); expect(keyA, equals(keyA2)); expect(keyA.hashCode, equals(keyA2.hashCode)); expect(keyA, isNot(equals(keyB))); }); testWidgets('GlobalObjectKey toString test', (WidgetTester tester) async { const GlobalObjectKey one = GlobalObjectKey(1); const GlobalObjectKey<TestState> two = GlobalObjectKey<TestState>(2); const GlobalObjectKey three = _MyGlobalObjectKey(3); const GlobalObjectKey<TestState> four = _MyGlobalObjectKey<TestState>(4); expect(one.toString(), equals('[GlobalObjectKey ${describeIdentity(1)}]')); expect(two.toString(), equals('[GlobalObjectKey<TestState> ${describeIdentity(2)}]')); expect(three.toString(), equals('[_MyGlobalObjectKey ${describeIdentity(3)}]')); expect(four.toString(), equals('[_MyGlobalObjectKey<TestState> ${describeIdentity(4)}]')); }); testWidgets('GlobalObjectKey control test', (WidgetTester tester) async { final Object a = Object(); final Object b = Object(); final Key keyA = GlobalObjectKey(a); final Key keyA2 = GlobalObjectKey(a); final Key keyB = GlobalObjectKey(b); expect(keyA, hasOneLineDescription); expect(keyA, equals(keyA2)); expect(keyA.hashCode, equals(keyA2.hashCode)); expect(keyA, isNot(equals(keyB))); }); testWidgets('GlobalKey correct case 1 - can move global key from container widget to layoutbuilder', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'correct'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container( key: const ValueKey<int>(1), child: SizedBox(key: key), ), LayoutBuilder( key: const ValueKey<int>(2), builder: (BuildContext context, BoxConstraints constraints) { return const Placeholder(); }, ), ], )); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container( key: const ValueKey<int>(1), child: const Placeholder(), ), LayoutBuilder( key: const ValueKey<int>(2), builder: (BuildContext context, BoxConstraints constraints) { return SizedBox(key: key); }, ), ], )); }); testWidgets('GlobalKey correct case 2 - can move global key from layoutbuilder to container widget', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'correct'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container( key: const ValueKey<int>(1), child: const Placeholder(), ), LayoutBuilder( key: const ValueKey<int>(2), builder: (BuildContext context, BoxConstraints constraints) { return SizedBox(key: key); }, ), ], )); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container( key: const ValueKey<int>(1), child: SizedBox(key: key), ), LayoutBuilder( key: const ValueKey<int>(2), builder: (BuildContext context, BoxConstraints constraints) { return const Placeholder(); }, ), ], )); }); testWidgets('GlobalKey correct case 3 - can deal with early rebuild in layoutbuilder - move backward', (WidgetTester tester) async { const Key key1 = GlobalObjectKey('Text1'); const Key key2 = GlobalObjectKey('Text2'); Key? rebuiltKeyOfSecondChildBeforeLayout; Key? rebuiltKeyOfFirstChildAfterLayout; Key? rebuiltKeyOfSecondChildAfterLayout; await tester.pumpWidget( LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return Column( children: <Widget>[ const _Stateful( child: Text( 'Text1', textDirection: TextDirection.ltr, key: key1, ), ), _Stateful( child: const Text( 'Text2', textDirection: TextDirection.ltr, key: key2, ), onElementRebuild: (StatefulElement element) { // We don't want noise to override the result; expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); final _Stateful statefulWidget = element.widget as _Stateful; rebuiltKeyOfSecondChildBeforeLayout = statefulWidget.child.key; }, ), ], ); }, ), ); // Result will be written during first build and need to clear it to remove // noise. rebuiltKeyOfSecondChildBeforeLayout = null; final _StatefulState state = tester.firstState(find.byType(_Stateful).at(1)); state.rebuild(); // Reorders the items await tester.pumpWidget( LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return Column( children: <Widget>[ _Stateful( child: const Text( 'Text2', textDirection: TextDirection.ltr, key: key2, ), onElementRebuild: (StatefulElement element) { // Verifies the early rebuild happens before layout. expect(rebuiltKeyOfSecondChildBeforeLayout, key2); // We don't want noise to override the result; expect(rebuiltKeyOfFirstChildAfterLayout, isNull); final _Stateful statefulWidget = element.widget as _Stateful; rebuiltKeyOfFirstChildAfterLayout = statefulWidget.child.key; }, ), _Stateful( child: const Text( 'Text1', textDirection: TextDirection.ltr, key: key1, ), onElementRebuild: (StatefulElement element) { // Verifies the early rebuild happens before layout. expect(rebuiltKeyOfSecondChildBeforeLayout, key2); // We don't want noise to override the result; expect(rebuiltKeyOfSecondChildAfterLayout, isNull); final _Stateful statefulWidget = element.widget as _Stateful; rebuiltKeyOfSecondChildAfterLayout = statefulWidget.child.key; }, ), ], ); }, ), ); expect(rebuiltKeyOfSecondChildBeforeLayout, key2); expect(rebuiltKeyOfFirstChildAfterLayout, key2); expect(rebuiltKeyOfSecondChildAfterLayout, key1); }); testWidgets('GlobalKey correct case 4 - can deal with early rebuild in layoutbuilder - move forward', (WidgetTester tester) async { const Key key1 = GlobalObjectKey('Text1'); const Key key2 = GlobalObjectKey('Text2'); const Key key3 = GlobalObjectKey('Text3'); Key? rebuiltKeyOfSecondChildBeforeLayout; Key? rebuiltKeyOfSecondChildAfterLayout; Key? rebuiltKeyOfThirdChildAfterLayout; await tester.pumpWidget( LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return Column( children: <Widget>[ const _Stateful( child: Text( 'Text1', textDirection: TextDirection.ltr, key: key1, ), ), _Stateful( child: const Text( 'Text2', textDirection: TextDirection.ltr, key: key2, ), onElementRebuild: (StatefulElement element) { // We don't want noise to override the result; expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); final _Stateful statefulWidget = element.widget as _Stateful; rebuiltKeyOfSecondChildBeforeLayout = statefulWidget.child.key; }, ), const _Stateful( child: Text( 'Text3', textDirection: TextDirection.ltr, key: key3, ), ), ], ); }, ), ); // Result will be written during first build and need to clear it to remove // noise. rebuiltKeyOfSecondChildBeforeLayout = null; final _StatefulState state = tester.firstState(find.byType(_Stateful).at(1)); state.rebuild(); // Reorders the items await tester.pumpWidget( LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return Column( children: <Widget>[ const _Stateful( child: Text( 'Text1', textDirection: TextDirection.ltr, key: key1, ), ), _Stateful( child: const Text( 'Text3', textDirection: TextDirection.ltr, key: key3, ), onElementRebuild: (StatefulElement element) { // Verifies the early rebuild happens before layout. expect(rebuiltKeyOfSecondChildBeforeLayout, key2); // We don't want noise to override the result; expect(rebuiltKeyOfSecondChildAfterLayout, isNull); final _Stateful statefulWidget = element.widget as _Stateful; rebuiltKeyOfSecondChildAfterLayout = statefulWidget.child.key; }, ), _Stateful( child: const Text( 'Text2', textDirection: TextDirection.ltr, key: key2, ), onElementRebuild: (StatefulElement element) { // Verifies the early rebuild happens before layout. expect(rebuiltKeyOfSecondChildBeforeLayout, key2); // We don't want noise to override the result; expect(rebuiltKeyOfThirdChildAfterLayout, isNull); final _Stateful statefulWidget = element.widget as _Stateful; rebuiltKeyOfThirdChildAfterLayout = statefulWidget.child.key; }, ), ], ); }, ), ); expect(rebuiltKeyOfSecondChildBeforeLayout, key2); expect(rebuiltKeyOfSecondChildAfterLayout, key3); expect(rebuiltKeyOfThirdChildAfterLayout, key2); }); testWidgets('GlobalKey correct case 5 - can deal with early rebuild in layoutbuilder - only one global key', (WidgetTester tester) async { const Key key1 = GlobalObjectKey('Text1'); Key? rebuiltKeyOfSecondChildBeforeLayout; Key? rebuiltKeyOfThirdChildAfterLayout; await tester.pumpWidget( LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return Column( children: <Widget>[ const _Stateful( child: Text( 'Text1', textDirection: TextDirection.ltr, ), ), _Stateful( child: const Text( 'Text2', textDirection: TextDirection.ltr, key: key1, ), onElementRebuild: (StatefulElement element) { // We don't want noise to override the result; expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); final _Stateful statefulWidget = element.widget as _Stateful; rebuiltKeyOfSecondChildBeforeLayout = statefulWidget.child.key; }, ), const _Stateful( child: Text( 'Text3', textDirection: TextDirection.ltr, ), ), ], ); }, ), ); // Result will be written during first build and need to clear it to remove // noise. rebuiltKeyOfSecondChildBeforeLayout = null; final _StatefulState state = tester.firstState(find.byType(_Stateful).at(1)); state.rebuild(); // Reorders the items await tester.pumpWidget( LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return Column( children: <Widget>[ const _Stateful( child: Text( 'Text1', textDirection: TextDirection.ltr, ), ), _Stateful( child: const Text( 'Text3', textDirection: TextDirection.ltr, ), onElementRebuild: (StatefulElement element) { // Verifies the early rebuild happens before layout. expect(rebuiltKeyOfSecondChildBeforeLayout, key1); }, ), _Stateful( child: const Text( 'Text2', textDirection: TextDirection.ltr, key: key1, ), onElementRebuild: (StatefulElement element) { // Verifies the early rebuild happens before layout. expect(rebuiltKeyOfSecondChildBeforeLayout, key1); // We don't want noise to override the result; expect(rebuiltKeyOfThirdChildAfterLayout, isNull); final _Stateful statefulWidget = element.widget as _Stateful; rebuiltKeyOfThirdChildAfterLayout = statefulWidget.child.key; }, ), ], ); }, ), ); expect(rebuiltKeyOfSecondChildBeforeLayout, key1); expect(rebuiltKeyOfThirdChildAfterLayout, key1); }); testWidgets('GlobalKey duplication 1 - double appearance', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container( key: const ValueKey<int>(1), child: SizedBox(key: key), ), Container( key: const ValueKey<int>(2), child: Placeholder(key: key), ), ], )); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect( exception.toString(), equalsIgnoringHashCodes( 'Multiple widgets used the same GlobalKey.\n' 'The key [GlobalKey#00000 problematic] was used by multiple widgets. The parents of those widgets were:\n' '- Container-[<1>]\n' '- Container-[<2>]\n' 'A GlobalKey can only be specified on one widget at a time in the widget tree.', ), ); }); testWidgets('GlobalKey duplication 2 - splitting and changing type', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container( key: const ValueKey<int>(1), ), Container( key: const ValueKey<int>(2), ), Container( key: key, ), ], )); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container( key: const ValueKey<int>(1), child: SizedBox(key: key), ), Container( key: const ValueKey<int>(2), child: Placeholder(key: key), ), ], )); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect( exception.toString(), equalsIgnoringHashCodes( 'Multiple widgets used the same GlobalKey.\n' 'The key [GlobalKey#00000 problematic] was used by multiple widgets. The parents of those widgets were:\n' '- Container-[<1>]\n' '- Container-[<2>]\n' 'A GlobalKey can only be specified on one widget at a time in the widget tree.', ), ); }); testWidgets('GlobalKey duplication 3 - splitting and changing type', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: key), ], )); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ SizedBox(key: key), Placeholder(key: key), ], )); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect( exception.toString(), equalsIgnoringHashCodes( 'Duplicate keys found.\n' 'If multiple keyed widgets exist as children of another widget, they must have unique keys.\n' 'Stack(alignment: AlignmentDirectional.topStart, textDirection: ltr, fit: loose) has multiple children with key [GlobalKey#00000 problematic].' ), ); }); testWidgets('GlobalKey duplication 4 - splitting and half changing type', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: key), ], )); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: key), Placeholder(key: key), ], )); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect( exception.toString(), equalsIgnoringHashCodes( 'Duplicate keys found.\n' 'If multiple keyed widgets exist as children of another widget, they must have unique keys.\n' 'Stack(alignment: AlignmentDirectional.topStart, textDirection: ltr, fit: loose) has multiple children with key [GlobalKey#00000 problematic].' ), ); }); testWidgets('GlobalKey duplication 5 - splitting and half changing type', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: key), ], )); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Placeholder(key: key), Container(key: key), ], )); expect(tester.takeException(), isFlutterError); }); testWidgets('GlobalKey duplication 6 - splitting and not changing type', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: key), ], )); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: key), Container(key: key), ], )); expect(tester.takeException(), isFlutterError); }); testWidgets('GlobalKey duplication 7 - appearing later', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: const ValueKey<int>(1), child: Container(key: key)), Container(key: const ValueKey<int>(2)), ], )); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: const ValueKey<int>(1), child: Container(key: key)), Container(key: const ValueKey<int>(2), child: Container(key: key)), ], )); expect(tester.takeException(), isFlutterError); }); testWidgets('GlobalKey duplication 8 - appearing earlier', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: const ValueKey<int>(1)), Container(key: const ValueKey<int>(2), child: Container(key: key)), ], )); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: const ValueKey<int>(1), child: Container(key: key)), Container(key: const ValueKey<int>(2), child: Container(key: key)), ], )); expect(tester.takeException(), isFlutterError); }); testWidgets('GlobalKey duplication 9 - moving and appearing later', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: const ValueKey<int>(0), child: Container(key: key)), Container(key: const ValueKey<int>(1)), Container(key: const ValueKey<int>(2)), ], )); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: const ValueKey<int>(0)), Container(key: const ValueKey<int>(1), child: Container(key: key)), Container(key: const ValueKey<int>(2), child: Container(key: key)), ], )); expect(tester.takeException(), isFlutterError); }); testWidgets('GlobalKey duplication 10 - moving and appearing earlier', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: const ValueKey<int>(1)), Container(key: const ValueKey<int>(2)), Container(key: const ValueKey<int>(3), child: Container(key: key)), ], )); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: const ValueKey<int>(1), child: Container(key: key)), Container(key: const ValueKey<int>(2), child: Container(key: key)), Container(key: const ValueKey<int>(3)), ], )); expect(tester.takeException(), isFlutterError); }); testWidgets('GlobalKey duplication 11 - double sibling appearance', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: key), Container(key: key), ], )); expect(tester.takeException(), isFlutterError); }); testWidgets('GlobalKey duplication 12 - all kinds of badness at once', (WidgetTester tester) async { final Key key1 = GlobalKey(debugLabel: 'problematic'); final Key key2 = GlobalKey(debugLabel: 'problematic'); // intentionally the same label final Key key3 = GlobalKey(debugLabel: 'also problematic'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: key1), Container(key: key1), Container(key: key2), Container(key: key1), Container(key: key1), Container(key: key2), Container(key: key1), Container(key: key1), Row( children: <Widget>[ Container(key: key1), Container(key: key1), Container(key: key2), Container(key: key2), Container(key: key2), Container(key: key3), Container(key: key2), ], ), Row( children: <Widget>[ Container(key: key1), Container(key: key1), Container(key: key3), ], ), Container(key: key3), ], )); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect( exception.toString(), equalsIgnoringHashCodes( 'Duplicate keys found.\n' 'If multiple keyed widgets exist as children of another widget, they must have unique keys.\n' 'Stack(alignment: AlignmentDirectional.topStart, textDirection: ltr, fit: loose) has multiple children with key [GlobalKey#00000 problematic].', ), ); }); testWidgets('GlobalKey duplication 13 - all kinds of badness at once', (WidgetTester tester) async { final Key key1 = GlobalKey(debugLabel: 'problematic'); final Key key2 = GlobalKey(debugLabel: 'problematic'); // intentionally the same label final Key key3 = GlobalKey(debugLabel: 'also problematic'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: key1), Container(key: key2), Container(key: key3), ], )); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: key1), Container(key: key1), Container(key: key2), Container(key: key1), Container(key: key1), Container(key: key2), Container(key: key1), Container(key: key1), Row( children: <Widget>[ Container(key: key1), Container(key: key1), Container(key: key2), Container(key: key2), Container(key: key2), Container(key: key3), Container(key: key2), ], ), Row( children: <Widget>[ Container(key: key1), Container(key: key1), Container(key: key3), ], ), Container(key: key3), ], )); expect(tester.takeException(), isFlutterError); }); testWidgets('GlobalKey duplication 14 - moving during build - before', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: key), Container(key: const ValueKey<int>(0)), Container(key: const ValueKey<int>(1)), ], )); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: const ValueKey<int>(0)), Container(key: const ValueKey<int>(1), child: Container(key: key)), ], )); }); testWidgets('GlobalKey duplication 15 - duplicating during build - before', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: key), Container(key: const ValueKey<int>(0)), Container(key: const ValueKey<int>(1)), ], )); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: key), Container(key: const ValueKey<int>(0)), Container(key: const ValueKey<int>(1), child: Container(key: key)), ], )); expect(tester.takeException(), isFlutterError); }); testWidgets('GlobalKey duplication 16 - moving during build - after', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: const ValueKey<int>(0)), Container(key: const ValueKey<int>(1)), Container(key: key), ], )); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: const ValueKey<int>(0)), Container(key: const ValueKey<int>(1), child: Container(key: key)), ], )); }); testWidgets('GlobalKey duplication 17 - duplicating during build - after', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: const ValueKey<int>(0)), Container(key: const ValueKey<int>(1)), Container(key: key), ], )); int count = 0; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { expect(details.exception, isFlutterError); count += 1; }; await tester.pumpWidget(Stack( textDirection: TextDirection.ltr, children: <Widget>[ Container(key: const ValueKey<int>(0)), Container(key: const ValueKey<int>(1), child: Container(key: key)), Container(key: key), ], )); FlutterError.onError = oldHandler; expect(count, 1); }); testWidgets('GlobalKey duplication 18 - subtree build duplicate key with same type', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); final Stack stack = Stack( textDirection: TextDirection.ltr, children: <Widget>[ const SwapKeyWidget(childKey: ValueKey<int>(0)), Container(key: const ValueKey<int>(1)), Container(key: key), ], ); await tester.pumpWidget(stack); final SwapKeyWidgetState state = tester.state(find.byType(SwapKeyWidget)); state.swapKey(key); await tester.pump(); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect( exception.toString(), equalsIgnoringHashCodes( 'Duplicate GlobalKey detected in widget tree.\n' 'The following GlobalKey was specified multiple times in the widget tree. This will lead ' 'to parts of the widget tree being truncated unexpectedly, because the second time a key is seen, the ' 'previous instance is moved to the new location. The key was:\n' '- [GlobalKey#00000 problematic]\n' 'This was determined by noticing that after the widget with the above global key was ' 'moved out of its previous parent, that previous parent never updated during this frame, meaning that ' 'it either did not update at all or updated before the widget was moved, in either case implying that ' 'it still thinks that it should have a child with that global key.\n' 'The specific parent that did not update after having one or more children forcibly ' 'removed due to GlobalKey reparenting is:\n' '- Stack(alignment: AlignmentDirectional.topStart, textDirection: ltr, fit: loose, ' 'renderObject: RenderStack#00000)\n' 'A GlobalKey can only be specified on one widget at a time in the widget tree.', ), ); }); testWidgets('GlobalKey duplication 19 - subtree build duplicate key with different types', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); final Stack stack = Stack( textDirection: TextDirection.ltr, children: <Widget>[ const SwapKeyWidget(childKey: ValueKey<int>(0)), Container(key: const ValueKey<int>(1)), ColoredBox(color: Colors.green, child: SizedBox(key: key)), ], ); await tester.pumpWidget(stack); final SwapKeyWidgetState state = tester.state(find.byType(SwapKeyWidget)); state.swapKey(key); await tester.pump(); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect( exception.toString(), equalsIgnoringHashCodes( 'Multiple widgets used the same GlobalKey.\n' 'The key [GlobalKey#95367 problematic] was used by 2 widgets:\n' ' SizedBox-[GlobalKey#00000 problematic]\n' ' Container-[GlobalKey#00000 problematic]\n' 'A GlobalKey can only be specified on one widget at a time in the widget tree.', ), ); }); testWidgets('GlobalKey duplication 20 - real duplication with early rebuild in layoutbuilder will throw', (WidgetTester tester) async { const Key key1 = GlobalObjectKey('Text1'); const Key key2 = GlobalObjectKey('Text2'); Key? rebuiltKeyOfSecondChildBeforeLayout; Key? rebuiltKeyOfFirstChildAfterLayout; Key? rebuiltKeyOfSecondChildAfterLayout; await tester.pumpWidget( LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return Column( children: <Widget>[ const _Stateful( child: Text( 'Text1', textDirection: TextDirection.ltr, key: key1, ), ), _Stateful( child: const Text( 'Text2', textDirection: TextDirection.ltr, key: key2, ), onElementRebuild: (StatefulElement element) { // We don't want noise to override the result; expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); final _Stateful statefulWidget = element.widget as _Stateful; rebuiltKeyOfSecondChildBeforeLayout = statefulWidget.child.key; }, ), ], ); }, ), ); // Result will be written during first build and need to clear it to remove // noise. rebuiltKeyOfSecondChildBeforeLayout = null; final _StatefulState state = tester.firstState(find.byType(_Stateful).at(1)); state.rebuild(); await tester.pumpWidget( LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return Column( children: <Widget>[ _Stateful( child: const Text( 'Text2', textDirection: TextDirection.ltr, key: key2, ), onElementRebuild: (StatefulElement element) { // Verifies the early rebuild happens before layout. expect(rebuiltKeyOfSecondChildBeforeLayout, key2); // We don't want noise to override the result; expect(rebuiltKeyOfFirstChildAfterLayout, isNull); final _Stateful statefulWidget = element.widget as _Stateful; rebuiltKeyOfFirstChildAfterLayout = statefulWidget.child.key; }, ), _Stateful( child: const Text( 'Text1', textDirection: TextDirection.ltr, key: key2, ), onElementRebuild: (StatefulElement element) { // Verifies the early rebuild happens before layout. expect(rebuiltKeyOfSecondChildBeforeLayout, key2); // We don't want noise to override the result; expect(rebuiltKeyOfSecondChildAfterLayout, isNull); final _Stateful statefulWidget = element.widget as _Stateful; rebuiltKeyOfSecondChildAfterLayout = statefulWidget.child.key; }, ), ], ); }, ), ); expect(rebuiltKeyOfSecondChildBeforeLayout, key2); expect(rebuiltKeyOfFirstChildAfterLayout, key2); expect(rebuiltKeyOfSecondChildAfterLayout, key2); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect( exception.toString(), equalsIgnoringHashCodes( 'Multiple widgets used the same GlobalKey.\n' 'The key [GlobalObjectKey String#00000] was used by multiple widgets. The ' 'parents of those widgets were:\n' '- _Stateful(state: _StatefulState#00000)\n' '- _Stateful(state: _StatefulState#00000)\n' 'A GlobalKey can only be specified on one widget at a time in the widget tree.', ), ); }); testWidgets('GlobalKey - detach and re-attach child to different parents', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( height: 100, child: CustomScrollView( controller: scrollController, slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate(<Widget>[ Text('child', key: GlobalKey()), ]), ), ], ), ), ), )); final SliverMultiBoxAdaptorElement element = tester.element(find.byType(SliverList)); late Element childElement; // Removing and recreating child with same Global Key should not trigger // duplicate key error. element.visitChildren((Element e) { childElement = e; }); element.removeChild(childElement.renderObject! as RenderBox); element.createChild(0, after: null); element.visitChildren((Element e) { childElement = e; }); element.removeChild(childElement.renderObject! as RenderBox); element.createChild(0, after: null); }); testWidgets('GlobalKey - re-attach child to new parents, and the old parent is deactivated(unmounted)', (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/62055 const Key key1 = GlobalObjectKey('key1'); const Key key2 = GlobalObjectKey('key2'); late StateSetter setState; int tabBarViewCnt = 2; TabController tabController = TabController(length: tabBarViewCnt, vsync: const TestVSync()); addTearDown(tabController.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; return TabBarView( controller: tabController, children: <Widget>[ if (tabBarViewCnt > 0) const Text('key1', key: key1), if (tabBarViewCnt > 1) const Text('key2', key: key2), ], ); }, ), )); expect(tabController.index, 0); // switch tabs 0 -> 1 setState(() { tabController.index = 1; }); await tester.pump(const Duration(seconds: 1)); // finish the animation expect(tabController.index, 1); // rebuild TabBarView that only have the 1st page with GlobalKey 'key1' setState(() { tabBarViewCnt = 1; tabController = TabController(length: tabBarViewCnt, vsync: const TestVSync()); addTearDown(tabController.dispose); }); await tester.pump(const Duration(seconds: 1)); // finish the animation expect(tabController.index, 0); }); testWidgets('Defunct setState throws exception', (WidgetTester tester) async { late StateSetter setState; await tester.pumpWidget(StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; return Container(); }, )); // Control check that setState doesn't throw an exception. setState(() { }); await tester.pumpWidget(Container()); expect(() { setState(() { }); }, throwsFlutterError); }); testWidgets('State toString', (WidgetTester tester) async { final TestState state = TestState(); expect(state.toString(), contains('no widget')); }); testWidgets('debugPrintGlobalKeyedWidgetLifecycle control test', (WidgetTester tester) async { expect(debugPrintGlobalKeyedWidgetLifecycle, isFalse); final DebugPrintCallback oldCallback = debugPrint; debugPrintGlobalKeyedWidgetLifecycle = true; final List<String> log = <String>[]; debugPrint = (String? message, { int? wrapWidth }) { log.add(message!); }; final GlobalKey key = GlobalKey(); await tester.pumpWidget(Container(key: key)); expect(log, isEmpty); await tester.pumpWidget(const Placeholder()); debugPrint = oldCallback; debugPrintGlobalKeyedWidgetLifecycle = false; expect(log.length, equals(2)); expect(log[0], matches('Deactivated')); expect(log[1], matches('Discarding .+ from inactive elements list.')); }); testWidgets('MultiChildRenderObjectElement.children', (WidgetTester tester) async { GlobalKey key0, key1, key2; await tester.pumpWidget(Column( key: key0 = GlobalKey(), children: <Widget>[ Container(), Container(key: key1 = GlobalKey()), Container(), Container(key: key2 = GlobalKey()), Container(), ], )); final MultiChildRenderObjectElement element = key0.currentContext! as MultiChildRenderObjectElement; expect( element.children.map((Element element) => element.widget.key), <Key?>[null, key1, null, key2, null], ); }); testWidgets('Can not attach a non-RenderObjectElement to the MultiChildRenderObjectElement - mount', (WidgetTester tester) async { await tester.pumpWidget( Column( children: <Widget>[ Container(), const _EmptyWidget(), ], ), ); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect( exception.toString(), startsWith( 'The children of `MultiChildRenderObjectElement` must each has an associated render object.\n' 'This typically means that the `_EmptyWidget` or its children\n' 'are not a subtype of `RenderObjectWidget`.\n' 'The following element does not have an associated render object:\n' ' _EmptyWidget\n' 'debugCreator: _EmptyWidget ← Column ← ', // Omitted end of debugCreator chain because it's irrelevant for test. ), ); }); testWidgets('Can not attach a non-RenderObjectElement to the MultiChildRenderObjectElement - update', (WidgetTester tester) async { await tester.pumpWidget( Column( children: <Widget>[ Container(), ], ), ); await tester.pumpWidget( Column( children: <Widget>[ Container(), const _EmptyWidget(), ], ), ); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect( exception.toString(), startsWith( 'The children of `MultiChildRenderObjectElement` must each has an associated render object.\n' 'This typically means that the `_EmptyWidget` or its children\n' 'are not a subtype of `RenderObjectWidget`.\n' 'The following element does not have an associated render object:\n' ' _EmptyWidget\n' 'debugCreator: _EmptyWidget ← Column ← ', // Omitted end of debugCreator chain because it's irrelevant for test. ), ); }); testWidgets('Element diagnostics', (WidgetTester tester) async { GlobalKey key0; await tester.pumpWidget(Column( key: key0 = GlobalKey(), children: <Widget>[ Container(), Container(key: GlobalKey()), ColoredBox(color: Colors.green, child: Container()), Container(key: GlobalKey()), Container(), ], )); final MultiChildRenderObjectElement element = key0.currentContext! as MultiChildRenderObjectElement; expect(element, hasAGoodToStringDeep); expect( element.toStringDeep(), equalsIgnoringHashCodes( 'Column-[GlobalKey#00000](direction: vertical, mainAxisAlignment: start, crossAxisAlignment: center, renderObject: RenderFlex#00000)\n' '├Container\n' '│└LimitedBox(maxWidth: 0.0, maxHeight: 0.0, renderObject: RenderLimitedBox#00000 relayoutBoundary=up1)\n' '│ └ConstrainedBox(BoxConstraints(biggest), renderObject: RenderConstrainedBox#00000 relayoutBoundary=up2)\n' '├Container-[GlobalKey#00000]\n' '│└LimitedBox(maxWidth: 0.0, maxHeight: 0.0, renderObject: RenderLimitedBox#00000 relayoutBoundary=up1)\n' '│ └ConstrainedBox(BoxConstraints(biggest), renderObject: RenderConstrainedBox#00000 relayoutBoundary=up2)\n' '├ColoredBox(color: MaterialColor(primary value: Color(0xff4caf50)), renderObject: _RenderColoredBox#00000 relayoutBoundary=up1)\n' '│└Container\n' '│ └LimitedBox(maxWidth: 0.0, maxHeight: 0.0, renderObject: RenderLimitedBox#00000 relayoutBoundary=up2)\n' '│ └ConstrainedBox(BoxConstraints(biggest), renderObject: RenderConstrainedBox#00000 relayoutBoundary=up3)\n' '├Container-[GlobalKey#00000]\n' '│└LimitedBox(maxWidth: 0.0, maxHeight: 0.0, renderObject: RenderLimitedBox#00000 relayoutBoundary=up1)\n' '│ └ConstrainedBox(BoxConstraints(biggest), renderObject: RenderConstrainedBox#00000 relayoutBoundary=up2)\n' '└Container\n' ' └LimitedBox(maxWidth: 0.0, maxHeight: 0.0, renderObject: RenderLimitedBox#00000 relayoutBoundary=up1)\n' ' └ConstrainedBox(BoxConstraints(biggest), renderObject: RenderConstrainedBox#00000 relayoutBoundary=up2)\n', ), ); }); testWidgets('scheduleBuild while debugBuildingDirtyElements is true', (WidgetTester tester) async { // ignore here is required for testing purpose because changing the flag properly is hard // ignore: invalid_use_of_protected_member tester.binding.debugBuildingDirtyElements = true; late FlutterError error; try { tester.binding.buildOwner!.scheduleBuildFor( DirtyElementWithCustomBuildOwner(tester.binding.buildOwner!, Container()), ); } on FlutterError catch (e) { error = e; } finally { expect(error.diagnostics.length, 3); expect(error.diagnostics.last.level, DiagnosticLevel.hint); expect( error.diagnostics.last.toStringDeep(), equalsIgnoringHashCodes( 'This might be because setState() was called from a layout or\n' 'paint callback. If a change is needed to the widget tree, it\n' 'should be applied as the tree is being built. Scheduling a change\n' 'for the subsequent frame instead results in an interface that\n' 'lags behind by one frame. If this was done to make your build\n' 'dependent on a size measured at layout time, consider using a\n' 'LayoutBuilder, CustomSingleChildLayout, or\n' 'CustomMultiChildLayout. If, on the other hand, the one frame\n' 'delay is the desired effect, for example because this is an\n' 'animation, consider scheduling the frame in a post-frame callback\n' 'using SchedulerBinding.addPostFrameCallback or using an\n' 'AnimationController to trigger the animation.\n', ), ); expect( error.toStringDeep(), 'FlutterError\n' ' Build scheduled during frame.\n' ' While the widget tree was being built, laid out, and painted, a\n' ' new frame was scheduled to rebuild the widget tree.\n' ' This might be because setState() was called from a layout or\n' ' paint callback. If a change is needed to the widget tree, it\n' ' should be applied as the tree is being built. Scheduling a change\n' ' for the subsequent frame instead results in an interface that\n' ' lags behind by one frame. If this was done to make your build\n' ' dependent on a size measured at layout time, consider using a\n' ' LayoutBuilder, CustomSingleChildLayout, or\n' ' CustomMultiChildLayout. If, on the other hand, the one frame\n' ' delay is the desired effect, for example because this is an\n' ' animation, consider scheduling the frame in a post-frame callback\n' ' using SchedulerBinding.addPostFrameCallback or using an\n' ' AnimationController to trigger the animation.\n', ); } }); testWidgets('didUpdateDependencies is not called on a State that never rebuilds', (WidgetTester tester) async { final GlobalKey<DependentState> key = GlobalKey<DependentState>(); /// Initial build - should call didChangeDependencies, not deactivate await tester.pumpWidget(Inherited(1, child: DependentStatefulWidget(key: key))); final DependentState state = key.currentState!; expect(key.currentState, isNotNull); expect(state.didChangeDependenciesCount, 1); expect(state.deactivatedCount, 0); /// Rebuild with updated value - should call didChangeDependencies await tester.pumpWidget(Inherited(2, child: DependentStatefulWidget(key: key))); expect(key.currentState, isNotNull); expect(state.didChangeDependenciesCount, 2); expect(state.deactivatedCount, 0); // reparent it - should call deactivate and didChangeDependencies await tester.pumpWidget(Inherited(3, child: SizedBox(child: DependentStatefulWidget(key: key)))); expect(key.currentState, isNotNull); expect(state.didChangeDependenciesCount, 3); expect(state.deactivatedCount, 1); // Remove it - should call deactivate, but not didChangeDependencies await tester.pumpWidget(const Inherited(4, child: SizedBox())); expect(key.currentState, isNull); expect(state.didChangeDependenciesCount, 3); expect(state.deactivatedCount, 2); }); testWidgets('StatefulElement subclass can decorate State.build', (WidgetTester tester) async { late bool isDidChangeDependenciesDecorated; late bool isBuildDecorated; final Widget child = Decorate( didChangeDependencies: (bool value) { isDidChangeDependenciesDecorated = value; }, build: (bool value) { isBuildDecorated = value; }, ); await tester.pumpWidget(Inherited(0, child: child)); expect(isBuildDecorated, isTrue); expect(isDidChangeDependenciesDecorated, isFalse); await tester.pumpWidget(Inherited(1, child: child)); expect(isBuildDecorated, isTrue); expect(isDidChangeDependenciesDecorated, isFalse); }); group('BuildContext.debugDoingbuild', () { testWidgets('StatelessWidget', (WidgetTester tester) async { late bool debugDoingBuildOnBuild; await tester.pumpWidget( StatelessWidgetSpy( onBuild: (BuildContext context) { debugDoingBuildOnBuild = context.debugDoingBuild; }, ), ); final Element context = tester.element(find.byType(StatelessWidgetSpy)); expect(context.debugDoingBuild, isFalse); expect(debugDoingBuildOnBuild, isTrue); }); testWidgets('StatefulWidget', (WidgetTester tester) async { late bool debugDoingBuildOnBuild; late bool debugDoingBuildOnInitState; late bool debugDoingBuildOnDidChangeDependencies; late bool debugDoingBuildOnDidUpdateWidget; bool? debugDoingBuildOnDispose; bool? debugDoingBuildOnDeactivate; await tester.pumpWidget( Inherited( 0, child: StatefulWidgetSpy( onInitState: (BuildContext context) { debugDoingBuildOnInitState = context.debugDoingBuild; }, onDidChangeDependencies: (BuildContext context) { context.dependOnInheritedWidgetOfExactType<Inherited>(); debugDoingBuildOnDidChangeDependencies = context.debugDoingBuild; }, onBuild: (BuildContext context) { debugDoingBuildOnBuild = context.debugDoingBuild; }, ), ), ); final Element context = tester.element(find.byType(StatefulWidgetSpy)); expect(context.debugDoingBuild, isFalse); expect(debugDoingBuildOnBuild, isTrue); expect(debugDoingBuildOnInitState, isFalse); expect(debugDoingBuildOnDidChangeDependencies, isFalse); await tester.pumpWidget( Inherited( 1, child: StatefulWidgetSpy( onDidUpdateWidget: (BuildContext context) { debugDoingBuildOnDidUpdateWidget = context.debugDoingBuild; }, onDidChangeDependencies: (BuildContext context) { debugDoingBuildOnDidChangeDependencies = context.debugDoingBuild; }, onBuild: (BuildContext context) { debugDoingBuildOnBuild = context.debugDoingBuild; }, onDispose: (BuildContext context) { debugDoingBuildOnDispose = context.debugDoingBuild; }, onDeactivate: (BuildContext context) { debugDoingBuildOnDeactivate = context.debugDoingBuild; }, ), ), ); expect(context.debugDoingBuild, isFalse); expect(debugDoingBuildOnBuild, isTrue); expect(debugDoingBuildOnDidUpdateWidget, isFalse); expect(debugDoingBuildOnDidChangeDependencies, isFalse); expect(debugDoingBuildOnDeactivate, isNull); expect(debugDoingBuildOnDispose, isNull); await tester.pumpWidget(Container()); expect(context.debugDoingBuild, isFalse); expect(debugDoingBuildOnDispose, isFalse); expect(debugDoingBuildOnDeactivate, isFalse); }); testWidgets('RenderObjectWidget', (WidgetTester tester) async { late bool debugDoingBuildOnCreateRenderObject; bool? debugDoingBuildOnUpdateRenderObject; bool? debugDoingBuildOnDidUnmountRenderObject; final ValueNotifier<int> notifier = ValueNotifier<int>(0); addTearDown(notifier.dispose); late BuildContext spyContext; Widget build() { return ValueListenableBuilder<int>( valueListenable: notifier, builder: (BuildContext context, int? value, Widget? child) { return Inherited(value, child: child!); }, child: RenderObjectWidgetSpy( onCreateRenderObject: (BuildContext context) { spyContext = context; context.dependOnInheritedWidgetOfExactType<Inherited>(); debugDoingBuildOnCreateRenderObject = context.debugDoingBuild; }, onUpdateRenderObject: (BuildContext context) { debugDoingBuildOnUpdateRenderObject = context.debugDoingBuild; }, onDidUnmountRenderObject: () { debugDoingBuildOnDidUnmountRenderObject = spyContext.debugDoingBuild; }, ), ); } await tester.pumpWidget(build()); spyContext = tester.element(find.byType(RenderObjectWidgetSpy)); expect(spyContext.debugDoingBuild, isFalse); expect(debugDoingBuildOnCreateRenderObject, isTrue); expect(debugDoingBuildOnUpdateRenderObject, isNull); expect(debugDoingBuildOnDidUnmountRenderObject, isNull); await tester.pumpWidget(build()); expect(spyContext.debugDoingBuild, isFalse); expect(debugDoingBuildOnUpdateRenderObject, isTrue); expect(debugDoingBuildOnDidUnmountRenderObject, isNull); notifier.value++; debugDoingBuildOnUpdateRenderObject = false; await tester.pump(); expect(spyContext.debugDoingBuild, isFalse); expect(debugDoingBuildOnUpdateRenderObject, isTrue); expect(debugDoingBuildOnDidUnmountRenderObject, isNull); await tester.pumpWidget(Container()); expect(spyContext.debugDoingBuild, isFalse); expect(debugDoingBuildOnDidUnmountRenderObject, isFalse); }); }); testWidgets('A widget whose element has an invalid visitChildren implementation triggers a useful error message', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget(_WidgetWithNoVisitChildren(_StatefulLeaf(key: key))); (key.currentState! as _StatefulLeafState).markNeedsBuild(); await tester.pumpWidget(Container()); final dynamic exception = tester.takeException(); expect( // ignore: avoid_dynamic_calls exception.message, equalsIgnoringHashCodes( 'Tried to build dirty widget in the wrong build scope.\n' 'A widget which was marked as dirty and is still active was scheduled to be built, ' 'but the current build scope unexpectedly does not contain that widget.\n' 'Sometimes this is detected when an element is removed from the widget tree, but ' 'the element somehow did not get marked as inactive. In that case, it might be ' 'caused by an ancestor element failing to implement visitChildren correctly, thus ' 'preventing some or all of its descendants from being correctly deactivated.\n' 'The root of the build scope was:\n' ' [root]\n' 'The offending element (which does not appear to be a descendant of the root of ' 'the build scope) was:\n' ' _StatefulLeaf-[GlobalKey#00000]', ), ); }); testWidgets('Can create BuildOwner that does not interfere with pointer router or raw key event handler', (WidgetTester tester) async { final int pointerRouterCount = GestureBinding.instance.pointerRouter.debugGlobalRouteCount; final RawKeyEventHandler? rawKeyEventHandler = RawKeyboard.instance.keyEventHandler; expect(rawKeyEventHandler, isNotNull); final FocusManager focusManager = FocusManager(); addTearDown(focusManager.dispose); BuildOwner(focusManager: focusManager); expect(GestureBinding.instance.pointerRouter.debugGlobalRouteCount, pointerRouterCount); expect(RawKeyboard.instance.keyEventHandler, same(rawKeyEventHandler)); }); testWidgets('Can access debugFillProperties without _LateInitializationError', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); TestRenderObjectElement().debugFillProperties(builder); expect(builder.properties.any((DiagnosticsNode property) => property.name == 'renderObject' && property.value == null), isTrue); }); testWidgets('debugFillProperties sorts dependencies in alphabetical order', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); final TestRenderObjectElement element = TestRenderObjectElement(); final _TestInheritedElement focusTraversalOrder = _TestInheritedElement(const FocusTraversalOrder( order: LexicalFocusOrder(''), child: Placeholder(), )); final _TestInheritedElement directionality = _TestInheritedElement(const Directionality( textDirection: TextDirection.ltr, child: Placeholder(), )); final _TestInheritedElement navigationBarTheme = _TestInheritedElement(const NavigationBarTheme( data: NavigationBarThemeData( indicatorColor: Color(0xff00ff00), ), child: Placeholder(), )); // Dependencies are added out of alphabetical order. element ..dependOnInheritedElement(focusTraversalOrder) ..dependOnInheritedElement(directionality) ..dependOnInheritedElement(navigationBarTheme); // Dependencies will be sorted by [debugFillProperties]. element.debugFillProperties(builder); expect( builder.properties.any((DiagnosticsNode property) => property.name == 'dependencies' && property.value != null), isTrue, ); final DiagnosticsProperty<Set<InheritedElement>> dependenciesProperty = builder.properties.firstWhere((DiagnosticsNode property) => property.name == 'dependencies') as DiagnosticsProperty<Set<InheritedElement>>; expect(dependenciesProperty, isNotNull); final Set<InheritedElement> dependencies = dependenciesProperty.value!; expect(dependencies.length, equals(3)); expect(dependenciesProperty.toDescription(), '[Directionality, FocusTraversalOrder, NavigationBarTheme]'); }); testWidgets('BuildOwner.globalKeyCount keeps track of in-use global keys', (WidgetTester tester) async { final int initialCount = tester.binding.buildOwner!.globalKeyCount; final GlobalKey key1 = GlobalKey(); final GlobalKey key2 = GlobalKey(); await tester.pumpWidget(Container(key: key1)); expect(tester.binding.buildOwner!.globalKeyCount, initialCount + 1); await tester.pumpWidget(Container(key: key1, child: Container())); expect(tester.binding.buildOwner!.globalKeyCount, initialCount + 1); await tester.pumpWidget(Container(key: key1, child: Container(key: key2))); expect(tester.binding.buildOwner!.globalKeyCount, initialCount + 2); await tester.pumpWidget(Container()); expect(tester.binding.buildOwner!.globalKeyCount, initialCount + 0); }); testWidgets('Widget and State properties are nulled out when unmounted', (WidgetTester tester) async { await tester.pumpWidget(const _StatefulLeaf()); final StatefulElement element = tester.element<StatefulElement>(find.byType(_StatefulLeaf)); expect(element.state, isA<State<_StatefulLeaf>>()); expect(element.widget, isA<_StatefulLeaf>()); // Replace the widget tree to unmount the element. await tester.pumpWidget(Container()); // Accessing state/widget now throws a CastError because they have been // nulled out to reduce severity of memory leaks when an Element (e.g. in // the form of a BuildContext) is retained past its useful life. See also // https://github.com/flutter/flutter/issues/79605 for examples why this may // occur. expect(() => element.state, throwsA(isA<TypeError>())); expect(() => element.widget, throwsA(isA<TypeError>())); }); testWidgets('LayerLink can be swapped between parent and child container layers', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/96959. final LayerLink link = LayerLink(); await tester.pumpWidget(_TestLeaderLayerWidget( link: link, child: const _TestLeaderLayerWidget( child: Placeholder(), ) )); expect(tester.takeException(), isNull); // Swaps the layer link. await tester.pumpWidget(_TestLeaderLayerWidget( child: _TestLeaderLayerWidget( link: link, child: const Placeholder(), ), )); expect(tester.takeException(), isNull); }); testWidgets('Deactivate and activate are called correctly', (WidgetTester tester) async { final List<String> states = <String>[]; Widget build([Key? key]) { return StatefulWidgetSpy( key: key, onInitState: (BuildContext context) { states.add('initState'); }, onDidUpdateWidget: (BuildContext context) { states.add('didUpdateWidget'); }, onDeactivate: (BuildContext context) { states.add('deactivate'); }, onActivate: (BuildContext context) { states.add('activate'); }, onBuild: (BuildContext context) { states.add('build'); }, onDispose: (BuildContext context) { states.add('dispose'); }, ); } Future<void> pumpWidget(Widget widget) { states.clear(); return tester.pumpWidget(widget); } await pumpWidget(build()); expect(states, <String>['initState', 'build']); await pumpWidget(Container(child: build())); expect(states, <String>['deactivate', 'initState', 'build', 'dispose']); await pumpWidget(Container()); expect(states, <String>['deactivate', 'dispose']); final GlobalKey key = GlobalKey(); await pumpWidget(build(key)); expect(states, <String>['initState', 'build']); await pumpWidget(Container(child: build(key))); expect(states, <String>['deactivate', 'activate', 'didUpdateWidget', 'build']); await pumpWidget(Container()); expect(states, <String>['deactivate', 'dispose']); }); testWidgets('Element.deactivate reports its deactivation to the InheritedElement it depends on', (WidgetTester tester) async { final List<Key> removedDependentWidgetKeys = <Key>[]; InheritedElement elementCreator(InheritedWidget widget) { return _InheritedElementSpy( widget, onRemoveDependent: (Element dependent) { removedDependentWidgetKeys.add(dependent.widget.key!); }, ); } Widget builder(BuildContext context) { context.dependOnInheritedWidgetOfExactType<Inherited>(); return Container(); } await tester.pumpWidget( Inherited( 0, elementCreator: elementCreator, child: Column( children: <Widget>[ Builder( key: const Key('dependent'), builder: builder, ), ], ), ), ); expect(removedDependentWidgetKeys, isEmpty); await tester.pumpWidget( Inherited( 0, elementCreator: elementCreator, child: Column( children: <Widget>[ Container(), ], ), ), ); expect(removedDependentWidgetKeys, hasLength(1)); expect(removedDependentWidgetKeys.first, const Key('dependent')); }); testWidgets('RenderObjectElement.unmount disposes of its renderObject', (WidgetTester tester) async { await tester.pumpWidget(const Placeholder()); final RenderObjectElement element = tester.allElements.whereType<RenderObjectElement>().last; final RenderObject renderObject = element.renderObject; expect(renderObject.debugDisposed, false); await tester.pumpWidget(Container()); expect(() => element.renderObject, throwsAssertionError); expect(renderObject.debugDisposed, true); }); testWidgets('Getting the render object of an unmounted element throws', (WidgetTester tester) async { await tester.pumpWidget(const _StatefulLeaf()); final StatefulElement element = tester.element<StatefulElement>(find.byType(_StatefulLeaf)); expect(element.state, isA<State<_StatefulLeaf>>()); expect(element.widget, isA<_StatefulLeaf>()); // Replace the widget tree to unmount the element. await tester.pumpWidget(Container()); expect( () => element.findRenderObject(), throwsA(isA<FlutterError>().having( (FlutterError error) => error.message, 'message', equalsIgnoringHashCodes(''' Cannot get renderObject of inactive element. In order for an element to have a valid renderObject, it must be active, which means it is part of the tree. Instead, this element is in the _ElementLifecycle.defunct state. If you called this method from a State object, consider guarding it with State.mounted. The findRenderObject() method was called for the following element: StatefulElement#00000(DEFUNCT)'''), )), ); }); testWidgets('Elements use the identity hashCode', experimentalLeakTesting: LeakTesting.settings.withIgnoredAll(), // The test leaks by design. (WidgetTester tester) async { final StatefulElement statefulElement = StatefulElement(const _StatefulLeaf()); expect(statefulElement.hashCode, identityHashCode(statefulElement)); final StatelessElement statelessElement = StatelessElement(const Placeholder()); expect(statelessElement.hashCode, identityHashCode(statelessElement)); final InheritedElement inheritedElement = InheritedElement( const Directionality(textDirection: TextDirection.ltr, child: Placeholder()), ); expect(inheritedElement.hashCode, identityHashCode(inheritedElement)); }); testWidgets('doesDependOnInheritedElement', (WidgetTester tester) async { final _TestInheritedElement ancestor = _TestInheritedElement(const Directionality( textDirection: TextDirection.ltr, child: Placeholder(), )); final _TestInheritedElement child = _TestInheritedElement(const Directionality( textDirection: TextDirection.ltr, child: Placeholder(), )); expect(child.doesDependOnInheritedElement(ancestor), isFalse); child.dependOnInheritedElement(ancestor); expect(child.doesDependOnInheritedElement(ancestor), isTrue); }); testWidgets( 'MultiChildRenderObjectElement.updateChildren test', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/120762. final GlobalKey globalKey = GlobalKey(); await tester.pumpWidget(Column( children: <Widget>[ const SizedBox(), SizedBox(key: globalKey), const SizedBox(), ], )); expect(tester.takeException(), isNull); await tester.pumpWidget(Column( children: <Widget>[ const SizedBox(), const SizedBox(), SizedBox(child: SizedBox(key: globalKey)), ], )); expect(tester.takeException(), isNull); }); } class _TestInheritedElement extends InheritedElement { _TestInheritedElement(super.widget); @override bool doesDependOnInheritedElement(InheritedElement element) { return super.doesDependOnInheritedElement(element); } } class _WidgetWithNoVisitChildren extends StatelessWidget { const _WidgetWithNoVisitChildren(this.child); final Widget child; @override Widget build(BuildContext context) => child; @override _WidgetWithNoVisitChildrenElement createElement() => _WidgetWithNoVisitChildrenElement(this); } class _WidgetWithNoVisitChildrenElement extends StatelessElement { _WidgetWithNoVisitChildrenElement(_WidgetWithNoVisitChildren super.widget); @override void visitChildren(ElementVisitor visitor) { // This implementation is intentionally buggy, to test that an error message is // shown when this situation occurs. // The superclass has the correct implementation (calling `visitor(_child)`), so // we don't call it here. } } class _StatefulLeaf extends StatefulWidget { const _StatefulLeaf({ super.key }); @override State<_StatefulLeaf> createState() => _StatefulLeafState(); } class _StatefulLeafState extends State<_StatefulLeaf> { void markNeedsBuild() { setState(() { }); } @override Widget build(BuildContext context) { return const SizedBox.shrink(); } } class Decorate extends StatefulWidget { const Decorate({ super.key, required this.didChangeDependencies, required this.build, }); final void Function(bool isInBuild) didChangeDependencies; final void Function(bool isInBuild) build; @override State<Decorate> createState() => _DecorateState(); @override DecorateElement createElement() => DecorateElement(this); } class DecorateElement extends StatefulElement { DecorateElement(Decorate super.widget); bool isDecorated = false; @override Widget build() { try { isDecorated = true; return super.build(); } finally { isDecorated = false; } } } class _DecorateState extends State<Decorate> { @override void didChangeDependencies() { super.didChangeDependencies(); widget.didChangeDependencies.call((context as DecorateElement).isDecorated); } @override Widget build(covariant DecorateElement context) { context.dependOnInheritedWidgetOfExactType<Inherited>(); widget.build.call(context.isDecorated); return Container(); } } class DirtyElementWithCustomBuildOwner extends Element { DirtyElementWithCustomBuildOwner(BuildOwner buildOwner, super.widget) : _owner = buildOwner; final BuildOwner _owner; @override BuildOwner get owner => _owner; @override bool get dirty => true; @override bool get debugDoingBuild => throw UnimplementedError(); } class Inherited extends InheritedWidget { const Inherited(this.value, {super.key, required super.child, this.elementCreator}); final int? value; final InheritedElement Function(Inherited widget)? elementCreator; @override bool updateShouldNotify(Inherited oldWidget) => oldWidget.value != value; @override InheritedElement createElement() { if (elementCreator != null) { return elementCreator!(this); } return super.createElement(); } } class _InheritedElementSpy extends InheritedElement { _InheritedElementSpy(super.widget, {this.onRemoveDependent}); final void Function(Element element)? onRemoveDependent; @override void removeDependent(Element dependent) { super.removeDependent(dependent); onRemoveDependent?.call(dependent); } } class DependentStatefulWidget extends StatefulWidget { const DependentStatefulWidget({super.key}); @override State<StatefulWidget> createState() => DependentState(); } class DependentState extends State<DependentStatefulWidget> { int didChangeDependenciesCount = 0; int deactivatedCount = 0; @override void didChangeDependencies() { super.didChangeDependencies(); didChangeDependenciesCount += 1; } @override Widget build(BuildContext context) { context.dependOnInheritedWidgetOfExactType<Inherited>(); return const SizedBox(); } @override void deactivate() { super.deactivate(); deactivatedCount += 1; } } class SwapKeyWidget extends StatefulWidget { const SwapKeyWidget({super.key, this.childKey}); final Key? childKey; @override SwapKeyWidgetState createState() => SwapKeyWidgetState(); } class SwapKeyWidgetState extends State<SwapKeyWidget> { Key? key; @override void initState() { super.initState(); key = widget.childKey; } void swapKey(Key newKey) { setState(() { key = newKey; }); } @override Widget build(BuildContext context) { return Container(key: key); } } class _Stateful extends StatefulWidget { const _Stateful({required this.child, this.onElementRebuild}); final Text child; final ElementRebuildCallback? onElementRebuild; @override State<StatefulWidget> createState() => _StatefulState(); @override StatefulElement createElement() => StatefulElementSpy(this); } class _StatefulState extends State<_Stateful> { void rebuild() => setState(() {}); @override Widget build(BuildContext context) { return widget.child; } } class StatefulElementSpy extends StatefulElement { StatefulElementSpy(super.widget); _Stateful get _statefulWidget => widget as _Stateful; @override void rebuild({bool force = false}) { _statefulWidget.onElementRebuild?.call(this); super.rebuild(force: force); } } class StatelessWidgetSpy extends StatelessWidget { const StatelessWidgetSpy({ super.key, required this.onBuild, }); final void Function(BuildContext) onBuild; @override Widget build(BuildContext context) { onBuild(context); return Container(); } } class StatefulWidgetSpy extends StatefulWidget { const StatefulWidgetSpy({ super.key, this.onBuild, this.onInitState, this.onDidChangeDependencies, this.onDispose, this.onDeactivate, this.onActivate, this.onDidUpdateWidget, }); final void Function(BuildContext)? onBuild; final void Function(BuildContext)? onInitState; final void Function(BuildContext)? onDidChangeDependencies; final void Function(BuildContext)? onDispose; final void Function(BuildContext)? onDeactivate; final void Function(BuildContext)? onActivate; final void Function(BuildContext)? onDidUpdateWidget; @override State<StatefulWidgetSpy> createState() => _StatefulWidgetSpyState(); } class _StatefulWidgetSpyState extends State<StatefulWidgetSpy> { @override void initState() { super.initState(); widget.onInitState?.call(context); } @override void deactivate() { super.deactivate(); widget.onDeactivate?.call(context); } @override void activate() { super.activate(); widget.onActivate?.call(context); } @override void dispose() { super.dispose(); widget.onDispose?.call(context); } @override void didChangeDependencies() { super.didChangeDependencies(); widget.onDidChangeDependencies?.call(context); } @override void didUpdateWidget(StatefulWidgetSpy oldWidget) { super.didUpdateWidget(oldWidget); widget.onDidUpdateWidget?.call(context); } @override Widget build(BuildContext context) { widget.onBuild?.call(context); return Container(); } } class RenderObjectWidgetSpy extends LeafRenderObjectWidget { const RenderObjectWidgetSpy({ super.key, this.onCreateRenderObject, this.onUpdateRenderObject, this.onDidUnmountRenderObject, }); final void Function(BuildContext)? onCreateRenderObject; final void Function(BuildContext)? onUpdateRenderObject; final void Function()? onDidUnmountRenderObject; @override RenderObject createRenderObject(BuildContext context) { onCreateRenderObject?.call(context); return FakeLeafRenderObject(); } @override void updateRenderObject(BuildContext context, RenderObject renderObject) { onUpdateRenderObject?.call(context); } @override void didUnmountRenderObject(RenderObject renderObject) { super.didUnmountRenderObject(renderObject); onDidUnmountRenderObject?.call(); } } class FakeLeafRenderObject extends RenderBox { @override Size computeDryLayout(BoxConstraints constraints) { return constraints.biggest; } @override void performLayout() { size = constraints.biggest; } } class TestRenderObjectElement extends RenderObjectElement { TestRenderObjectElement() : super(Table()); @override void insertRenderObjectChild(covariant RenderObject child, covariant Object? slot) { } @override void moveRenderObjectChild(covariant RenderObject child, covariant Object? oldSlot, covariant Object? newSlot) { } @override void removeRenderObjectChild(covariant RenderObject child, covariant Object? slot) { } } class _EmptyWidget extends Widget { const _EmptyWidget(); @override Element createElement() => _EmptyElement(this); } class _EmptyElement extends Element { _EmptyElement(_EmptyWidget super.widget); @override bool get debugDoingBuild => false; } class _TestLeaderLayerWidget extends SingleChildRenderObjectWidget { const _TestLeaderLayerWidget({ this.link, super.child, }); final LayerLink? link; @override _RenderTestLeaderLayerWidget createRenderObject(BuildContext context) { return _RenderTestLeaderLayerWidget( link: link, ); } @override void updateRenderObject(BuildContext context, _RenderTestLeaderLayerWidget renderObject) { renderObject.link = link; } } class _RenderTestLeaderLayerWidget extends RenderProxyBox { _RenderTestLeaderLayerWidget({ LayerLink? link, RenderBox? child, }) : _link = link, super(child); LayerLink? get link => _link; LayerLink? _link; set link(LayerLink? value) { if (_link == value) { return; } _link = value; markNeedsPaint(); } @override bool get isRepaintBoundary => true; @override void paint(PaintingContext context, Offset offset) { super.paint(context, offset); if (_link != null) { context.pushLayer(LeaderLayer(link: _link!, offset: offset),(_, __){}, Offset.zero); } } }
flutter/packages/flutter/test/widgets/framework_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/framework_test.dart", "repo_id": "flutter", "token_count": 31591 }
695
// 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 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('IconThemeData control test', () { const IconThemeData data = IconThemeData( size: 16.0, fill: 0.5, weight: 600, grade: 25, opticalSize: 45, color: Color(0xAAAAAAAA), opacity: 0.5, shadows: <Shadow>[Shadow(color: Color(0xAAAAAAAA), blurRadius: 1.0, offset: Offset(1.0, 1.0))], ); expect(data, hasOneLineDescription); expect(data, equals(data.copyWith())); expect(data.hashCode, equals(data.copyWith().hashCode)); final IconThemeData lerped = IconThemeData.lerp(data, const IconThemeData.fallback(), 0.25); expect(lerped.size, 18.0); expect(lerped.fill, 0.375); expect(lerped.weight, 550.0); expect(lerped.grade, 18.75); expect(lerped.opticalSize, 45.75); expect(lerped.color, const Color(0xBF7F7F7F)); expect(lerped.opacity, 0.625); expect(lerped.shadows, const <Shadow>[Shadow(color: Color(0xAAAAAAAA), blurRadius: 0.75, offset: Offset(0.75, 0.75))]); }); group('IconThemeData lerp', () { const IconThemeData data = IconThemeData( size: 16.0, fill: 0.5, weight: 600, grade: 25, opticalSize: 45, color: Color(0xFFFFFFFF), opacity: 1.0, shadows: <Shadow>[Shadow(color: Color(0xFFFFFFFF), blurRadius: 1.0, offset: Offset(1.0, 1.0))], ); test('with first null', () { final IconThemeData lerped = IconThemeData.lerp(null, data, 0.25); expect(lerped.size, 4.0); expect(lerped.fill, 0.125); expect(lerped.weight, 150.0); expect(lerped.grade, 6.25); expect(lerped.opticalSize, 11.25); expect(lerped.color, const Color(0x40FFFFFF)); expect(lerped.opacity, 0.25); expect(lerped.shadows, const <Shadow>[Shadow(color: Color(0xFFFFFFFF), blurRadius: 0.25, offset: Offset(0.25, 0.25))]); }); test('IconThemeData lerp special cases', () { expect(IconThemeData.lerp(null, null, 0), const IconThemeData()); const IconThemeData data = IconThemeData(); expect(identical(IconThemeData.lerp(data, data, 0.5), data), true); }); test('with second null', () { final IconThemeData lerped = IconThemeData.lerp(data, null, 0.25); expect(lerped.size, 12.0); expect(lerped.fill, 0.375); expect(lerped.weight, 450.0); expect(lerped.grade, 18.75); expect(lerped.opticalSize, 33.75); expect(lerped.color, const Color(0xBFFFFFFF)); expect(lerped.opacity, 0.75); expect(lerped.shadows, const <Shadow>[Shadow(color: Color(0xFFFFFFFF), blurRadius: 0.75, offset: Offset(0.75, 0.75))]); }); test('with both null', () { final IconThemeData lerped = IconThemeData.lerp(null, null, 0.25); expect(lerped.size, null); expect(lerped.fill, null); expect(lerped.weight, null); expect(lerped.grade, null); expect(lerped.opticalSize, null); expect(lerped.color, null); expect(lerped.opacity, null); expect(lerped.shadows, null); }); }); test('Throws if given invalid values', () { expect(() => IconThemeData(fill: -0.1), throwsAssertionError); expect(() => IconThemeData(fill: 1.1), throwsAssertionError); expect(() => IconThemeData(weight: -0.1), throwsAssertionError); expect(() => IconThemeData(weight: 0.0), throwsAssertionError); expect(() => IconThemeData(opticalSize: -0.1), throwsAssertionError); expect(() => IconThemeData(opticalSize: 0), throwsAssertionError); }); }
flutter/packages/flutter/test/widgets/icon_theme_data_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/icon_theme_data_test.dart", "repo_id": "flutter", "token_count": 1527 }
696
// 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 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; List<String> ancestors = <String>[]; class TestWidget extends StatefulWidget { const TestWidget({ super.key }); @override TestWidgetState createState() => TestWidgetState(); } class TestWidgetState extends State<TestWidget> { @override void initState() { super.initState(); context.visitAncestorElements((Element element) { ancestors.add(element.widget.runtimeType.toString()); return true; }); } @override Widget build(BuildContext context) => Container(); } void main() { testWidgets('initState() is called when we are in the tree', (WidgetTester tester) async { await tester.pumpWidget(const Parent(child: TestWidget())); expect(ancestors, containsAllInOrder(<String>['Parent', 'View', 'RootWidget'])); }); } class Parent extends StatelessWidget { const Parent({ super.key, required this.child }); final Widget child; @override Widget build(BuildContext context) => child; }
flutter/packages/flutter/test/widgets/init_state_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/init_state_test.dart", "repo_id": "flutter", "token_count": 375 }
697
// 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 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('ListView can handle shrinking top elements', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( cacheExtent: 0.0, controller: controller, children: const <Widget>[ SizedBox(height: 400.0, child: Text('1')), SizedBox(height: 400.0, child: Text('2')), SizedBox(height: 400.0, child: Text('3')), SizedBox(height: 400.0, child: Text('4')), SizedBox(height: 400.0, child: Text('5')), SizedBox(height: 400.0, child: Text('6')), ], ), ), ); controller.jumpTo(1000.0); await tester.pump(); expect(tester.getTopLeft(find.text('4')).dy, equals(200.0)); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( cacheExtent: 0.0, controller: controller, children: const <Widget>[ SizedBox(height: 200.0, child: Text('1')), SizedBox(height: 400.0, child: Text('2')), SizedBox(height: 400.0, child: Text('3')), SizedBox(height: 400.0, child: Text('4')), SizedBox(height: 400.0, child: Text('5')), SizedBox(height: 400.0, child: Text('6')), ], ), ), ); expect(controller.offset, equals(1000.0)); expect(tester.getTopLeft(find.text('4')).dy, equals(200.0)); controller.jumpTo(300.0); await tester.pump(); expect(controller.offset, equals(300.0)); expect(tester.getTopLeft(find.text('2')).dy, equals(100.0)); controller.jumpTo(50.0); await tester.pump(); expect(controller.offset, equals(0.0)); expect(tester.getTopLeft(find.text('2')).dy, equals(200.0)); }); testWidgets('ListView can handle shrinking top elements with cache extent', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( controller: controller, children: const <Widget>[ SizedBox(height: 400.0, child: Text('1')), SizedBox(height: 400.0, child: Text('2')), SizedBox(height: 400.0, child: Text('3')), SizedBox(height: 400.0, child: Text('4')), SizedBox(height: 400.0, child: Text('5')), SizedBox(height: 400.0, child: Text('6')), ], ), ), ); controller.jumpTo(1000.0); await tester.pump(); expect(tester.getTopLeft(find.text('4')).dy, equals(200.0)); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( controller: controller, children: const <Widget>[ SizedBox(height: 200.0, child: Text('1')), SizedBox(height: 400.0, child: Text('2')), SizedBox(height: 400.0, child: Text('3')), SizedBox(height: 400.0, child: Text('4')), SizedBox(height: 400.0, child: Text('5')), SizedBox(height: 400.0, child: Text('6')), ], ), ), ); expect(controller.offset, equals(1000.0)); expect(tester.getTopLeft(find.text('4')).dy, equals(200.0)); controller.jumpTo(300.0); await tester.pump(); expect(controller.offset, equals(250.0)); expect(tester.getTopLeft(find.text('2')).dy, equals(-50.0)); controller.jumpTo(50.0); await tester.pump(); expect(controller.offset, equals(50.0)); expect(tester.getTopLeft(find.text('2')).dy, equals(150.0)); }); testWidgets('ListView can handle inserts at 0', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( controller: controller, children: const <Widget>[ SizedBox(height: 400.0, child: Text('0')), SizedBox(height: 400.0, child: Text('1')), SizedBox(height: 400.0, child: Text('2')), SizedBox(height: 400.0, child: Text('3')), ], ), ), ); expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsOneWidget); expect(find.text('2'), findsNothing); expect(find.text('3'), findsNothing); final Finder findItemA = find.descendant(of: find.byType(SizedBox), matching: find.text('A')); final Finder findItemB = find.descendant(of: find.byType(SizedBox), matching: find.text('B')); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( controller: controller, children: const <Widget>[ SizedBox(height: 10.0, child: Text('A')), SizedBox(height: 10.0, child: Text('B')), SizedBox(height: 400.0, child: Text('0')), SizedBox(height: 400.0, child: Text('1')), SizedBox(height: 400.0, child: Text('2')), SizedBox(height: 400.0, child: Text('3')), ], ), ), ); expect(find.text('A'), findsOneWidget); expect(find.text('B'), findsOneWidget); expect(tester.getTopLeft(findItemA).dy, 0.0); expect(tester.getBottomRight(findItemA).dy, 10.0); expect(tester.getTopLeft(findItemB).dy, 10.0); expect(tester.getBottomRight(findItemB).dy, 20.0); controller.jumpTo(1200.0); await tester.pump(); expect(find.text('A'), findsNothing); expect(find.text('B'), findsNothing); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( controller: controller, children: const <Widget>[ SizedBox(height: 200.0, child: Text('A')), SizedBox(height: 200.0, child: Text('B')), SizedBox(height: 400.0, child: Text('0')), SizedBox(height: 400.0, child: Text('1')), SizedBox(height: 400.0, child: Text('2')), SizedBox(height: 400.0, child: Text('3')), ], ), ), ); expect(find.text('A'), findsNothing); expect(find.text('B'), findsNothing); // Scrolling to 0 causes items A and B to underflow (extend below // scrollOffset 0) because their heights have grown from 10 - 200. // RenderSliver list corrects the scroll offset in this case. Only item // B will become visible and item B's bottom edge will still appear // where it was when its height was 10.0. controller.jumpTo(0.0); await tester.pump(); expect(find.text('B'), findsOneWidget); expect(controller.offset, greaterThan(0.0)); // RenderSliverList corrected the offset. expect(tester.getTopLeft(findItemB).dy, -180.0); expect(tester.getBottomRight(findItemB).dy, 20.0); controller.jumpTo(0.0); await tester.pump(); expect(find.text('A'), findsOneWidget); expect(find.text('B'), findsOneWidget); expect(tester.getTopLeft(findItemA).dy, 0.0); expect(tester.getBottomRight(findItemA).dy, 200.0); expect(tester.getTopLeft(findItemB).dy, 200.0); expect(tester.getBottomRight(findItemB).dy, 400.0); }); }
flutter/packages/flutter/test/widgets/list_view_correction_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/list_view_correction_test.dart", "repo_id": "flutter", "token_count": 3406 }
698
// 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. @Tags(<String>['reduced-test-set']) library; import 'package:fake_async/fake_async.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; class _MockAnimationController extends AnimationController { _MockAnimationController() : super(duration: const Duration(minutes: 1), vsync: const TestVSync()); int forwardCalls = 0; int reverseCalls = 0; @override TickerFuture forward({double? from}) { forwardCalls++; return super.forward(from: from); } @override TickerFuture reverse({double? from}) { reverseCalls++; return super.reverse(from: from); } } void main() { Future<T> runFakeAsync<T>(Future<T> Function(FakeAsync time) f) async { return FakeAsync().run((FakeAsync time) async { bool pump = true; final Future<T> future = f(time).whenComplete(() => pump = false); while (pump) { time.flushMicrotasks(); } return future; }); } group('Raw Magnifier', () { testWidgets('should render with correct focal point and decoration', (WidgetTester tester) async { final Key appKey = UniqueKey(); const Size magnifierSize = Size(100, 100); const Offset magnifierFocalPoint = Offset(50, 50); const Offset magnifierPosition = Offset(200, 200); const double magnificationScale = 2; await tester.pumpWidget(MaterialApp( key: appKey, home: Container( color: Colors.orange, width: double.infinity, height: double.infinity, child: Stack( children: <Widget>[ Positioned( // Positioned so that it is right in the center of the magnifier // focal point. left: magnifierPosition.dx + magnifierFocalPoint.dx, top: magnifierPosition.dy + magnifierFocalPoint.dy, child: Container( color: Colors.pink, // Since it is the size of the magnifier but over its // magnificationScale, it should take up the whole magnifier. width: (magnifierSize.width * 1.5) / magnificationScale, height: (magnifierSize.height * 1.5) / magnificationScale, ), ), Positioned( left: magnifierPosition.dx, top: magnifierPosition.dy, child: const RawMagnifier( size: magnifierSize, focalPointOffset: magnifierFocalPoint, magnificationScale: magnificationScale, decoration: MagnifierDecoration(shadows: <BoxShadow>[ BoxShadow( spreadRadius: 10, blurRadius: 10, color: Colors.green, offset: Offset(5, 5), ), ]), ), ), ], ), ))); await tester.pumpAndSettle(); // Should look like an orange screen, with two pink boxes. // One pink box is in the magnifier (so has a green shadow) and is double // size (from magnification). Also, the magnifier should be slightly orange // since it has opacity. await expectLater( find.byKey(appKey), matchesGoldenFile('widgets.magnifier.styled.png'), ); }, skip: kIsWeb); // [intended] Bdf does not display on web. group('transition states', () { final AnimationController animationController = AnimationController( vsync: const TestVSync(), duration: const Duration(minutes: 2)); final MagnifierController magnifierController = MagnifierController(); tearDown(() { animationController.value = 0; magnifierController.hide(); magnifierController.removeFromOverlay(); }); testWidgets( 'should immediately remove from overlay on no animation controller', (WidgetTester tester) async { await runFakeAsync((FakeAsync async) async { const RawMagnifier testMagnifier = RawMagnifier( size: Size(100, 100), ); await tester.pumpWidget(const MaterialApp( home: Placeholder(), )); final BuildContext context = tester.firstElement(find.byType(Placeholder)); magnifierController.show( context: context, builder: (BuildContext context) => testMagnifier, ); WidgetsBinding.instance.scheduleFrame(); await tester.pump(); expect(magnifierController.overlayEntry, isNot(isNull)); magnifierController.hide(); WidgetsBinding.instance.scheduleFrame(); await tester.pump(); expect(magnifierController.overlayEntry, isNull); }); }); testWidgets('should update shown based on animation status', (WidgetTester tester) async { await runFakeAsync((FakeAsync async) async { final MagnifierController magnifierController = MagnifierController(animationController: animationController); const RawMagnifier testMagnifier = RawMagnifier( size: Size(100, 100), ); await tester.pumpWidget(const MaterialApp( home: Placeholder(), )); final BuildContext context = tester.firstElement(find.byType(Placeholder)); magnifierController.show( context: context, builder: (BuildContext context) => testMagnifier, ); WidgetsBinding.instance.scheduleFrame(); await tester.pump(); // No time has passed, so the animation controller has not completed. expect(magnifierController.animationController?.status, AnimationStatus.forward); expect(magnifierController.shown, true); async.elapse(animationController.duration!); await tester.pumpAndSettle(); expect(magnifierController.animationController?.status, AnimationStatus.completed); expect(magnifierController.shown, true); magnifierController.hide(); WidgetsBinding.instance.scheduleFrame(); await tester.pump(); expect(magnifierController.animationController?.status, AnimationStatus.reverse); expect(magnifierController.shown, false); async.elapse(animationController.duration!); await tester.pumpAndSettle(); expect(magnifierController.animationController?.status, AnimationStatus.dismissed); expect(magnifierController.shown, false); }); }); }); }); group('magnifier controller', () { final MagnifierController magnifierController = MagnifierController(); tearDown(() { magnifierController.removeFromOverlay(); }); group('show', () { testWidgets('should insert below below widget', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Text('text'), )); final BuildContext context = tester.firstElement(find.byType(Text)); final Widget fakeMagnifier = Placeholder(key: UniqueKey()); final Widget fakeBefore = Placeholder(key: UniqueKey()); final OverlayEntry fakeBeforeOverlayEntry = OverlayEntry(builder: (_) => fakeBefore); addTearDown(() => fakeBeforeOverlayEntry..remove()..dispose()); Overlay.of(context).insert(fakeBeforeOverlayEntry); magnifierController.show( context: context, builder: (_) => fakeMagnifier, below: fakeBeforeOverlayEntry); WidgetsBinding.instance.scheduleFrame(); await tester.pumpAndSettle(); final Iterable<Element> allOverlayChildren = find .descendant( of: find.byType(Overlay), matching: find.byType(Placeholder)) .evaluate(); // Expect the magnifier to be the first child, even though it was inserted // after the fakeBefore. expect(allOverlayChildren.last.widget.key, fakeBefore.key); expect(allOverlayChildren.first.widget.key, fakeMagnifier.key); }); testWidgets('should insert newly built widget without animating out if overlay != null', (WidgetTester tester) async { await runFakeAsync((FakeAsync async) async { final _MockAnimationController animationController = _MockAnimationController(); addTearDown(animationController.dispose); const RawMagnifier testMagnifier = RawMagnifier( size: Size(100, 100), ); const RawMagnifier testMagnifier2 = RawMagnifier( size: Size(100, 100), ); await tester.pumpWidget(const MaterialApp( home: Placeholder(), )); final BuildContext context = tester.firstElement(find.byType(Placeholder)); magnifierController.show( context: context, builder: (BuildContext context) => testMagnifier, ); WidgetsBinding.instance.scheduleFrame(); await tester.pump(); async.elapse(animationController.duration!); await tester.pumpAndSettle(); magnifierController.show(context: context, builder: (_) => testMagnifier2); WidgetsBinding.instance.scheduleFrame(); await tester.pump(); expect(animationController.reverseCalls, 0, reason: 'should not have called reverse on animation controller due to force remove'); expect(find.byWidget(testMagnifier2), findsOneWidget); }); }); }); group('shift within bounds', () { final List<Rect> boundsRects = <Rect>[ const Rect.fromLTRB(0, 0, 100, 100), const Rect.fromLTRB(0, 0, 100, 100), const Rect.fromLTRB(0, 0, 100, 100), const Rect.fromLTRB(0, 0, 100, 100), ]; final List<Rect> inputRects = <Rect>[ const Rect.fromLTRB(-100, -100, -80, -80), const Rect.fromLTRB(0, 0, 20, 20), const Rect.fromLTRB(110, 0, 120, 10), const Rect.fromLTRB(110, 110, 120, 120) ]; final List<Rect> outputRects = <Rect>[ const Rect.fromLTRB(0, 0, 20, 20), const Rect.fromLTRB(0, 0, 20, 20), const Rect.fromLTRB(90, 0, 100, 10), const Rect.fromLTRB(90, 90, 100, 100) ]; for (int i = 0; i < boundsRects.length; i++) { test( 'should shift ${inputRects[i]} to ${outputRects[i]} for bounds ${boundsRects[i]}', () { final Rect outputRect = MagnifierController.shiftWithinBounds( bounds: boundsRects[i], rect: inputRects[i]); expect(outputRect, outputRects[i]); }); } }); }); }
flutter/packages/flutter/test/widgets/magnifier_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/magnifier_test.dart", "repo_id": "flutter", "token_count": 4896 }
699
// 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 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; class TestOverlayRoute extends OverlayRoute<void> { TestOverlayRoute({ super.settings }); @override Iterable<OverlayEntry> createOverlayEntries() sync* { yield OverlayEntry(builder: _build); } Widget _build(BuildContext context) => const Text('Overlay'); } class PersistentBottomSheetTest extends StatefulWidget { const PersistentBottomSheetTest({ super.key }); @override PersistentBottomSheetTestState createState() => PersistentBottomSheetTestState(); } class PersistentBottomSheetTestState extends State<PersistentBottomSheetTest> { final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>(); bool setStateCalled = false; void showBottomSheet() { _scaffoldKey.currentState!.showBottomSheet((BuildContext context) { return const Text('bottomSheet'); }) .closed.whenComplete(() { setState(() { setStateCalled = true; }); }); } @override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, body: const Text('Sheet'), ); } } void main() { testWidgets('Check onstage/offstage handling around transitions', (WidgetTester tester) async { final GlobalKey containerKey1 = GlobalKey(); final GlobalKey containerKey2 = GlobalKey(); final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ '/': (_) => Container(key: containerKey1, child: const Text('Home')), '/settings': (_) => Container(key: containerKey2, child: const Text('Settings')), }; await tester.pumpWidget(MaterialApp(routes: routes)); expect(find.text('Home'), isOnstage); expect(find.text('Settings'), findsNothing); expect(find.text('Overlay'), findsNothing); expect(Navigator.canPop(containerKey1.currentContext!), isFalse); Navigator.pushNamed(containerKey1.currentContext!, '/settings'); expect(Navigator.canPop(containerKey1.currentContext!), isTrue); await tester.pump(); expect(find.text('Home'), isOnstage); expect(find.text('Settings', skipOffstage: false), isOffstage); expect(find.text('Overlay'), findsNothing); await tester.pump(const Duration(milliseconds: 16)); expect(find.text('Home'), isOnstage); expect(find.text('Settings'), isOnstage); expect(find.text('Overlay'), findsNothing); await tester.pump(const Duration(seconds: 1)); expect(find.text('Home'), findsNothing); expect(find.text('Settings'), isOnstage); expect(find.text('Overlay'), findsNothing); Navigator.push(containerKey2.currentContext!, TestOverlayRoute()); await tester.pump(); expect(find.text('Home'), findsNothing); expect(find.text('Settings'), isOnstage); expect(find.text('Overlay'), isOnstage); await tester.pump(const Duration(seconds: 1)); expect(find.text('Home'), findsNothing); expect(find.text('Settings'), isOnstage); expect(find.text('Overlay'), isOnstage); expect(Navigator.canPop(containerKey2.currentContext!), isTrue); Navigator.pop(containerKey2.currentContext!); await tester.pump(); expect(find.text('Home'), findsNothing); expect(find.text('Settings'), isOnstage); expect(find.text('Overlay'), findsNothing); await tester.pump(const Duration(seconds: 1)); expect(find.text('Home'), findsNothing); expect(find.text('Settings'), isOnstage); expect(find.text('Overlay'), findsNothing); expect(Navigator.canPop(containerKey2.currentContext!), isTrue); Navigator.pop(containerKey2.currentContext!); await tester.pump(); await tester.pump(); expect(find.text('Home'), isOnstage); expect(find.text('Settings'), isOnstage); expect(find.text('Overlay'), findsNothing); await tester.pump(const Duration(seconds: 1)); expect(find.text('Home'), isOnstage); expect(find.text('Settings'), findsNothing); expect(find.text('Overlay'), findsNothing); expect(Navigator.canPop(containerKey1.currentContext!), isFalse); }); testWidgets('Check back gesture disables Heroes', (WidgetTester tester) async { final GlobalKey containerKey1 = GlobalKey(); final GlobalKey containerKey2 = GlobalKey(); const String kHeroTag = 'hero'; final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ '/': (_) => Scaffold( key: containerKey1, body: const ColoredBox( color: Color(0xff00ffff), child: Hero( tag: kHeroTag, child: Text('Home'), ), ), ), '/settings': (_) => Scaffold( key: containerKey2, body: Container( padding: const EdgeInsets.all(100.0), color: const Color(0xffff00ff), child: const Hero( tag: kHeroTag, child: Text('Settings'), ), ), ), }; await tester.pumpWidget(MaterialApp(routes: routes)); Navigator.pushNamed(containerKey1.currentContext!, '/settings'); await tester.pump(); await tester.pump(const Duration(milliseconds: 16)); expect(find.text('Settings'), isOnstage); // Settings text is heroing to its new location Offset settingsOffset = tester.getTopLeft(find.text('Settings')); expect(settingsOffset.dx, greaterThan(0.0)); expect(settingsOffset.dx, lessThan(100.0)); expect(settingsOffset.dy, greaterThan(0.0)); expect(settingsOffset.dy, lessThan(100.0)); await tester.pump(const Duration(seconds: 1)); expect(find.text('Home'), findsNothing); expect(find.text('Settings'), isOnstage); // Drag from left edge to invoke the gesture. final TestGesture gesture = await tester.startGesture(const Offset(5.0, 100.0)); await gesture.moveBy(const Offset(50.0, 0.0)); await tester.pump(); // Home is now visible. expect(find.text('Home'), isOnstage); expect(find.text('Settings'), isOnstage); // Home page is sliding in from the left, no heroes. final Offset homeOffset = tester.getTopLeft(find.text('Home')); expect(homeOffset.dx, lessThan(0.0)); expect(homeOffset.dy, 0.0); // Settings page is sliding off to the right, no heroes. settingsOffset = tester.getTopLeft(find.text('Settings')); expect(settingsOffset.dx, greaterThan(100.0)); expect(settingsOffset.dy, 100.0); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets("Check back gesture doesn't start during transitions", (WidgetTester tester) async { final GlobalKey containerKey1 = GlobalKey(); final GlobalKey containerKey2 = GlobalKey(); final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ '/': (_) => Scaffold(key: containerKey1, body: const Text('Home')), '/settings': (_) => Scaffold(key: containerKey2, body: const Text('Settings')), }; await tester.pumpWidget(MaterialApp(routes: routes)); Navigator.pushNamed(containerKey1.currentContext!, '/settings'); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); // We are mid-transition, both pages are on stage. expect(find.text('Home'), isOnstage); expect(find.text('Settings'), isOnstage); // Drag from left edge to invoke the gesture. (near bottom so we grab // the Settings page as it comes up). TestGesture gesture = await tester.startGesture(const Offset(5.0, 550.0)); await gesture.moveBy(const Offset(500.0, 0.0)); await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 1000)); // The original forward navigation should have completed, instead of the // back gesture, since we were mid transition. expect(find.text('Home'), findsNothing); expect(find.text('Settings'), isOnstage); // Try again now that we're settled. gesture = await tester.startGesture(const Offset(5.0, 550.0)); await gesture.moveBy(const Offset(500.0, 0.0)); await gesture.up(); await tester.pump(); await tester.pump(const Duration(milliseconds: 1000)); expect(find.text('Home'), isOnstage); expect(find.text('Settings'), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); // Tests bug https://github.com/flutter/flutter/issues/6451 testWidgets('Check back gesture with a persistent bottom sheet showing', (WidgetTester tester) async { final GlobalKey containerKey1 = GlobalKey(); final GlobalKey containerKey2 = GlobalKey(); final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ '/': (_) => Scaffold(key: containerKey1, body: const Text('Home')), '/sheet': (_) => PersistentBottomSheetTest(key: containerKey2), }; await tester.pumpWidget(MaterialApp(routes: routes)); Navigator.pushNamed(containerKey1.currentContext!, '/sheet'); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(find.text('Home'), findsNothing); expect(find.text('Sheet'), isOnstage); // Drag from left edge to invoke the gesture. We should go back. TestGesture gesture = await tester.startGesture(const Offset(5.0, 100.0)); await gesture.moveBy(const Offset(500.0, 0.0)); await gesture.up(); await tester.pump(); await tester.pump(const Duration(seconds: 1)); Navigator.pushNamed(containerKey1.currentContext!, '/sheet'); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(find.text('Home'), findsNothing); expect(find.text('Sheet'), isOnstage); // Show the bottom sheet. final PersistentBottomSheetTestState sheet = containerKey2.currentState! as PersistentBottomSheetTestState; sheet.showBottomSheet(); await tester.pump(const Duration(seconds: 1)); // Drag from left edge to invoke the gesture. Nothing should happen. gesture = await tester.startGesture(const Offset(5.0, 100.0)); await gesture.moveBy(const Offset(500.0, 0.0)); await gesture.up(); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(find.text('Home'), findsNothing); expect(find.text('Sheet'), isOnstage); // Sheet did not call setState (since the gesture did nothing). expect(sheet.setStateCalled, isFalse); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('Test completed future', (WidgetTester tester) async { final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ '/': (_) => const Center(child: Text('home')), '/next': (_) => const Center(child: Text('next')), }; await tester.pumpWidget(MaterialApp(routes: routes)); final PageRoute<void> route = MaterialPageRoute<void>( settings: const RouteSettings(name: '/page'), builder: (BuildContext context) => const Center(child: Text('page')), ); int popCount = 0; route.popped.whenComplete(() { popCount += 1; }); int completeCount = 0; route.completed.whenComplete(() { completeCount += 1; }); expect(popCount, 0); expect(completeCount, 0); Navigator.push(tester.element(find.text('home')), route); expect(popCount, 0); expect(completeCount, 0); await tester.pump(); expect(popCount, 0); expect(completeCount, 0); await tester.pump(const Duration(milliseconds: 100)); expect(popCount, 0); expect(completeCount, 0); await tester.pump(const Duration(milliseconds: 100)); expect(popCount, 0); expect(completeCount, 0); await tester.pump(const Duration(seconds: 1)); expect(popCount, 0); expect(completeCount, 0); Navigator.pop(tester.element(find.text('page'))); expect(popCount, 0); expect(completeCount, 0); await tester.pump(); expect(popCount, 1); expect(completeCount, 0); await tester.pump(const Duration(milliseconds: 100)); expect(popCount, 1); expect(completeCount, 0); await tester.pump(const Duration(milliseconds: 100)); expect(popCount, 1); expect(completeCount, 0); await tester.pump(const Duration(seconds: 1)); expect(popCount, 1); expect(completeCount, 1); }); }
flutter/packages/flutter/test/widgets/page_transitions_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/page_transitions_test.dart", "repo_id": "flutter", "token_count": 4382 }
700
// 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 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; final BoxDecoration kBoxDecorationA = BoxDecoration(border: nonconst(null)); final BoxDecoration kBoxDecorationB = BoxDecoration(border: nonconst(null)); final BoxDecoration kBoxDecorationC = BoxDecoration(border: nonconst(null)); class TestWidget extends StatelessWidget { const TestWidget({ super.key, required this.child, }); final Widget child; @override Widget build(BuildContext context) => child; } class TestOrientedBox extends SingleChildRenderObjectWidget { const TestOrientedBox({ super.key, super.child }); Decoration _getDecoration(BuildContext context) { return switch (MediaQuery.orientationOf(context)) { Orientation.landscape => const BoxDecoration(color: Color(0xFF00FF00)), Orientation.portrait => const BoxDecoration(color: Color(0xFF0000FF)), }; } @override RenderDecoratedBox createRenderObject(BuildContext context) => RenderDecoratedBox(decoration: _getDecoration(context)); @override void updateRenderObject(BuildContext context, RenderDecoratedBox renderObject) { renderObject.decoration = _getDecoration(context); } } class TestNonVisitingWidget extends SingleChildRenderObjectWidget { const TestNonVisitingWidget({ super.key, required Widget super.child }); @override RenderObject createRenderObject(BuildContext context) => TestNonVisitingRenderObject(); } class TestNonVisitingRenderObject extends RenderBox with RenderObjectWithChildMixin<RenderBox> { @override Size computeDryLayout(BoxConstraints constraints) { return child!.getDryLayout(constraints); } @override void performLayout() { child!.layout(constraints, parentUsesSize: true); size = child!.size; } @override void paint(PaintingContext context, Offset offset) { context.paintChild(child!, offset); } @override void visitChildren(RenderObjectVisitor visitor) { // oops! } } void main() { testWidgets('RenderObjectWidget smoke test', (WidgetTester tester) async { await tester.pumpWidget(DecoratedBox(decoration: kBoxDecorationA)); SingleChildRenderObjectElement element = tester.element(find.byElementType(SingleChildRenderObjectElement)); expect(element, isNotNull); expect(element.renderObject, isA<RenderDecoratedBox>()); RenderDecoratedBox renderObject = element.renderObject as RenderDecoratedBox; expect(renderObject.decoration, equals(kBoxDecorationA)); expect(renderObject.position, equals(DecorationPosition.background)); await tester.pumpWidget(DecoratedBox(decoration: kBoxDecorationB)); element = tester.element(find.byElementType(SingleChildRenderObjectElement)); expect(element, isNotNull); expect(element.renderObject, isA<RenderDecoratedBox>()); renderObject = element.renderObject as RenderDecoratedBox; expect(renderObject.decoration, equals(kBoxDecorationB)); expect(renderObject.position, equals(DecorationPosition.background)); }); testWidgets('RenderObjectWidget can add and remove children', (WidgetTester tester) async { void checkFullTree() { final SingleChildRenderObjectElement element = tester.firstElement(find.byElementType(SingleChildRenderObjectElement)); expect(element, isNotNull); expect(element.renderObject, isA<RenderDecoratedBox>()); final RenderDecoratedBox renderObject = element.renderObject as RenderDecoratedBox; expect(renderObject.decoration, equals(kBoxDecorationA)); expect(renderObject.position, equals(DecorationPosition.background)); expect(renderObject.child, isNotNull); expect(renderObject.child, isA<RenderDecoratedBox>()); final RenderDecoratedBox child = renderObject.child! as RenderDecoratedBox; expect(child.decoration, equals(kBoxDecorationB)); expect(child.position, equals(DecorationPosition.background)); expect(child.child, isNull); } void childBareTree() { final SingleChildRenderObjectElement element = tester.element(find.byElementType(SingleChildRenderObjectElement)); expect(element, isNotNull); expect(element.renderObject, isA<RenderDecoratedBox>()); final RenderDecoratedBox renderObject = element.renderObject as RenderDecoratedBox; expect(renderObject.decoration, equals(kBoxDecorationA)); expect(renderObject.position, equals(DecorationPosition.background)); expect(renderObject.child, isNull); } await tester.pumpWidget(DecoratedBox( decoration: kBoxDecorationA, child: DecoratedBox( decoration: kBoxDecorationB, ), )); checkFullTree(); await tester.pumpWidget(DecoratedBox( decoration: kBoxDecorationA, child: TestWidget( child: DecoratedBox( decoration: kBoxDecorationB, ), ), )); checkFullTree(); await tester.pumpWidget(DecoratedBox( decoration: kBoxDecorationA, child: DecoratedBox( decoration: kBoxDecorationB, ), )); checkFullTree(); await tester.pumpWidget(DecoratedBox( decoration: kBoxDecorationA, )); childBareTree(); await tester.pumpWidget(DecoratedBox( decoration: kBoxDecorationA, child: TestWidget( child: TestWidget( child: DecoratedBox( decoration: kBoxDecorationB, ), ), ), )); checkFullTree(); await tester.pumpWidget(DecoratedBox( decoration: kBoxDecorationA, )); childBareTree(); }); testWidgets('Detached render tree is intact', (WidgetTester tester) async { await tester.pumpWidget(DecoratedBox( decoration: kBoxDecorationA, child: DecoratedBox( decoration: kBoxDecorationB, child: DecoratedBox( decoration: kBoxDecorationC, ), ), )); SingleChildRenderObjectElement element = tester.firstElement(find.byElementType(SingleChildRenderObjectElement)); expect(element.renderObject, isA<RenderDecoratedBox>()); final RenderDecoratedBox parent = element.renderObject as RenderDecoratedBox; expect(parent.child, isA<RenderDecoratedBox>()); final RenderDecoratedBox child = parent.child! as RenderDecoratedBox; expect(child.decoration, equals(kBoxDecorationB)); expect(child.child, isA<RenderDecoratedBox>()); final RenderDecoratedBox grandChild = child.child! as RenderDecoratedBox; expect(grandChild.decoration, equals(kBoxDecorationC)); expect(grandChild.child, isNull); await tester.pumpWidget(DecoratedBox( decoration: kBoxDecorationA, )); element = tester.element(find.byElementType(SingleChildRenderObjectElement)); expect(element.renderObject, isA<RenderDecoratedBox>()); expect(element.renderObject, equals(parent)); expect(parent.child, isNull); expect(child.parent, isNull); expect(child.decoration, equals(kBoxDecorationB)); expect(child.child, equals(grandChild)); expect(grandChild.parent, equals(child)); expect(grandChild.decoration, equals(kBoxDecorationC)); expect(grandChild.child, isNull); }); testWidgets('Can watch inherited widgets', (WidgetTester tester) async { final Key boxKey = UniqueKey(); final TestOrientedBox box = TestOrientedBox(key: boxKey); await tester.pumpWidget(MediaQuery( data: const MediaQueryData(size: Size(400.0, 300.0)), child: box, )); final RenderDecoratedBox renderBox = tester.renderObject(find.byKey(boxKey)); BoxDecoration decoration = renderBox.decoration as BoxDecoration; expect(decoration.color, equals(const Color(0xFF00FF00))); await tester.pumpWidget(MediaQuery( data: const MediaQueryData(size: Size(300.0, 400.0)), child: box, )); decoration = renderBox.decoration as BoxDecoration; expect(decoration.color, equals(const Color(0xFF0000FF))); }); testWidgets('RenderObject not visiting children provides helpful error message', (WidgetTester tester) async { await tester.pumpWidget( TestNonVisitingWidget( child: Container(color: const Color(0xFFED1D7F)), ), ); final RenderObject renderObject = tester.renderObject(find.byType(TestNonVisitingWidget)); final Canvas testCanvas = TestRecordingCanvas(); final PaintingContext testContext = TestRecordingPaintingContext(testCanvas); // When a parent fails to visit a child in visitChildren, the child's compositing // bits won't be cleared properly, leading to an exception during paint. renderObject.paint(testContext, Offset.zero); final dynamic error = tester.takeException(); expect(error, isNotNull, reason: 'RenderObject did not throw when painting'); expect(error, isFlutterError); expect(error.toString(), contains("A RenderObject was not visited by the parent's visitChildren")); }); }
flutter/packages/flutter/test/widgets/render_object_widget_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/render_object_widget_test.dart", "repo_id": "flutter", "token_count": 3116 }
701
// 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:collection'; import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; final List<String> results = <String>[]; Set<TestRoute> routes = HashSet<TestRoute>(); class TestRoute extends Route<String?> with LocalHistoryRoute<String?> { TestRoute(this.name); final String name; @override List<OverlayEntry> get overlayEntries => _entries; final List<OverlayEntry> _entries = <OverlayEntry>[]; void log(String s) { results.add('$name: $s'); } @override void install() { log('install'); final OverlayEntry entry = OverlayEntry( builder: (BuildContext context) => Container(), opaque: true, ); _entries.add(entry); routes.add(this); super.install(); } @override TickerFuture didPush() { log('didPush'); return super.didPush(); } @override void didAdd() { log('didAdd'); super.didAdd(); } @override void didReplace(Route<dynamic>? oldRoute) { expect(oldRoute, isA<TestRoute>()); final TestRoute castRoute = oldRoute! as TestRoute; log('didReplace ${castRoute.name}'); super.didReplace(castRoute); } @override bool didPop(String? result) { log('didPop $result'); bool returnValue; if (returnValue = super.didPop(result)) { navigator!.finalizeRoute(this); } return returnValue; } @override void didPopNext(Route<dynamic> nextRoute) { expect(nextRoute, isA<TestRoute>()); final TestRoute castRoute = nextRoute as TestRoute; log('didPopNext ${castRoute.name}'); super.didPopNext(castRoute); } @override void didChangeNext(Route<dynamic>? nextRoute) { expect(nextRoute, anyOf(isNull, isA<TestRoute>())); final TestRoute? castRoute = nextRoute as TestRoute?; log('didChangeNext ${castRoute?.name}'); super.didChangeNext(castRoute); } @override void dispose() { log('dispose'); for (final OverlayEntry e in _entries) { e.dispose(); } _entries.clear(); routes.remove(this); super.dispose(); } } Future<void> runNavigatorTest( WidgetTester tester, NavigatorState host, VoidCallback test, List<String> expectations, [ List<String> expectationsAfterAnotherPump = const <String>[], ]) async { expect(host, isNotNull); test(); expect(results, equals(expectations)); results.clear(); await tester.pump(); expect(results, equals(expectationsAfterAnotherPump)); results.clear(); } void main() { testWidgets('Route settings', (WidgetTester tester) async { const RouteSettings settings = RouteSettings(name: 'A'); expect(settings, hasOneLineDescription); }); testWidgets('Route settings arguments', (WidgetTester tester) async { const RouteSettings settings = RouteSettings(name: 'A'); expect(settings.arguments, isNull); final Object arguments = Object(); final RouteSettings settings2 = RouteSettings(name: 'A', arguments: arguments); expect(settings2.arguments, same(arguments)); }); testWidgets('Route management - push, replace, pop sequence', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Navigator( key: navigatorKey, onGenerateRoute: (_) => TestRoute('initial'), ), ), ); final NavigatorState host = navigatorKey.currentState!; await runNavigatorTest( tester, host, () { }, <String>[ 'initial: install', 'initial: didAdd', 'initial: didChangeNext null', ], ); late TestRoute second; await runNavigatorTest( tester, host, () { host.push(second = TestRoute('second')); }, <String>[ // stack is: initial, second 'second: install', 'second: didPush', 'second: didChangeNext null', 'initial: didChangeNext second', ], ); await runNavigatorTest( tester, host, () { host.push(TestRoute('third')); }, <String>[ // stack is: initial, second, third 'third: install', 'third: didPush', 'third: didChangeNext null', 'second: didChangeNext third', ], ); await runNavigatorTest( tester, host, () { host.replace(oldRoute: second, newRoute: TestRoute('two')); }, <String>[ // stack is: initial, two, third 'two: install', 'two: didReplace second', 'two: didChangeNext third', 'initial: didChangeNext two', 'second: dispose', ], ); await runNavigatorTest( tester, host, () { host.pop('hello'); }, <String>[ // stack is: initial, two 'third: didPop hello', 'two: didPopNext third', ], <String>[ 'third: dispose', ], ); await runNavigatorTest( tester, host, () { host.pop('good bye'); }, <String>[ // stack is: initial 'two: didPop good bye', 'initial: didPopNext two', ], <String>[ 'two: dispose', ], ); await tester.pumpWidget(Container()); expect(results, equals(<String>['initial: dispose'])); expect(routes.isEmpty, isTrue); results.clear(); }); testWidgets('Route management - push, remove, pop', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Navigator( key: navigatorKey, onGenerateRoute: (_) => TestRoute('first'), ), ), ); final NavigatorState host = navigatorKey.currentState!; await runNavigatorTest( tester, host, () { }, <String>[ 'first: install', 'first: didAdd', 'first: didChangeNext null', ], ); late TestRoute second; await runNavigatorTest( tester, host, () { host.push(second = TestRoute('second')); }, <String>[ 'second: install', 'second: didPush', 'second: didChangeNext null', 'first: didChangeNext second', ], ); await runNavigatorTest( tester, host, () { host.push(TestRoute('third')); }, <String>[ 'third: install', 'third: didPush', 'third: didChangeNext null', 'second: didChangeNext third', ], ); await runNavigatorTest( tester, host, () { host.removeRouteBelow(second); }, <String>[ 'first: dispose', ], ); await runNavigatorTest( tester, host, () { host.pop('good bye'); }, <String>[ 'third: didPop good bye', 'second: didPopNext third', ], <String>[ 'third: dispose', ], ); await runNavigatorTest( tester, host, () { host.push(TestRoute('three')); }, <String>[ 'three: install', 'three: didPush', 'three: didChangeNext null', 'second: didChangeNext three', ], ); late TestRoute four; await runNavigatorTest( tester, host, () { host.push(four = TestRoute('four')); }, <String>[ 'four: install', 'four: didPush', 'four: didChangeNext null', 'three: didChangeNext four', ], ); await runNavigatorTest( tester, host, () { host.removeRouteBelow(four); }, <String>[ 'second: didChangeNext four', 'three: dispose', ], ); await runNavigatorTest( tester, host, () { host.pop('the end'); }, <String>[ 'four: didPop the end', 'second: didPopNext four', ], <String>[ 'four: dispose', ], ); await tester.pumpWidget(Container()); expect(results, equals(<String>['second: dispose'])); expect(routes.isEmpty, isTrue); results.clear(); }); testWidgets('Route management - push, replace, popUntil', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Navigator( key: navigatorKey, onGenerateRoute: (_) => TestRoute('A'), ), ), ); final NavigatorState host = navigatorKey.currentState!; await runNavigatorTest( tester, host, () { }, <String>[ 'A: install', 'A: didAdd', 'A: didChangeNext null', ], ); await runNavigatorTest( tester, host, () { host.push(TestRoute('B')); }, <String>[ 'B: install', 'B: didPush', 'B: didChangeNext null', 'A: didChangeNext B', ], ); late TestRoute routeC; await runNavigatorTest( tester, host, () { host.push(routeC = TestRoute('C')); }, <String>[ 'C: install', 'C: didPush', 'C: didChangeNext null', 'B: didChangeNext C', ], ); expect(routeC.isActive, isTrue); late TestRoute routeB; await runNavigatorTest( tester, host, () { host.replaceRouteBelow(anchorRoute: routeC, newRoute: routeB = TestRoute('b')); }, <String>[ 'b: install', 'b: didReplace B', 'b: didChangeNext C', 'A: didChangeNext b', 'B: dispose', ], ); await runNavigatorTest( tester, host, () { host.popUntil((Route<dynamic> route) => route == routeB); }, <String>[ 'C: didPop null', 'b: didPopNext C', ], <String>[ 'C: dispose', ], ); await tester.pumpWidget(Container()); expect(results, equals(<String>['b: dispose', 'A: dispose'])); expect(routes.isEmpty, isTrue); results.clear(); }); testWidgets('Route localHistory - popUntil', (WidgetTester tester) async { final TestRoute routeA = TestRoute('A'); routeA.addLocalHistoryEntry(LocalHistoryEntry( onRemove: () { routeA.log('onRemove 0'); }, )); routeA.addLocalHistoryEntry(LocalHistoryEntry( onRemove: () { routeA.log('onRemove 1'); }, )); final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Navigator( key: navigatorKey, onGenerateRoute: (_) => routeA, ), ), ); final NavigatorState host = navigatorKey.currentState!; await runNavigatorTest( tester, host, () { host.popUntil((Route<dynamic> route) => !route.willHandlePopInternally); }, <String>[ 'A: install', 'A: didAdd', 'A: didChangeNext null', 'A: didPop null', 'A: onRemove 1', 'A: didPop null', 'A: onRemove 0', ], ); await runNavigatorTest( tester, host, () { host.popUntil((Route<dynamic> route) => !route.willHandlePopInternally); }, <String>[ ], ); await tester.pumpWidget(Container()); expect(routes.isEmpty, isTrue); results.clear(); }); group('PageRouteObserver', () { test('calls correct listeners', () { final RouteObserver<PageRoute<dynamic>> observer = RouteObserver<PageRoute<dynamic>>(); final MockRouteAware pageRouteAware1 = MockRouteAware(); final MockPageRoute route1 = MockPageRoute(); observer.subscribe(pageRouteAware1, route1); expect(pageRouteAware1.didPushCount, 1); final MockRouteAware pageRouteAware2 = MockRouteAware(); final MockPageRoute route2 = MockPageRoute(); observer.didPush(route2, route1); expect(pageRouteAware1.didPushNextCount, 1); observer.subscribe(pageRouteAware2, route2); expect(pageRouteAware2.didPushCount, 1); observer.didPop(route2, route1); expect(pageRouteAware2.didPopCount, 1); expect(pageRouteAware1.didPopNextCount, 1); }); test('does not call listeners for non-PageRoute', () { final RouteObserver<PageRoute<dynamic>> observer = RouteObserver<PageRoute<dynamic>>(); final MockRouteAware pageRouteAware = MockRouteAware(); final MockPageRoute pageRoute = MockPageRoute(); final MockRoute route = MockRoute(); observer.subscribe(pageRouteAware, pageRoute); expect(pageRouteAware.didPushCount, 1); observer.didPush(route, pageRoute); observer.didPop(route, pageRoute); expect(pageRouteAware.didPushCount, 1); expect(pageRouteAware.didPopCount, 0); }); test('does not call listeners when already subscribed', () { final RouteObserver<PageRoute<dynamic>> observer = RouteObserver<PageRoute<dynamic>>(); final MockRouteAware pageRouteAware = MockRouteAware(); final MockPageRoute pageRoute = MockPageRoute(); observer.subscribe(pageRouteAware, pageRoute); observer.subscribe(pageRouteAware, pageRoute); expect(pageRouteAware.didPushCount, 1); }); test('does not call listeners when unsubscribed', () { final RouteObserver<PageRoute<dynamic>> observer = RouteObserver<PageRoute<dynamic>>(); final MockRouteAware pageRouteAware = MockRouteAware(); final MockPageRoute pageRoute = MockPageRoute(); final MockPageRoute nextPageRoute = MockPageRoute(); observer.subscribe(pageRouteAware, pageRoute); observer.subscribe(pageRouteAware, nextPageRoute); expect(pageRouteAware.didPushCount, 2); observer.unsubscribe(pageRouteAware); observer.didPush(nextPageRoute, pageRoute); observer.didPop(nextPageRoute, pageRoute); expect(pageRouteAware.didPushCount, 2); expect(pageRouteAware.didPopCount, 0); }); test('releases reference to route when unsubscribed', () { final RouteObserver<PageRoute<dynamic>> observer = RouteObserver<PageRoute<dynamic>>(); final MockRouteAware pageRouteAware = MockRouteAware(); final MockRouteAware page2RouteAware = MockRouteAware(); final MockPageRoute pageRoute = MockPageRoute(); final MockPageRoute nextPageRoute = MockPageRoute(); observer.subscribe(pageRouteAware, pageRoute); observer.subscribe(pageRouteAware, nextPageRoute); observer.subscribe(page2RouteAware, pageRoute); observer.subscribe(page2RouteAware, nextPageRoute); expect(pageRouteAware.didPushCount, 2); expect(page2RouteAware.didPushCount, 2); expect(observer.debugObservingRoute(pageRoute), true); expect(observer.debugObservingRoute(nextPageRoute), true); observer.unsubscribe(pageRouteAware); expect(observer.debugObservingRoute(pageRoute), true); expect(observer.debugObservingRoute(nextPageRoute), true); observer.unsubscribe(page2RouteAware); expect(observer.debugObservingRoute(pageRoute), false); expect(observer.debugObservingRoute(nextPageRoute), false); }); }); testWidgets('Can autofocus a TextField nested in a Focus in a route.', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); final FocusNode focusNode = FocusNode(debugLabel: 'Test Node'); addTearDown(focusNode.dispose); await tester.pumpWidget( Material( child: MaterialApp( onGenerateRoute: (RouteSettings settings) { return PageRouteBuilder<void>( settings: settings, pageBuilder: (BuildContext context, Animation<double> input, Animation<double> out) { return Focus( child: TextField( autofocus: true, focusNode: focusNode, controller: controller, ), ); }, ); }, ), ), ); await tester.pump(); expect(focusNode.hasPrimaryFocus, isTrue); }); group('PageRouteBuilder', () { testWidgets('reverseTransitionDuration defaults to 300ms', (WidgetTester tester) async { // Default PageRouteBuilder reverse transition duration should be 300ms. await tester.pumpWidget( MaterialApp( onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<dynamic>( builder: (BuildContext context) { return ElevatedButton( onPressed: () { Navigator.of(context).push<void>( PageRouteBuilder<void>( settings: settings, pageBuilder: (BuildContext context, Animation<double> input, Animation<double> out) { return const Text('Page Two'); }, ), ); }, child: const Text('Open page'), ); }, ); }, ), ); // Open the new route. await tester.tap(find.byType(ElevatedButton)); await tester.pumpAndSettle(); expect(find.text('Open page'), findsNothing); expect(find.text('Page Two'), findsOneWidget); // Pop the new route. tester.state<NavigatorState>(find.byType(Navigator)).pop(); await tester.pump(); expect(find.text('Page Two'), findsOneWidget); // Text('Page Two') should be present halfway through the reverse transition. await tester.pump(const Duration(milliseconds: 150)); expect(find.text('Page Two'), findsOneWidget); // Text('Page Two') should be present at the very end of the reverse transition. await tester.pump(const Duration(milliseconds: 150)); expect(find.text('Page Two'), findsOneWidget); // Text('Page Two') have transitioned out after 300ms. await tester.pump(const Duration(milliseconds: 1)); expect(find.text('Page Two'), findsNothing); expect(find.text('Open page'), findsOneWidget); }); testWidgets('reverseTransitionDuration can be customized', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<dynamic>( builder: (BuildContext context) { return ElevatedButton( onPressed: () { Navigator.of(context).push<void>( PageRouteBuilder<void>( settings: settings, pageBuilder: (BuildContext context, Animation<double> input, Animation<double> out) { return const Text('Page Two'); }, // modified value, default PageRouteBuilder reverse transition duration should be 300ms. reverseTransitionDuration: const Duration(milliseconds: 150), ), ); }, child: const Text('Open page'), ); }, ); }, )); // Open the new route. await tester.tap(find.byType(ElevatedButton)); await tester.pumpAndSettle(); expect(find.text('Open page'), findsNothing); expect(find.text('Page Two'), findsOneWidget); // Pop the new route. tester.state<NavigatorState>(find.byType(Navigator)).pop(); await tester.pump(); expect(find.text('Page Two'), findsOneWidget); // Text('Page Two') should be present halfway through the reverse transition. await tester.pump(const Duration(milliseconds: 75)); expect(find.text('Page Two'), findsOneWidget); // Text('Page Two') should be present at the very end of the reverse transition. await tester.pump(const Duration(milliseconds: 75)); expect(find.text('Page Two'), findsOneWidget); // Text('Page Two') have transitioned out after 500ms. await tester.pump(const Duration(milliseconds: 1)); expect(find.text('Page Two'), findsNothing); expect(find.text('Open page'), findsOneWidget); }); }); group('TransitionRoute', () { testWidgets('secondary animation is kDismissed when next route finishes pop', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); await tester.pumpWidget( MaterialApp( navigatorKey: navigator, home: const Text('home'), ), ); // Push page one, its secondary animation is kAlwaysDismissedAnimation. late ProxyAnimation secondaryAnimationProxyPageOne; late ProxyAnimation animationPageOne; navigator.currentState!.push( PageRouteBuilder<void>( pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { secondaryAnimationProxyPageOne = secondaryAnimation as ProxyAnimation; animationPageOne = animation as ProxyAnimation; return const Text('Page One'); }, ), ); await tester.pump(); await tester.pumpAndSettle(); final ProxyAnimation secondaryAnimationPageOne = secondaryAnimationProxyPageOne.parent! as ProxyAnimation; expect(animationPageOne.value, 1.0); expect(secondaryAnimationPageOne.parent, kAlwaysDismissedAnimation); // Push page two, the secondary animation of page one is the primary // animation of page two. late ProxyAnimation secondaryAnimationProxyPageTwo; late ProxyAnimation animationPageTwo; navigator.currentState!.push( PageRouteBuilder<void>( pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { secondaryAnimationProxyPageTwo = secondaryAnimation as ProxyAnimation; animationPageTwo = animation as ProxyAnimation; return const Text('Page Two'); }, ), ); await tester.pump(); await tester.pumpAndSettle(); final ProxyAnimation secondaryAnimationPageTwo = secondaryAnimationProxyPageTwo.parent! as ProxyAnimation; expect(animationPageTwo.value, 1.0); expect(secondaryAnimationPageTwo.parent, kAlwaysDismissedAnimation); expect(secondaryAnimationPageOne.parent, animationPageTwo.parent); // Pop page two, the secondary animation of page one becomes // kAlwaysDismissedAnimation. navigator.currentState!.pop(); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); expect(secondaryAnimationPageOne.parent, animationPageTwo.parent); await tester.pumpAndSettle(); expect(animationPageTwo.value, 0.0); expect(secondaryAnimationPageOne.parent, kAlwaysDismissedAnimation); }); testWidgets('secondary animation is kDismissed when next route is removed', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); await tester.pumpWidget( MaterialApp( navigatorKey: navigator, home: const Text('home'), ), ); // Push page one, its secondary animation is kAlwaysDismissedAnimation. late ProxyAnimation secondaryAnimationProxyPageOne; late ProxyAnimation animationPageOne; navigator.currentState!.push( PageRouteBuilder<void>( pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { secondaryAnimationProxyPageOne = secondaryAnimation as ProxyAnimation; animationPageOne = animation as ProxyAnimation; return const Text('Page One'); }, ), ); await tester.pump(); await tester.pumpAndSettle(); final ProxyAnimation secondaryAnimationPageOne = secondaryAnimationProxyPageOne.parent! as ProxyAnimation; expect(animationPageOne.value, 1.0); expect(secondaryAnimationPageOne.parent, kAlwaysDismissedAnimation); // Push page two, the secondary animation of page one is the primary // animation of page two. late ProxyAnimation secondaryAnimationProxyPageTwo; late ProxyAnimation animationPageTwo; Route<void> secondRoute; navigator.currentState!.push( secondRoute = PageRouteBuilder<void>( pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { secondaryAnimationProxyPageTwo = secondaryAnimation as ProxyAnimation; animationPageTwo = animation as ProxyAnimation; return const Text('Page Two'); }, ), ); await tester.pump(); await tester.pumpAndSettle(); final ProxyAnimation secondaryAnimationPageTwo = secondaryAnimationProxyPageTwo.parent! as ProxyAnimation; expect(animationPageTwo.value, 1.0); expect(secondaryAnimationPageTwo.parent, kAlwaysDismissedAnimation); expect(secondaryAnimationPageOne.parent, animationPageTwo.parent); // Remove the second route, the secondary animation of page one is // kAlwaysDismissedAnimation again. navigator.currentState!.removeRoute(secondRoute); await tester.pump(); expect(secondaryAnimationPageOne.parent, kAlwaysDismissedAnimation); }); testWidgets('secondary animation is kDismissed after train hopping finishes and pop', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); await tester.pumpWidget( MaterialApp( navigatorKey: navigator, home: const Text('home'), ), ); // Push page one, its secondary animation is kAlwaysDismissedAnimation. late ProxyAnimation secondaryAnimationProxyPageOne; late ProxyAnimation animationPageOne; navigator.currentState!.push( PageRouteBuilder<void>( pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { secondaryAnimationProxyPageOne = secondaryAnimation as ProxyAnimation; animationPageOne = animation as ProxyAnimation; return const Text('Page One'); }, ), ); await tester.pump(); await tester.pumpAndSettle(); final ProxyAnimation secondaryAnimationPageOne = secondaryAnimationProxyPageOne.parent! as ProxyAnimation; expect(animationPageOne.value, 1.0); expect(secondaryAnimationPageOne.parent, kAlwaysDismissedAnimation); // Push page two, the secondary animation of page one is the primary // animation of page two. late ProxyAnimation animationPageTwo; navigator.currentState!.push( PageRouteBuilder<void>( pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { animationPageTwo = animation as ProxyAnimation; return const Text('Page Two'); }, ), ); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); expect(secondaryAnimationPageOne.parent, animationPageTwo.parent); // Replace with a different route while push is ongoing to trigger // TrainHopping. late ProxyAnimation animationPageThree; navigator.currentState!.pushReplacement( TestPageRouteBuilder( pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { animationPageThree = animation as ProxyAnimation; return const Text('Page Three'); }, ), ); await tester.pump(); await tester.pump(const Duration(milliseconds: 1)); expect(secondaryAnimationPageOne.parent, isA<TrainHoppingAnimation>()); final TrainHoppingAnimation trainHopper = secondaryAnimationPageOne.parent! as TrainHoppingAnimation; expect(trainHopper.currentTrain, animationPageTwo.parent); await tester.pump(const Duration(milliseconds: 100)); expect(secondaryAnimationPageOne.parent, isNot(isA<TrainHoppingAnimation>())); expect(secondaryAnimationPageOne.parent, animationPageThree.parent); expect(trainHopper.currentTrain, isNull); // Has been disposed. await tester.pumpAndSettle(); expect(secondaryAnimationPageOne.parent, animationPageThree.parent); // Pop page three. navigator.currentState!.pop(); await tester.pump(); await tester.pumpAndSettle(); expect(secondaryAnimationPageOne.parent, kAlwaysDismissedAnimation); }); testWidgets('secondary animation is kDismissed when train hopping is interrupted', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); await tester.pumpWidget( MaterialApp( navigatorKey: navigator, home: const Text('home'), ), ); // Push page one, its secondary animation is kAlwaysDismissedAnimation. late ProxyAnimation secondaryAnimationProxyPageOne; late ProxyAnimation animationPageOne; navigator.currentState!.push( PageRouteBuilder<void>( pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { secondaryAnimationProxyPageOne = secondaryAnimation as ProxyAnimation; animationPageOne = animation as ProxyAnimation; return const Text('Page One'); }, ), ); await tester.pump(); await tester.pumpAndSettle(); final ProxyAnimation secondaryAnimationPageOne = secondaryAnimationProxyPageOne.parent! as ProxyAnimation; expect(animationPageOne.value, 1.0); expect(secondaryAnimationPageOne.parent, kAlwaysDismissedAnimation); // Push page two, the secondary animation of page one is the primary // animation of page two. late ProxyAnimation animationPageTwo; navigator.currentState!.push( PageRouteBuilder<void>( pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { animationPageTwo = animation as ProxyAnimation; return const Text('Page Two'); }, ), ); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); expect(secondaryAnimationPageOne.parent, animationPageTwo.parent); // Replace with a different route while push is ongoing to trigger // TrainHopping. navigator.currentState!.pushReplacement( TestPageRouteBuilder( pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { return const Text('Page Three'); }, ), ); await tester.pump(); await tester.pump(const Duration(milliseconds: 10)); expect(secondaryAnimationPageOne.parent, isA<TrainHoppingAnimation>()); final TrainHoppingAnimation trainHopper = secondaryAnimationPageOne.parent! as TrainHoppingAnimation; expect(trainHopper.currentTrain, animationPageTwo.parent); // Pop page three while replacement push is ongoing. navigator.currentState!.pop(); await tester.pump(); expect(secondaryAnimationPageOne.parent, isA<TrainHoppingAnimation>()); final TrainHoppingAnimation trainHopper2 = secondaryAnimationPageOne.parent! as TrainHoppingAnimation; expect(trainHopper2.currentTrain, animationPageTwo.parent); expect(trainHopper.currentTrain, isNull); // Has been disposed. await tester.pumpAndSettle(); expect(secondaryAnimationPageOne.parent, kAlwaysDismissedAnimation); expect(trainHopper2.currentTrain, isNull); // Has been disposed. }); testWidgets('secondary animation is triggered when pop initial route', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); late Animation<double> secondaryAnimationOfRouteOne; late Animation<double> primaryAnimationOfRouteTwo; await tester.pumpWidget( MaterialApp( navigatorKey: navigator, onGenerateRoute: (RouteSettings settings) { return PageRouteBuilder<void>( settings: settings, pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { if (settings.name == '/') { secondaryAnimationOfRouteOne = secondaryAnimation; } else { primaryAnimationOfRouteTwo = animation; } return const Text('Page'); }, ); }, initialRoute: '/a', ), ); // The secondary animation of the bottom route should be chained with the // primary animation of top most route. expect(secondaryAnimationOfRouteOne.value, 1.0); expect(secondaryAnimationOfRouteOne.value, primaryAnimationOfRouteTwo.value); // Pops the top most route and verifies two routes are still chained. navigator.currentState!.pop(); await tester.pump(); await tester.pump(const Duration(milliseconds: 30)); expect(secondaryAnimationOfRouteOne.value, 0.9); expect(secondaryAnimationOfRouteOne.value, primaryAnimationOfRouteTwo.value); await tester.pumpAndSettle(); expect(secondaryAnimationOfRouteOne.value, 0.0); expect(secondaryAnimationOfRouteOne.value, primaryAnimationOfRouteTwo.value); }); testWidgets('showGeneralDialog handles transparent barrier color', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Builder( builder: (BuildContext context) { return ElevatedButton( onPressed: () { showGeneralDialog<void>( context: context, barrierDismissible: true, barrierLabel: 'barrier_label', barrierColor: const Color(0x00000000), transitionDuration: Duration.zero, pageBuilder: (BuildContext innerContext, _, __) { return const SizedBox(); }, ); }, child: const Text('Show Dialog'), ); }, ), )); // Open the dialog. await tester.tap(find.byType(ElevatedButton)); await tester.pump(); expect(find.byType(ModalBarrier), findsNWidgets(2)); // Close the dialog. await tester.tapAt(Offset.zero); await tester.pump(); expect(find.byType(ModalBarrier), findsNWidgets(1)); }); testWidgets('showGeneralDialog adds non-dismissible barrier when barrierDismissible is false', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Builder( builder: (BuildContext context) { return ElevatedButton( onPressed: () { showGeneralDialog<void>( context: context, transitionDuration: Duration.zero, pageBuilder: (BuildContext innerContext, _, __) { return const SizedBox(); }, ); }, child: const Text('Show Dialog'), ); }, ), )); // Open the dialog. await tester.tap(find.byType(ElevatedButton)); await tester.pump(); expect(find.byType(ModalBarrier), findsNWidgets(2)); final ModalBarrier barrier = find.byType(ModalBarrier).evaluate().last.widget as ModalBarrier; expect(barrier.dismissible, isFalse); // Close the dialog. final StatefulElement navigatorElement = find.byType(Navigator).evaluate().last as StatefulElement; final NavigatorState navigatorState = navigatorElement.state as NavigatorState; navigatorState.pop(); await tester.pumpAndSettle(); expect(find.byType(ModalBarrier), findsNWidgets(1)); }); testWidgets('showGeneralDialog uses null as a barrierLabel by default', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Builder( builder: (BuildContext context) { return ElevatedButton( onPressed: () { showGeneralDialog<void>( context: context, transitionDuration: Duration.zero, pageBuilder: (BuildContext innerContext, _, __) { return const SizedBox(); }, ); }, child: const Text('Show Dialog'), ); }, ), )); // Open the dialog. await tester.tap(find.byType(ElevatedButton)); await tester.pump(); expect(find.byType(ModalBarrier), findsNWidgets(2)); final ModalBarrier barrier = find.byType(ModalBarrier).evaluate().last.widget as ModalBarrier; expect(barrier.semanticsLabel, same(null)); // Close the dialog. final StatefulElement navigatorElement = find.byType(Navigator).evaluate().last as StatefulElement; final NavigatorState navigatorState = navigatorElement.state as NavigatorState; navigatorState.pop(); await tester.pumpAndSettle(); expect(find.byType(ModalBarrier), findsNWidgets(1)); }); testWidgets('showGeneralDialog uses root navigator by default', (WidgetTester tester) async { final DialogObserver rootObserver = DialogObserver(); final DialogObserver nestedObserver = DialogObserver(); await tester.pumpWidget(MaterialApp( navigatorObservers: <NavigatorObserver>[rootObserver], home: Navigator( observers: <NavigatorObserver>[nestedObserver], onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<dynamic>( builder: (BuildContext context) { return ElevatedButton( onPressed: () { showGeneralDialog<void>( context: context, transitionDuration: Duration.zero, pageBuilder: (BuildContext innerContext, _, __) { return const SizedBox(); }, ); }, child: const Text('Show Dialog'), ); }, ); }, ), )); // Open the dialog. await tester.tap(find.byType(ElevatedButton)); expect(rootObserver.dialogCount, 1); expect(nestedObserver.dialogCount, 0); }); testWidgets('showGeneralDialog uses nested navigator if useRootNavigator is false', (WidgetTester tester) async { final DialogObserver rootObserver = DialogObserver(); final DialogObserver nestedObserver = DialogObserver(); await tester.pumpWidget(MaterialApp( navigatorObservers: <NavigatorObserver>[rootObserver], home: Navigator( observers: <NavigatorObserver>[nestedObserver], onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<dynamic>( builder: (BuildContext context) { return ElevatedButton( onPressed: () { showGeneralDialog<void>( useRootNavigator: false, context: context, transitionDuration: Duration.zero, pageBuilder: (BuildContext innerContext, _, __) { return const SizedBox(); }, ); }, child: const Text('Show Dialog'), ); }, ); }, ), )); // Open the dialog. await tester.tap(find.byType(ElevatedButton)); expect(rootObserver.dialogCount, 0); expect(nestedObserver.dialogCount, 1); }); testWidgets('showGeneralDialog default argument values', (WidgetTester tester) async { final DialogObserver rootObserver = DialogObserver(); await tester.pumpWidget(MaterialApp( navigatorObservers: <NavigatorObserver>[rootObserver], home: Navigator( onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<dynamic>( builder: (BuildContext context) { return ElevatedButton( onPressed: () { showGeneralDialog<void>( context: context, pageBuilder: (BuildContext innerContext, _, __) { return const SizedBox(); }, ); }, child: const Text('Show Dialog'), ); }, ); }, ), )); // Open the dialog. await tester.tap(find.byType(ElevatedButton)); expect(rootObserver.dialogRoutes.length, equals(1)); final ModalRoute<dynamic> route = rootObserver.dialogRoutes.last; expect(route.barrierDismissible, isNotNull); expect(route.barrierColor, isNotNull); expect(route.transitionDuration, isNotNull); }); group('showGeneralDialog avoids overlapping display features', () { testWidgets('positioning with anchorPoint', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( builder: (BuildContext context, Widget? child) { return MediaQuery( // Display has a vertical hinge down the middle data: const MediaQueryData( size: Size(800, 600), displayFeatures: <DisplayFeature>[ DisplayFeature( bounds: Rect.fromLTRB(390, 0, 410, 600), type: DisplayFeatureType.hinge, state: DisplayFeatureState.unknown, ), ], ), child: child!, ); }, home: const Center(child: Text('Test')), ), ); final BuildContext context = tester.element(find.text('Test')); showGeneralDialog<void>( context: context, pageBuilder: (BuildContext context, _, __) { return const Placeholder(); }, anchorPoint: const Offset(1000, 0), ); await tester.pumpAndSettle(); // Should take the right side of the screen expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(410.0, 0.0)); expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(800.0, 600.0)); }); testWidgets('positioning with Directionality', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( builder: (BuildContext context, Widget? child) { return MediaQuery( // Display has a vertical hinge down the middle data: const MediaQueryData( size: Size(800, 600), displayFeatures: <DisplayFeature>[ DisplayFeature( bounds: Rect.fromLTRB(390, 0, 410, 600), type: DisplayFeatureType.hinge, state: DisplayFeatureState.unknown, ), ], ), child: Directionality( textDirection: TextDirection.rtl, child: child!, ), ); }, home: const Center(child: Text('Test')), ), ); final BuildContext context = tester.element(find.text('Test')); showGeneralDialog<void>( context: context, pageBuilder: (BuildContext context, _, __) { return const Placeholder(); }, ); await tester.pumpAndSettle(); // Since this is RTL, it should place the dialog on the right screen expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(410.0, 0.0)); expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(800.0, 600.0)); }); testWidgets('positioning by default', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( builder: (BuildContext context, Widget? child) { return MediaQuery( // Display has a vertical hinge down the middle data: const MediaQueryData( size: Size(800, 600), displayFeatures: <DisplayFeature>[ DisplayFeature( bounds: Rect.fromLTRB(390, 0, 410, 600), type: DisplayFeatureType.hinge, state: DisplayFeatureState.unknown, ), ], ), child: child!, ); }, home: const Center(child: Text('Test')), ), ); final BuildContext context = tester.element(find.text('Test')); showGeneralDialog<void>( context: context, pageBuilder: (BuildContext context, _, __) { return const Placeholder(); }, ); await tester.pumpAndSettle(); // By default it should place the dialog on the left screen expect(tester.getTopLeft(find.byType(Placeholder)), Offset.zero); expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(390.0, 600.0)); }); }); testWidgets('reverseTransitionDuration defaults to transitionDuration', (WidgetTester tester) async { final GlobalKey containerKey = GlobalKey(); // Default MaterialPageRoute transition duration should be 300ms. await tester.pumpWidget(MaterialApp( onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<dynamic>( builder: (BuildContext context) { return ElevatedButton( onPressed: () { Navigator.of(context).push<void>( MaterialPageRoute<void>( builder: (BuildContext innerContext) { return Container( key: containerKey, color: Colors.green, ); }, ), ); }, child: const Text('Open page'), ); }, ); }, )); // Open the new route. await tester.tap(find.byType(ElevatedButton)); await tester.pumpAndSettle(); expect(find.text('Open page'), findsNothing); expect(find.byKey(containerKey), findsOneWidget); // Pop the new route. tester.state<NavigatorState>(find.byType(Navigator)).pop(); await tester.pump(); expect(find.byKey(containerKey), findsOneWidget); // Container should be present halfway through the transition. await tester.pump(const Duration(milliseconds: 150)); expect(find.byKey(containerKey), findsOneWidget); // Container should be present at the very end of the transition. await tester.pump(const Duration(milliseconds: 150)); expect(find.byKey(containerKey), findsOneWidget); // Container have transitioned out after 300ms. await tester.pump(const Duration(milliseconds: 1)); expect(find.byKey(containerKey), findsNothing); }); testWidgets('reverseTransitionDuration can be customized', (WidgetTester tester) async { final GlobalKey containerKey = GlobalKey(); await tester.pumpWidget(MaterialApp( onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<dynamic>( builder: (BuildContext context) { return ElevatedButton( onPressed: () { Navigator.of(context).push<void>( ModifiedReverseTransitionDurationRoute<void>( builder: (BuildContext innerContext) { return Container( key: containerKey, color: Colors.green, ); }, // modified value, default MaterialPageRoute transition duration should be 300ms. reverseTransitionDuration: const Duration(milliseconds: 150), ), ); }, child: const Text('Open page'), ); }, ); }, )); // Open the new route. await tester.tap(find.byType(ElevatedButton)); await tester.pumpAndSettle(); expect(find.text('Open page'), findsNothing); expect(find.byKey(containerKey), findsOneWidget); // Pop the new route. tester.state<NavigatorState>(find.byType(Navigator)).pop(); await tester.pump(); expect(find.byKey(containerKey), findsOneWidget); // Container should be present halfway through the transition. await tester.pump(const Duration(milliseconds: 75)); expect(find.byKey(containerKey), findsOneWidget); // Container should be present at the very end of the transition. await tester.pump(const Duration(milliseconds: 75)); expect(find.byKey(containerKey), findsOneWidget); // Container have transitioned out after 150ms. await tester.pump(const Duration(milliseconds: 1)); expect(find.byKey(containerKey), findsNothing); }); testWidgets('custom reverseTransitionDuration does not result in interrupted animations', (WidgetTester tester) async { final GlobalKey containerKey = GlobalKey(); await tester.pumpWidget(MaterialApp( theme: ThemeData( pageTransitionsTheme: const PageTransitionsTheme( builders: <TargetPlatform, PageTransitionsBuilder>{ TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(), // use a fade transition }, ), ), onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<dynamic>( builder: (BuildContext context) { return ElevatedButton( onPressed: () { Navigator.of(context).push<void>( ModifiedReverseTransitionDurationRoute<void>( builder: (BuildContext innerContext) { return Container( key: containerKey, color: Colors.green, ); }, // modified value, default MaterialPageRoute transition duration should be 300ms. reverseTransitionDuration: const Duration(milliseconds: 150), ), ); }, child: const Text('Open page'), ); }, ); }, )); // Open the new route. await tester.tap(find.byType(ElevatedButton)); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); // jump partway through the forward transition expect(find.byKey(containerKey), findsOneWidget); // Gets the opacity of the fade transition while animating forwards. final double topFadeTransitionOpacity = _getOpacity(containerKey, tester); // Pop the new route mid-transition. tester.state<NavigatorState>(find.byType(Navigator)).pop(); await tester.pump(); // Transition should not jump. In other words, the fade transition // opacity before and after animation changes directions should remain // the same. expect(_getOpacity(containerKey, tester), topFadeTransitionOpacity); // Reverse transition duration should be: // Forward transition elapsed time: 200ms / 300ms = 2 / 3 // Reverse transition remaining time: 150ms * 2 / 3 = 100ms // Container should be present at the very end of the transition. await tester.pump(const Duration(milliseconds: 100)); expect(find.byKey(containerKey), findsOneWidget); // Container have transitioned out after 100ms. await tester.pump(const Duration(milliseconds: 1)); expect(find.byKey(containerKey), findsNothing); }); }); group('ModalRoute', () { testWidgets('default barrierCurve', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Material( child: Builder( builder: (BuildContext context) { return Center( child: ElevatedButton( child: const Text('X'), onPressed: () { Navigator.of(context).push<void>( _TestDialogRouteWithCustomBarrierCurve<void>( child: const Text('Hello World'), ), ); }, ), ); }, ), ), )); final CurveTween defaultBarrierTween = CurveTween(curve: Curves.ease); int getExpectedBarrierTweenAlphaValue(double t) { return Color.getAlphaFromOpacity(defaultBarrierTween.transform(t)); } await tester.tap(find.text('X')); await tester.pump(); final Finder animatedModalBarrier = find.byType(AnimatedModalBarrier); expect(animatedModalBarrier, findsOneWidget); Animation<Color?> modalBarrierAnimation; modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; expect(modalBarrierAnimation.value, Colors.transparent); await tester.pump(const Duration(milliseconds: 25)); modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; expect( modalBarrierAnimation.value!.alpha, closeTo(getExpectedBarrierTweenAlphaValue(0.25), 1), ); await tester.pump(const Duration(milliseconds: 25)); modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; expect( modalBarrierAnimation.value!.alpha, closeTo(getExpectedBarrierTweenAlphaValue(0.50), 1), ); await tester.pump(const Duration(milliseconds: 25)); modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; expect( modalBarrierAnimation.value!.alpha, closeTo(getExpectedBarrierTweenAlphaValue(0.75), 1), ); await tester.pumpAndSettle(); modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; expect(modalBarrierAnimation.value, Colors.black); }); testWidgets('custom barrierCurve', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Material( child: Builder( builder: (BuildContext context) { return Center( child: ElevatedButton( child: const Text('X'), onPressed: () { Navigator.of(context).push<void>( _TestDialogRouteWithCustomBarrierCurve<void>( child: const Text('Hello World'), barrierCurve: Curves.linear, ), ); }, ), ); }, ), ), )); final CurveTween customBarrierTween = CurveTween(curve: Curves.linear); int getExpectedBarrierTweenAlphaValue(double t) { return Color.getAlphaFromOpacity(customBarrierTween.transform(t)); } await tester.tap(find.text('X')); await tester.pump(); final Finder animatedModalBarrier = find.byType(AnimatedModalBarrier); expect(animatedModalBarrier, findsOneWidget); Animation<Color?> modalBarrierAnimation; modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; expect(modalBarrierAnimation.value, Colors.transparent); await tester.pump(const Duration(milliseconds: 25)); modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; expect( modalBarrierAnimation.value!.alpha, closeTo(getExpectedBarrierTweenAlphaValue(0.25), 1), ); await tester.pump(const Duration(milliseconds: 25)); modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; expect( modalBarrierAnimation.value!.alpha, closeTo(getExpectedBarrierTweenAlphaValue(0.50), 1), ); await tester.pump(const Duration(milliseconds: 25)); modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; expect( modalBarrierAnimation.value!.alpha, closeTo(getExpectedBarrierTweenAlphaValue(0.75), 1), ); await tester.pumpAndSettle(); modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; expect(modalBarrierAnimation.value, Colors.black); }); testWidgets('white barrierColor', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Material( child: Builder( builder: (BuildContext context) { return Center( child: ElevatedButton( child: const Text('X'), onPressed: () { Navigator.of(context).push<void>( _TestDialogRouteWithCustomBarrierCurve<void>( child: const Text('Hello World'), barrierColor: Colors.white, ), ); }, ), ); }, ), ), )); final CurveTween defaultBarrierTween = CurveTween(curve: Curves.ease); int getExpectedBarrierTweenAlphaValue(double t) { return Color.getAlphaFromOpacity(defaultBarrierTween.transform(t)); } await tester.tap(find.text('X')); await tester.pump(); final Finder animatedModalBarrier = find.byType(AnimatedModalBarrier); expect(animatedModalBarrier, findsOneWidget); Animation<Color?> modalBarrierAnimation; modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; expect(modalBarrierAnimation.value, Colors.white.withOpacity(0)); await tester.pump(const Duration(milliseconds: 25)); modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; expect( modalBarrierAnimation.value!.alpha, closeTo(getExpectedBarrierTweenAlphaValue(0.25), 1), ); await tester.pump(const Duration(milliseconds: 25)); modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; expect( modalBarrierAnimation.value!.alpha, closeTo(getExpectedBarrierTweenAlphaValue(0.50), 1), ); await tester.pump(const Duration(milliseconds: 25)); modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; expect( modalBarrierAnimation.value!.alpha, closeTo(getExpectedBarrierTweenAlphaValue(0.75), 1), ); await tester.pumpAndSettle(); modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; expect(modalBarrierAnimation.value, Colors.white); }); testWidgets('modal route semantics order', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/46625. final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget(MaterialApp( home: Material( child: Builder( builder: (BuildContext context) { return Center( child: ElevatedButton( child: const Text('X'), onPressed: () { Navigator.of(context).push<void>( _TestDialogRouteWithCustomBarrierCurve<void>( child: const Text('Hello World'), barrierLabel: 'test label', barrierCurve: Curves.linear, ), ); }, ), ); }, ), ), )); await tester.tap(find.text('X')); await tester.pumpAndSettle(); expect(find.text('Hello World'), findsOneWidget); final TestSemantics expectedSemantics = TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, rect: TestSemantics.fullScreen, children: <TestSemantics>[ TestSemantics( id: 6, rect: TestSemantics.fullScreen, children: <TestSemantics>[ TestSemantics( id: 7, rect: TestSemantics.fullScreen, flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( id: 8, label: 'Hello World', rect: TestSemantics.fullScreen, textDirection: TextDirection.ltr, ), ], ), ], ), // Modal barrier is put after modal scope TestSemantics( id: 5, rect: TestSemantics.fullScreen, actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss], label: 'test label', textDirection: TextDirection.ltr, ), ], ), ], ) ; expect(semantics, hasSemantics(expectedSemantics)); semantics.dispose(); }, variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS})); testWidgets('focus traverse correct when pop multiple page simultaneously', (WidgetTester tester) async { // Regression test: https://github.com/flutter/flutter/issues/48903 final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); await tester.pumpWidget(MaterialApp( navigatorKey: navigatorKey, home: const Text('dummy1'), )); final Element textOnPageOne = tester.element(find.text('dummy1')); final FocusScopeNode focusNodeOnPageOne = FocusScope.of(textOnPageOne); expect(focusNodeOnPageOne.hasFocus, isTrue); // Pushes one page. navigatorKey.currentState!.push<void>( MaterialPageRoute<void>( builder: (BuildContext context) => const Text('dummy2'), ), ); await tester.pumpAndSettle(); final Element textOnPageTwo = tester.element(find.text('dummy2')); final FocusScopeNode focusNodeOnPageTwo = FocusScope.of(textOnPageTwo); // The focus should be on second page. expect(focusNodeOnPageOne.hasFocus, isFalse); expect(focusNodeOnPageTwo.hasFocus, isTrue); // Pushes another page. navigatorKey.currentState!.push<void>( MaterialPageRoute<void>( builder: (BuildContext context) => const Text('dummy3'), ), ); await tester.pumpAndSettle(); final Element textOnPageThree = tester.element(find.text('dummy3')); final FocusScopeNode focusNodeOnPageThree = FocusScope.of(textOnPageThree); // The focus should be on third page. expect(focusNodeOnPageOne.hasFocus, isFalse); expect(focusNodeOnPageTwo.hasFocus, isFalse); expect(focusNodeOnPageThree.hasFocus, isTrue); // Pops two pages simultaneously. navigatorKey.currentState!.popUntil((Route<void> route) => route.isFirst); await tester.pumpAndSettle(); // It should refocus page one after pops. expect(focusNodeOnPageOne.hasFocus, isTrue); }); testWidgets('focus traversal is correct when popping multiple pages simultaneously - with focused children', (WidgetTester tester) async { // Regression test: https://github.com/flutter/flutter/issues/48903 final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); await tester.pumpWidget(MaterialApp( navigatorKey: navigatorKey, home: const Text('dummy1'), )); final Element textOnPageOne = tester.element(find.text('dummy1')); final FocusScopeNode focusNodeOnPageOne = FocusScope.of(textOnPageOne); expect(focusNodeOnPageOne.hasFocus, isTrue); // Pushes one page. navigatorKey.currentState!.push<void>( MaterialPageRoute<void>( builder: (BuildContext context) => const Material(child: TextField()), ), ); await tester.pumpAndSettle(); final Element textOnPageTwo = tester.element(find.byType(TextField)); final FocusScopeNode focusNodeOnPageTwo = FocusScope.of(textOnPageTwo); // The focus should be on second page. expect(focusNodeOnPageOne.hasFocus, isFalse); expect(focusNodeOnPageTwo.hasFocus, isTrue); // Move the focus to another node. focusNodeOnPageTwo.nextFocus(); await tester.pumpAndSettle(); expect(focusNodeOnPageTwo.hasFocus, isTrue); expect(focusNodeOnPageTwo.hasPrimaryFocus, isFalse); // Pushes another page. navigatorKey.currentState!.push<void>( MaterialPageRoute<void>( builder: (BuildContext context) => const Text('dummy3'), ), ); await tester.pumpAndSettle(); final Element textOnPageThree = tester.element(find.text('dummy3')); final FocusScopeNode focusNodeOnPageThree = FocusScope.of(textOnPageThree); // The focus should be on third page. expect(focusNodeOnPageOne.hasFocus, isFalse); expect(focusNodeOnPageTwo.hasFocus, isFalse); expect(focusNodeOnPageThree.hasFocus, isTrue); // Pops two pages simultaneously. navigatorKey.currentState!.popUntil((Route<void> route) => route.isFirst); await tester.pumpAndSettle(); // It should refocus page one after pops. expect(focusNodeOnPageOne.hasFocus, isTrue); }); testWidgets('child with local history can be disposed', (WidgetTester tester) async { // Regression test: https://github.com/flutter/flutter/issues/52478 await tester.pumpWidget(const MaterialApp( home: WidgetWithLocalHistory(), )); final WidgetWithLocalHistoryState state = tester.state(find.byType(WidgetWithLocalHistory)); state.addLocalHistory(); // Waits for modal route to update its internal state; await tester.pump(); // Pumps a new widget to dispose WidgetWithLocalHistory. This should cause // it to remove the local history entry from modal route during // finalizeTree. await tester.pumpWidget(const MaterialApp( home: Text('dummy'), )); // Waits for modal route to update its internal state; await tester.pump(); expect(tester.takeException(), null); }); testWidgets('child with no local history can be disposed', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: WidgetWithNoLocalHistory(), )); final WidgetWithNoLocalHistoryState state = tester.state(find.byType(WidgetWithNoLocalHistory)); state.addLocalHistory(); // Waits for modal route to update its internal state; await tester.pump(); // Pumps a new widget to dispose WidgetWithNoLocalHistory. This should cause // it to remove the local history entry from modal route during // finalizeTree. await tester.pumpWidget(const MaterialApp( home: Text('dummy'), )); await tester.pump(); expect(tester.takeException(), null); }); }); testWidgets('can be dismissed with escape keyboard shortcut', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); await tester.pumpWidget(MaterialApp( navigatorKey: navigatorKey, home: const Text('dummy1'), )); final Element textOnPageOne = tester.element(find.text('dummy1')); // Show a simple dialog showDialog<void>( context: textOnPageOne, builder: (BuildContext context) => const Text('dialog1'), ); await tester.pumpAndSettle(); expect(find.text('dialog1'), findsOneWidget); // Try to dismiss the dialog with the shortcut key await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pumpAndSettle(); expect(find.text('dialog1'), findsNothing); }); testWidgets('can not be dismissed with escape keyboard shortcut if barrier not dismissible', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); await tester.pumpWidget(MaterialApp( navigatorKey: navigatorKey, home: const Text('dummy1'), )); final Element textOnPageOne = tester.element(find.text('dummy1')); // Show a simple dialog showDialog<void>( context: textOnPageOne, barrierDismissible: false, builder: (BuildContext context) => const Text('dialog1'), ); await tester.pumpAndSettle(); expect(find.text('dialog1'), findsOneWidget); // Try to dismiss the dialog with the shortcut key await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pumpAndSettle(); expect(find.text('dialog1'), findsOneWidget); }); testWidgets('ModalRoute.of works for void routes', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); await tester.pumpWidget(MaterialApp( navigatorKey: navigatorKey, home: const Text('home'), )); expect(find.text('page2'), findsNothing); navigatorKey.currentState!.push<void>(MaterialPageRoute<void>( builder: (BuildContext context) { return const Text('page2'); }, )); await tester.pumpAndSettle(); expect(find.text('page2'), findsOneWidget); final ModalRoute<void>? parentRoute = ModalRoute.of<void>(tester.element(find.text('page2'))); expect(parentRoute, isNotNull); expect(parentRoute, isA<MaterialPageRoute<void>>()); }); testWidgets('RawDialogRoute is state restorable', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( restorationScopeId: 'app', home: _RestorableDialogTestWidget(), ), ); expect(find.byType(AlertDialog), findsNothing); await tester.tap(find.text('X')); await tester.pumpAndSettle(); expect(find.byType(AlertDialog), findsOneWidget); final TestRestorationData restorationData = await tester.getRestorationData(); await tester.restartAndRestore(); expect(find.byType(AlertDialog), findsOneWidget); // Tap on the barrier. await tester.tapAt(const Offset(10.0, 10.0)); await tester.pumpAndSettle(); expect(find.byType(AlertDialog), findsNothing); await tester.restoreFrom(restorationData); expect(find.byType(AlertDialog), findsOneWidget); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/33615 } double _getOpacity(GlobalKey key, WidgetTester tester) { final Finder finder = find.ancestor( of: find.byKey(key), matching: find.byType(FadeTransition), ); return tester.widgetList(finder).fold<double>(1.0, (double a, Widget widget) { final FadeTransition transition = widget as FadeTransition; return a * transition.opacity.value; }); } class ModifiedReverseTransitionDurationRoute<T> extends MaterialPageRoute<T> { ModifiedReverseTransitionDurationRoute({ required super.builder, super.settings, required this.reverseTransitionDuration, super.fullscreenDialog, }); @override final Duration reverseTransitionDuration; } class MockPageRoute extends Fake implements PageRoute<dynamic> { } class MockRoute extends Fake implements Route<dynamic> { } class MockRouteAware extends Fake implements RouteAware { int didPushCount = 0; int didPushNextCount = 0; int didPopCount = 0; int didPopNextCount = 0; @override void didPush() { didPushCount += 1; } @override void didPushNext() { didPushNextCount += 1; } @override void didPop() { didPopCount += 1; } @override void didPopNext() { didPopNextCount += 1; } } class TestPageRouteBuilder extends PageRouteBuilder<void> { TestPageRouteBuilder({required super.pageBuilder}); @override Animation<double> createAnimation() { return CurvedAnimation(parent: super.createAnimation(), curve: Curves.easeOutExpo); } } class DialogObserver extends NavigatorObserver { final List<ModalRoute<dynamic>> dialogRoutes = <ModalRoute<dynamic>>[]; int dialogCount = 0; @override void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) { if (route is RawDialogRoute) { dialogRoutes.add(route); dialogCount++; } super.didPush(route, previousRoute); } @override void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) { if (route is RawDialogRoute) { dialogRoutes.removeLast(); dialogCount--; } super.didPop(route, previousRoute); } } class _TestDialogRouteWithCustomBarrierCurve<T> extends PopupRoute<T> { _TestDialogRouteWithCustomBarrierCurve({ required Widget child, this.barrierLabel, this.barrierColor = Colors.black, Curve? barrierCurve, }) : _barrierCurve = barrierCurve, _child = child; final Widget _child; @override bool get barrierDismissible => true; @override final String? barrierLabel; @override final Color? barrierColor; @override Curve get barrierCurve => _barrierCurve ?? super.barrierCurve; final Curve? _barrierCurve; @override Duration get transitionDuration => const Duration(milliseconds: 100); // easier value to test against @override Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { return Semantics( scopesRoute: true, explicitChildNodes: true, child: _child, ); } } class WidgetWithLocalHistory extends StatefulWidget { const WidgetWithLocalHistory({super.key}); @override WidgetWithLocalHistoryState createState() => WidgetWithLocalHistoryState(); } class WidgetWithLocalHistoryState extends State<WidgetWithLocalHistory> { late LocalHistoryEntry _localHistory; void addLocalHistory() { final ModalRoute<dynamic> route = ModalRoute.of(context)!; _localHistory = LocalHistoryEntry(); route.addLocalHistoryEntry(_localHistory); } @override void dispose() { super.dispose(); _localHistory.remove(); } @override Widget build(BuildContext context) { return const Text('dummy'); } } class WidgetWithNoLocalHistory extends StatefulWidget { const WidgetWithNoLocalHistory({super.key}); @override WidgetWithNoLocalHistoryState createState() => WidgetWithNoLocalHistoryState(); } class WidgetWithNoLocalHistoryState extends State<WidgetWithNoLocalHistory> { late LocalHistoryEntry _localHistory; void addLocalHistory() { _localHistory = LocalHistoryEntry(); // Not calling `route.addLocalHistoryEntry` here. } @override void dispose() { super.dispose(); _localHistory.remove(); } @override Widget build(BuildContext context) { return const Text('dummy'); } } class _RestorableDialogTestWidget extends StatelessWidget { const _RestorableDialogTestWidget(); @pragma('vm:entry-point') static Route<Object?> _dialogBuilder(BuildContext context, Object? arguments) { return RawDialogRoute<void>( pageBuilder: ( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, ) { return const AlertDialog(title: Text('Alert!')); }, ); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: OutlinedButton( onPressed: () { Navigator.of(context).restorablePush(_dialogBuilder); }, child: const Text('X'), ), ), ); } }
flutter/packages/flutter/test/widgets/routes_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/routes_test.dart", "repo_id": "flutter", "token_count": 31988 }
702
// 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 'package:flutter/gestures.dart' show DragStartBehavior; import 'package:flutter/material.dart'; import 'package:flutter/services.dart' show LogicalKeyboardKey; import 'package:flutter_test/flutter_test.dart'; import 'states.dart'; class MaterialLocalizationsDelegate extends LocalizationsDelegate<MaterialLocalizations> { @override bool isSupported(Locale locale) => true; @override Future<MaterialLocalizations> load(Locale locale) => DefaultMaterialLocalizations.load(locale); @override bool shouldReload(MaterialLocalizationsDelegate old) => false; } class WidgetsLocalizationsDelegate extends LocalizationsDelegate<WidgetsLocalizations> { @override bool isSupported(Locale locale) => true; @override Future<WidgetsLocalizations> load(Locale locale) => DefaultWidgetsLocalizations.load(locale); @override bool shouldReload(WidgetsLocalizationsDelegate old) => false; } Widget textFieldBoilerplate({ required Widget child }) { return MaterialApp( home: Localizations( locale: const Locale('en', 'US'), delegates: <LocalizationsDelegate<dynamic>>[ WidgetsLocalizationsDelegate(), MaterialLocalizationsDelegate(), ], child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(size: Size(800.0, 600.0)), child: Center( child: Material( child: child, ), ), ), ), ), ); } Widget primaryScrollControllerBoilerplate({ required Widget child, required ScrollController controller }) { return Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: PrimaryScrollController( controller: controller, child: child, ), ), ); } void main() { testWidgets('ListView control test', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( dragStartBehavior: DragStartBehavior.down, children: kStates.map<Widget>((String state) { return GestureDetector( onTap: () { log.add(state); }, dragStartBehavior: DragStartBehavior.down, child: Container( height: 200.0, color: const Color(0xFF0000FF), child: Text(state), ), ); }).toList(), ), ), ); await tester.tap(find.text('Alabama')); expect(log, equals(<String>['Alabama'])); log.clear(); expect(find.text('Nevada'), findsNothing); await tester.drag(find.text('Alabama'), const Offset(0.0, -4000.0)); await tester.pump(); expect(find.text('Alabama'), findsNothing); expect(tester.getCenter(find.text('Massachusetts')), equals(const Offset(400.0, 100.0))); await tester.tap(find.text('Massachusetts')); expect(log, equals(<String>['Massachusetts'])); log.clear(); }); testWidgets('ListView dismiss keyboard onDrag test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: ListView( padding: EdgeInsets.zero, keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, children: focusNodes.map((FocusNode focusNode) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNode, style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }).toList(), ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isFalse); }); testWidgets('GridView.builder supports null items', (WidgetTester tester) async { await tester.pumpWidget(textFieldBoilerplate( child: GridView.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 42, ), itemCount: 42, itemBuilder: (BuildContext context, int index) { if (index == 5) { return null; } return const Text('item'); }, ), )); expect(find.text('item'), findsNWidgets(5)); }); testWidgets('ListView.builder supports null items', (WidgetTester tester) async { await tester.pumpWidget(textFieldBoilerplate( child: ListView.builder( itemCount: 42, itemBuilder: (BuildContext context, int index) { if (index == 5) { return null; } return const Text('item'); }, ), )); expect(find.text('item'), findsNWidgets(5)); }); testWidgets('PageView supports null items in itemBuilder', (WidgetTester tester) async { final PageController controller = PageController(viewportFraction: 1 / 5); addTearDown(controller.dispose); await tester.pumpWidget(textFieldBoilerplate( child: PageView.builder( itemCount: 5, controller: controller, itemBuilder: (BuildContext context, int index) { if (index == 2) { return null; } return const Text('item'); }, ), )); expect(find.text('item'), findsNWidgets(2)); }); testWidgets('ListView.separated supports null items in itemBuilder', (WidgetTester tester) async { await tester.pumpWidget(textFieldBoilerplate( child: ListView.separated( itemCount: 42, separatorBuilder: (BuildContext context, int index) { return const Text('separator'); }, itemBuilder: (BuildContext context, int index) { if (index == 5) { return null; } return const Text('item'); }, ), )); expect(find.text('item'), findsNWidgets(5)); expect(find.text('separator'), findsNWidgets(5)); }); testWidgets('ListView.builder dismiss keyboard onDrag test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: ListView.builder( padding: EdgeInsets.zero, keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, itemCount: focusNodes.length, itemBuilder: (BuildContext context,int index) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNodes[index], style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }, ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isFalse); }); testWidgets('ListView.custom dismiss keyboard onDrag test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: ListView.custom( padding: EdgeInsets.zero, keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, childrenDelegate: SliverChildBuilderDelegate( (BuildContext context,int index) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNodes[index], style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }, childCount: focusNodes.length, ), ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isFalse); }); testWidgets('ListView.separated dismiss keyboard onDrag test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: ListView.separated( padding: EdgeInsets.zero, keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, itemCount: focusNodes.length, separatorBuilder: (BuildContext context, int index) => const Divider(), itemBuilder: (BuildContext context,int index) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNodes[index], style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }, ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isFalse); }); testWidgets('GridView dismiss keyboard onDrag test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: GridView( padding: EdgeInsets.zero, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount:2), keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, children: focusNodes.map((FocusNode focusNode) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNode, style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }).toList(), ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isFalse); }); testWidgets('GridView.builder dismiss keyboard onDrag test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: GridView.builder( padding: EdgeInsets.zero, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount:2), keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, itemCount: focusNodes.length, itemBuilder: (BuildContext context, int index) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNodes[index], style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }, ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isFalse); }); testWidgets('GridView.count dismiss keyboard onDrag test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: GridView.count( padding: EdgeInsets.zero, crossAxisCount: 2, keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, children: focusNodes.map((FocusNode focusNode) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNode, style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }).toList(), ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isFalse); }); testWidgets('GridView.extent dismiss keyboard onDrag test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: GridView.extent( padding: EdgeInsets.zero, maxCrossAxisExtent: 300, keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, children: focusNodes.map((FocusNode focusNode) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNode, style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }).toList(), ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isFalse); }); testWidgets('GridView.custom dismiss keyboard onDrag test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: GridView.custom( padding: EdgeInsets.zero, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount:2), keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, childrenDelegate: SliverChildBuilderDelegate( (BuildContext context,int index) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNodes[index], style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }, childCount: focusNodes.length, ), ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isFalse); }); testWidgets('ListView dismiss keyboard manual test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: ListView( padding: EdgeInsets.zero, children: focusNodes.map((FocusNode focusNode) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNode, style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }).toList(), ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isTrue); }); testWidgets('ListView.builder dismiss keyboard manual test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: ListView.builder( padding: EdgeInsets.zero, itemCount: focusNodes.length, itemBuilder: (BuildContext context,int index) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNodes[index], style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }, ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isTrue); }); testWidgets('ListView.custom dismiss keyboard manual test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: ListView.custom( padding: EdgeInsets.zero, childrenDelegate: SliverChildBuilderDelegate( (BuildContext context,int index) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNodes[index], style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }, childCount: focusNodes.length, ), ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isTrue); }); testWidgets('ListView.separated dismiss keyboard manual test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: ListView.separated( padding: EdgeInsets.zero, itemCount: focusNodes.length, separatorBuilder: (BuildContext context, int index) => const Divider(), itemBuilder: (BuildContext context,int index) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNodes[index], style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }, ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isTrue); }); testWidgets('GridView dismiss keyboard manual test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: GridView( padding: EdgeInsets.zero, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount:2), children: focusNodes.map((FocusNode focusNode) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNode, style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }).toList(), ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isTrue); }); testWidgets('GridView.builder dismiss keyboard manual test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: GridView.builder( padding: EdgeInsets.zero, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount:2), itemCount: focusNodes.length, itemBuilder: (BuildContext context, int index) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNodes[index], style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }, ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isTrue); }); testWidgets('GridView.count dismiss keyboard manual test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: GridView.count( padding: EdgeInsets.zero, crossAxisCount: 2, children: focusNodes.map((FocusNode focusNode) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNode, style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }).toList(), ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isTrue); }); testWidgets('GridView.extent dismiss keyboard manual test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: GridView.extent( padding: EdgeInsets.zero, maxCrossAxisExtent: 300, children: focusNodes.map((FocusNode focusNode) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNode, style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }).toList(), ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isTrue); }); testWidgets('GridView.custom dismiss keyboard manual test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: GridView.custom( padding: EdgeInsets.zero, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount:2), childrenDelegate: SliverChildBuilderDelegate( (BuildContext context,int index) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNodes[index], style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }, childCount: focusNodes.length, ), ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isTrue); }); testWidgets('ListView restart ballistic activity out of range', (WidgetTester tester) async { Widget buildListView(int n) { return Directionality( textDirection: TextDirection.ltr, child: ListView( dragStartBehavior: DragStartBehavior.down, children: kStates.take(n).map<Widget>((String state) { return Container( height: 200.0, color: const Color(0xFF0000FF), child: Text(state), ); }).toList(), ), ); } await tester.pumpWidget(buildListView(30)); await tester.fling(find.byType(ListView), const Offset(0.0, -4000.0), 4000.0); await tester.pumpWidget(buildListView(15)); await tester.pump(const Duration(milliseconds: 10)); await tester.pump(const Duration(milliseconds: 10)); await tester.pump(const Duration(milliseconds: 10)); await tester.pump(const Duration(milliseconds: 10)); await tester.pumpAndSettle(); final Viewport viewport = tester.widget(find.byType(Viewport)); expect(viewport.offset.pixels, equals(2400.0)); }); testWidgets('CustomScrollView control test', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( dragStartBehavior: DragStartBehavior.down, slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate( kStates.map<Widget>((String state) { return GestureDetector( dragStartBehavior: DragStartBehavior.down, onTap: () { log.add(state); }, child: Container( height: 200.0, color: const Color(0xFF0000FF), child: Text(state), ), ); }).toList(), ), ), ], ), ), ); await tester.tap(find.text('Alabama')); expect(log, equals(<String>['Alabama'])); log.clear(); expect(find.text('Nevada'), findsNothing); await tester.drag(find.text('Alabama'), const Offset(0.0, -4000.0)); await tester.pump(); expect(find.text('Alabama'), findsNothing); expect(tester.getCenter(find.text('Massachusetts')), equals(const Offset(400.0, 100.0))); await tester.tap(find.text('Massachusetts')); expect(log, equals(<String>['Massachusetts'])); log.clear(); }); testWidgets('CustomScrollView dismiss keyboard onDrag test', (WidgetTester tester) async { final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode()); addTearDown(() { for (final FocusNode node in focusNodes) { node.dispose(); } }); await tester.pumpWidget(textFieldBoilerplate( child: CustomScrollView( dragStartBehavior: DragStartBehavior.down, keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate( focusNodes.map((FocusNode focusNode) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNode, style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), ); }).toList(), ), ), ], ), )); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); await tester.showKeyboard(finder); expect(textField.focusNode!.hasFocus, isTrue); await tester.drag(finder, const Offset(0.0, -40.0)); await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isFalse); }); testWidgets('Can jumpTo during drag', (WidgetTester tester) async { final List<Type> log = <Type>[]; final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: NotificationListener<ScrollNotification>( onNotification: (ScrollNotification notification) { log.add(notification.runtimeType); return false; }, child: ListView( controller: controller, children: kStates.map<Widget>((String state) { return SizedBox( height: 200.0, child: Text(state), ); }).toList(), ), ), ), ); expect(log, isEmpty); final TestGesture gesture = await tester.startGesture(const Offset(100.0, 100.0)); await gesture.moveBy(const Offset(0.0, -100.0)); expect(log, equals(<Type>[ ScrollStartNotification, UserScrollNotification, ScrollUpdateNotification, ])); log.clear(); await tester.pump(); controller.jumpTo(550.0); expect(controller.offset, equals(550.0)); expect(log, equals(<Type>[ ScrollEndNotification, UserScrollNotification, ScrollStartNotification, ScrollUpdateNotification, ScrollEndNotification, ])); log.clear(); await tester.pump(); await gesture.moveBy(const Offset(0.0, -100.0)); expect(controller.offset, equals(550.0)); expect(log, isEmpty); }); test('PrimaryScrollController.automaticallyInheritOnPlatforms defaults to all mobile platforms', (){ final ScrollController controller = ScrollController(); addTearDown(controller.dispose); final PrimaryScrollController primaryScrollController = PrimaryScrollController( controller: controller, child: const SizedBox(), ); expect( primaryScrollController.automaticallyInheritForPlatforms, TargetPlatformVariant.mobile().values, ); }); testWidgets('Vertical CustomScrollViews are not primary by default', (WidgetTester tester) async { const CustomScrollView view = CustomScrollView(); expect(view.primary, isNull); }); testWidgets('Vertical CustomScrollViews use PrimaryScrollController by default on mobile', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(primaryScrollControllerBoilerplate( child: const CustomScrollView(), controller: controller, )); expect(controller.hasClients, isTrue); }, variant: TargetPlatformVariant.mobile()); testWidgets("Vertical CustomScrollViews don't use PrimaryScrollController by default on desktop", (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(primaryScrollControllerBoilerplate( child: const CustomScrollView(), controller: controller, )); expect(controller.hasClients, isFalse); }, variant: TargetPlatformVariant.desktop()); testWidgets('Vertical ListViews are not primary by default', (WidgetTester tester) async { final ListView view = ListView(); expect(view.primary, isNull); }); testWidgets('Vertical ListViews use PrimaryScrollController by default on mobile', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(primaryScrollControllerBoilerplate( child: ListView(), controller: controller, )); expect(controller.hasClients, isTrue); }, variant: TargetPlatformVariant.mobile()); testWidgets("Vertical ListViews don't use PrimaryScrollController by default on desktop", (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(primaryScrollControllerBoilerplate( child: ListView(), controller: controller, )); expect(controller.hasClients, isFalse); }, variant: TargetPlatformVariant.desktop()); testWidgets('Vertical GridViews are not primary by default', (WidgetTester tester) async { final GridView view = GridView.count(crossAxisCount: 1); expect(view.primary, isNull); }); testWidgets('Vertical GridViews use PrimaryScrollController by default on mobile', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(primaryScrollControllerBoilerplate( child: GridView.count(crossAxisCount: 1), controller: controller, )); expect(controller.hasClients, isTrue); }, variant: TargetPlatformVariant.mobile()); testWidgets("Vertical GridViews don't use PrimaryScrollController by default on desktop", (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(primaryScrollControllerBoilerplate( child: GridView.count(crossAxisCount: 1), controller: controller, )); expect(controller.hasClients, isFalse); }, variant: TargetPlatformVariant.desktop()); testWidgets('Horizontal CustomScrollViews are non-primary by default', (WidgetTester tester) async { final ScrollController controller1 = ScrollController(); addTearDown(controller1.dispose); final ScrollController controller2 = ScrollController(); addTearDown(controller2.dispose); await tester.pumpWidget(primaryScrollControllerBoilerplate( child: CustomScrollView( scrollDirection: Axis.horizontal, controller: controller2, ), controller: controller1, )); expect(controller1.hasClients, isFalse); }); testWidgets('Horizontal ListViews are non-primary by default', (WidgetTester tester) async { final ScrollController controller1 = ScrollController(); addTearDown(controller1.dispose); final ScrollController controller2 = ScrollController(); addTearDown(controller2.dispose); await tester.pumpWidget(primaryScrollControllerBoilerplate( child: ListView( scrollDirection: Axis.horizontal, controller: controller2, ), controller: controller1, )); expect(controller1.hasClients, isFalse); }); testWidgets('Horizontal GridViews are non-primary by default', (WidgetTester tester) async { final ScrollController controller1 = ScrollController(); addTearDown(controller1.dispose); final ScrollController controller2 = ScrollController(); addTearDown(controller2.dispose); await tester.pumpWidget(primaryScrollControllerBoilerplate( child: GridView.count( scrollDirection: Axis.horizontal, controller: controller2, crossAxisCount: 1, ), controller: controller1, )); expect(controller1.hasClients, isFalse); }); testWidgets('CustomScrollViews with controllers are non-primary by default', (WidgetTester tester) async { final ScrollController controller1 = ScrollController(); addTearDown(controller1.dispose); final ScrollController controller2 = ScrollController(); addTearDown(controller2.dispose); await tester.pumpWidget(primaryScrollControllerBoilerplate( child: CustomScrollView( controller: controller2, ), controller: controller1, )); expect(controller1.hasClients, isFalse); }); testWidgets('ListViews with controllers are non-primary by default', (WidgetTester tester) async { final ScrollController controller1 = ScrollController(); addTearDown(controller1.dispose); final ScrollController controller2 = ScrollController(); addTearDown(controller2.dispose); await tester.pumpWidget(primaryScrollControllerBoilerplate( child: ListView( controller: controller2, ), controller: controller1, )); expect(controller1.hasClients, isFalse); }); testWidgets('GridViews with controllers are non-primary by default', (WidgetTester tester) async { final ScrollController controller1 = ScrollController(); addTearDown(controller1.dispose); final ScrollController controller2 = ScrollController(); addTearDown(controller2.dispose); await tester.pumpWidget(primaryScrollControllerBoilerplate( child: GridView.count( controller: controller2, crossAxisCount: 1, ), controller: controller1, )); expect(controller1.hasClients, isFalse); }); testWidgets('CustomScrollView sets PrimaryScrollController when primary', (WidgetTester tester) async { final ScrollController primaryScrollController = ScrollController(); addTearDown(primaryScrollController.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: PrimaryScrollController( controller: primaryScrollController, child: const CustomScrollView(primary: true), ), ), ); final Scrollable scrollable = tester.widget(find.byType(Scrollable)); expect(scrollable.controller, primaryScrollController); }); testWidgets('ListView sets PrimaryScrollController when primary', (WidgetTester tester) async { final ScrollController primaryScrollController = ScrollController(); addTearDown(primaryScrollController.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: PrimaryScrollController( controller: primaryScrollController, child: ListView(primary: true), ), ), ); final Scrollable scrollable = tester.widget(find.byType(Scrollable)); expect(scrollable.controller, primaryScrollController); }); testWidgets('GridView sets PrimaryScrollController when primary', (WidgetTester tester) async { final ScrollController primaryScrollController = ScrollController(); addTearDown(primaryScrollController.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: PrimaryScrollController( controller: primaryScrollController, child: GridView.count(primary: true, crossAxisCount: 1), ), ), ); final Scrollable scrollable = tester.widget(find.byType(Scrollable)); expect(scrollable.controller, primaryScrollController); }); testWidgets('Nested scrollables have a null PrimaryScrollController', (WidgetTester tester) async { const Key innerKey = Key('inner'); final ScrollController primaryScrollController = ScrollController(); addTearDown(primaryScrollController.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: PrimaryScrollController( controller: primaryScrollController, child: ListView( primary: true, children: <Widget>[ Container( constraints: const BoxConstraints(maxHeight: 200.0), child: ListView(key: innerKey, primary: true), ), ], ), ), ), ); final Scrollable innerScrollable = tester.widget( find.descendant( of: find.byKey(innerKey), matching: find.byType(Scrollable), ), ); expect(innerScrollable.controller, isNull); }); testWidgets('Primary ListViews are always scrollable', (WidgetTester tester) async { final ListView view = ListView(primary: true); expect(view.physics, isA<AlwaysScrollableScrollPhysics>()); }); testWidgets('Non-primary ListViews are not always scrollable', (WidgetTester tester) async { final ListView view = ListView(primary: false); expect(view.physics, isNot(isA<AlwaysScrollableScrollPhysics>())); }); testWidgets('Defaulting-to-primary ListViews are always scrollable', (WidgetTester tester) async { final ListView view = ListView(); expect(view.physics, isA<AlwaysScrollableScrollPhysics>()); }); testWidgets('Defaulting-to-not-primary ListViews are not always scrollable', (WidgetTester tester) async { final ListView view = ListView(scrollDirection: Axis.horizontal); expect(view.physics, isNot(isA<AlwaysScrollableScrollPhysics>())); }); testWidgets('primary:true leads to scrolling', (WidgetTester tester) async { bool scrolled = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: NotificationListener<OverscrollNotification>( onNotification: (OverscrollNotification message) { scrolled = true; return false; }, child: ListView( primary: true, ), ), ), ); await tester.dragFrom(const Offset(100.0, 100.0), const Offset(0.0, 100.0)); expect(scrolled, isTrue); }); testWidgets('primary:false leads to no scrolling', (WidgetTester tester) async { bool scrolled = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: NotificationListener<OverscrollNotification>( onNotification: (OverscrollNotification message) { scrolled = true; return false; }, child: ListView( primary: false, ), ), ), ); await tester.dragFrom(const Offset(100.0, 100.0), const Offset(0.0, 100.0)); expect(scrolled, isFalse); }); testWidgets('physics:AlwaysScrollableScrollPhysics actually overrides primary:false default behavior', (WidgetTester tester) async { bool scrolled = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: NotificationListener<OverscrollNotification>( onNotification: (OverscrollNotification message) { scrolled = true; return false; }, child: ListView( primary: false, physics: const AlwaysScrollableScrollPhysics(), ), ), ), ); await tester.dragFrom(const Offset(100.0, 100.0), const Offset(0.0, 100.0)); expect(scrolled, isTrue); }); testWidgets('physics:ScrollPhysics actually overrides primary:true default behavior', (WidgetTester tester) async { bool scrolled = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: NotificationListener<OverscrollNotification>( onNotification: (OverscrollNotification message) { scrolled = true; return false; }, child: ListView( primary: true, physics: const ScrollPhysics(), ), ), ), ); await tester.dragFrom(const Offset(100.0, 100.0), const Offset(0.0, 100.0)); expect(scrolled, isFalse); }); testWidgets('separatorBuilder must return something', (WidgetTester tester) async { const List<String> listOfValues = <String>['ALPHA', 'BETA', 'GAMMA', 'DELTA']; Widget buildFrame(Widget firstSeparator) { return MaterialApp( home: Material( child: ListView.separated( itemBuilder: (BuildContext context, int index) { return Text(listOfValues[index]); }, separatorBuilder: (BuildContext context, int index) { if (index == 0) { return firstSeparator; } else { return const Divider(); } }, itemCount: listOfValues.length, ), ), ); } // A separatorBuilder that always returns a Divider is fine await tester.pumpWidget(buildFrame(const Divider())); expect(tester.takeException(), isNull); }); testWidgets('when itemBuilder throws, creates Error Widget', (WidgetTester tester) async { const List<String> listOfValues = <String>['ALPHA', 'BETA', 'GAMMA', 'DELTA']; Widget buildFrame(bool throwOnFirstItem) { return MaterialApp( home: Material( child: ListView.builder( itemBuilder: (BuildContext context, int index) { if (index == 0 && throwOnFirstItem) { throw Exception('itemBuilder fail'); } return Text(listOfValues[index]); }, itemCount: listOfValues.length, ), ), ); } // When itemBuilder doesn't throw, no ErrorWidget await tester.pumpWidget(buildFrame(false)); expect(tester.takeException(), isNull); final Finder finder = find.byType(ErrorWidget); expect(find.byType(ErrorWidget), findsNothing); // When it does throw, one error widget is rendered in the item's place await tester.pumpWidget(buildFrame(true)); expect(tester.takeException(), isA<Exception>()); expect(finder, findsOneWidget); }); testWidgets('when separatorBuilder throws, creates ErrorWidget', (WidgetTester tester) async { const List<String> listOfValues = <String>['ALPHA', 'BETA', 'GAMMA', 'DELTA']; const Key key = Key('list'); Widget buildFrame(bool throwOnFirstSeparator) { return MaterialApp( home: Material( child: ListView.separated( key: key, itemBuilder: (BuildContext context, int index) { return Text(listOfValues[index]); }, separatorBuilder: (BuildContext context, int index) { if (index == 0 && throwOnFirstSeparator) { throw Exception('separatorBuilder fail'); } return const Divider(); }, itemCount: listOfValues.length, ), ), ); } // When separatorBuilder doesn't throw, no ErrorWidget await tester.pumpWidget(buildFrame(false)); expect(tester.takeException(), isNull); final Finder finder = find.byType(ErrorWidget); expect(find.byType(ErrorWidget), findsNothing); // When it does throw, one error widget is rendered in the separator's place await tester.pumpWidget(buildFrame(true)); expect(tester.takeException(), isA<Exception>()); expect(finder, findsOneWidget); }); testWidgets('ListView asserts on both non-null itemExtent and prototypeItem', (WidgetTester tester) async { expect(() => ListView( itemExtent: 100, prototypeItem: const SizedBox(), ), throwsAssertionError); }); testWidgets('ListView.builder asserts on negative childCount', (WidgetTester tester) async { expect(() => ListView.builder( itemBuilder: (BuildContext context, int index) { return const SizedBox(); }, itemCount: -1, ), throwsAssertionError); }); testWidgets('ListView.builder asserts on negative semanticChildCount', (WidgetTester tester) async { expect(() => ListView.builder( itemBuilder: (BuildContext context, int index) { return const SizedBox(); }, itemCount: 1, semanticChildCount: -1, ), throwsAssertionError); }); testWidgets('ListView.builder asserts on nonsensical childCount/semanticChildCount', (WidgetTester tester) async { expect(() => ListView.builder( itemBuilder: (BuildContext context, int index) { return const SizedBox(); }, itemCount: 1, semanticChildCount: 4, ), throwsAssertionError); }); testWidgets('ListView.builder asserts on both non-null itemExtent and prototypeItem', (WidgetTester tester) async { expect(() => ListView.builder( itemBuilder: (BuildContext context, int index) { return const SizedBox(); }, itemExtent: 100, prototypeItem: const SizedBox(), ), throwsAssertionError); }); testWidgets('ListView.custom asserts on both non-null itemExtent and prototypeItem', (WidgetTester tester) async { expect(() => ListView.custom( childrenDelegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return const SizedBox(); }, ), itemExtent: 100, prototypeItem: const SizedBox(), ), throwsAssertionError); }); testWidgets('PrimaryScrollController provides fallback ScrollActions', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: CustomScrollView( primary: true, slivers: List<Widget>.generate( 20, (int index) { return SliverToBoxAdapter( child: Focus( autofocus: index == 0, child: SizedBox(key: ValueKey<String>('Box $index'), height: 50.0), ), ); }, ), ), ), ); final ScrollController controller = PrimaryScrollController.of( tester.element(find.byType(CustomScrollView)), ); await tester.pumpAndSettle(); expect(controller.position.pixels, equals(0.0)); expect( tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), ); await tester.sendKeyEvent(LogicalKeyboardKey.pageDown); await tester.pumpAndSettle(); expect(controller.position.pixels, equals(400.0)); expect( tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), equals(const Rect.fromLTRB(0.0, -400.0, 800.0, -350.0)), ); await tester.sendKeyEvent(LogicalKeyboardKey.pageUp); await tester.pumpAndSettle(); expect(controller.position.pixels, equals(0.0)); expect( tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), ); }); testWidgets('Fallback ScrollActions handle too many positions with error message', (WidgetTester tester) async { Widget getScrollView() { return SizedBox( width: 400.0, child: CustomScrollView( primary: true, slivers: List<Widget>.generate( 20, (int index) { return SliverToBoxAdapter( child: Focus( child: SizedBox(key: ValueKey<String>('Box $index'), height: 50.0), ), ); }, ), ), ); } await tester.pumpWidget( MaterialApp( home: Row( children: <Widget>[ getScrollView(), getScrollView(), ], ), ), ); await tester.pumpAndSettle(); expect( tester.getRect( find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false).first ), equals(const Rect.fromLTRB(0.0, 0.0, 400.0, 50.0)), ); await tester.sendKeyEvent(LogicalKeyboardKey.pageDown); final AssertionError exception = tester.takeException() as AssertionError; expect(exception, isAssertionError); expect( exception.message, contains( 'A ScrollAction was invoked with the PrimaryScrollController, but ' 'more than one ScrollPosition is attached.' ), ); }); testWidgets('if itemExtent is non-null, children have same extent in the scroll direction', (WidgetTester tester) async { final List<int> numbers = <int>[0,1,2]; await tester.pumpWidget( MaterialApp( home: Scaffold( body: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return ListView.builder( itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(numbers[index]), // children with different heights height: 20 + numbers[index] * 10, child: ReorderableDragStartListener( index: index, child: Text(numbers[index].toString()), ) ); }, itemCount: numbers.length, itemExtent: 30, ); }, ), ), ) ); final double item0Height = tester.getSize(find.text('0').hitTestable()).height; final double item1Height = tester.getSize(find.text('1').hitTestable()).height; final double item2Height = tester.getSize(find.text('2').hitTestable()).height; expect(item0Height, 30.0); expect(item1Height, 30.0); expect(item2Height, 30.0); }); testWidgets('if prototypeItem is non-null, children have same extent in the scroll direction', (WidgetTester tester) async { final List<int> numbers = <int>[0,1,2]; await tester.pumpWidget( MaterialApp( home: Scaffold( body: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return ListView.builder( itemBuilder: (BuildContext context, int index) { return SizedBox( key: ValueKey<int>(numbers[index]), // children with different heights height: 20 + numbers[index] * 10, child: ReorderableDragStartListener( index: index, child: Text(numbers[index].toString()), ) ); }, itemCount: numbers.length, prototypeItem: const SizedBox( height: 30, child: Text('3'), ), ); }, ), ), ) ); final double item0Height = tester.getSize(find.text('0').hitTestable()).height; final double item1Height = tester.getSize(find.text('1').hitTestable()).height; final double item2Height = tester.getSize(find.text('2').hitTestable()).height; expect(item0Height, 30.0); expect(item1Height, 30.0); expect(item2Height, 30.0); }); }
flutter/packages/flutter/test/widgets/scroll_view_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/scroll_view_test.dart", "repo_id": "flutter", "token_count": 24910 }
703
// 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 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'clipboard_utils.dart'; import 'keyboard_utils.dart'; import 'process_text_utils.dart'; import 'semantics_tester.dart'; Offset textOffsetToPosition(RenderParagraph paragraph, int offset) { const Rect caret = Rect.fromLTWH(0.0, 0.0, 2.0, 20.0); final Offset localOffset = paragraph.getOffsetForCaret(TextPosition(offset: offset), caret); return paragraph.localToGlobal(localOffset); } Offset globalize(Offset point, RenderBox box) { return box.localToGlobal(point); } void main() { TestWidgetsFlutterBinding.ensureInitialized(); final MockClipboard mockClipboard = MockClipboard(); setUp(() async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall); await Clipboard.setData(const ClipboardData(text: 'empty')); }); tearDown(() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null); }); group('SelectableRegion', () { testWidgets('mouse selection single click sends correct events', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), ), ); await tester.pumpAndSettle(); final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pumpAndSettle(); renderSelectionSpy.events.clear(); await gesture.moveTo(const Offset(200.0, 100.0)); expect(renderSelectionSpy.events.length, 2); expect(renderSelectionSpy.events[0].type, SelectionEventType.startEdgeUpdate); final SelectionEdgeUpdateEvent startEdge = renderSelectionSpy.events[0] as SelectionEdgeUpdateEvent; expect(startEdge.globalPosition, const Offset(200.0, 200.0)); expect(renderSelectionSpy.events[1].type, SelectionEventType.endEdgeUpdate); SelectionEdgeUpdateEvent endEdge = renderSelectionSpy.events[1] as SelectionEdgeUpdateEvent; expect(endEdge.globalPosition, const Offset(200.0, 100.0)); renderSelectionSpy.events.clear(); await gesture.moveTo(const Offset(100.0, 100.0)); expect(renderSelectionSpy.events.length, 1); expect(renderSelectionSpy.events[0].type, SelectionEventType.endEdgeUpdate); endEdge = renderSelectionSpy.events[0] as SelectionEdgeUpdateEvent; expect(endEdge.globalPosition, const Offset(100.0, 100.0)); await gesture.up(); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/102410. testWidgets('mouse double click sends select-word event', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), ) ); final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pump(); renderSelectionSpy.events.clear(); await gesture.down(const Offset(200.0, 200.0)); await tester.pump(); await gesture.up(); expect(renderSelectionSpy.events.length, 1); expect(renderSelectionSpy.events[0], isA<SelectWordSelectionEvent>()); final SelectWordSelectionEvent selectionEvent = renderSelectionSpy.events[0] as SelectWordSelectionEvent; expect(selectionEvent.globalPosition, const Offset(200.0, 200.0)); }); testWidgets('Does not crash when using Navigator pages', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/119776 final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: Navigator( pages: <Page<void>> [ MaterialPage<void>( child: Column( children: <Widget>[ const Text('How are you?'), SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const SelectAllWidget(child: SizedBox(width: 100, height: 100)), ), const Text('Fine, thank you.'), ], ), ), const MaterialPage<void>( child: Scaffold(body: Text('Foreground Page')), ), ], onPopPage: (_, __) => false, ), ), ); expect(tester.takeException(), isNull); }); testWidgets('can draw handles when they are at rect boundaries', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: Column( children: <Widget>[ const Text('How are you?'), SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectAllWidget(key: spy, child: const SizedBox(width: 100, height: 100)), ), const Text('Fine, thank you.'), ], ), ), ); await tester.pumpAndSettle(); final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(spy))); addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); await tester.pump(); final RenderSelectAll renderSpy = tester.renderObject<RenderSelectAll>(find.byKey(spy)); expect(renderSpy.startHandle, isNotNull); expect(renderSpy.endHandle, isNotNull); }); testWidgets('touch does not accept drag', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), ) ); final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0)); addTearDown(gesture.removePointer); await gesture.moveTo(const Offset(200.0, 100.0)); await gesture.up(); expect( renderSelectionSpy.events.every((SelectionEvent element) => element is ClearSelectionEvent), isTrue ); }); testWidgets('does not merge semantics node of the children', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Scaffold( body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ const Text('Line one'), const Text('Line two'), ElevatedButton( onPressed: () {}, child: const Text('Button'), ) ], ), ), ), ), ), ); expect( semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( label: 'Line one', textDirection: TextDirection.ltr, ), TestSemantics( label: 'Line two', textDirection: TextDirection.ltr, ), TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.isButton, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable ], actions: <SemanticsAction>[SemanticsAction.tap], label: 'Button', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ignoreRect: true, ignoreTransform: true, ignoreId: true, ), ); semantics.dispose(); }); testWidgets('mouse single-click selection collapses the selection', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), ) ); await tester.pumpAndSettle(); final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(renderSelectionSpy.events.length, 2); expect(renderSelectionSpy.events[0], isA<SelectionEdgeUpdateEvent>()); expect((renderSelectionSpy.events[0] as SelectionEdgeUpdateEvent).type, SelectionEventType.startEdgeUpdate); expect(renderSelectionSpy.events[1], isA<SelectionEdgeUpdateEvent>()); expect((renderSelectionSpy.events[1] as SelectionEdgeUpdateEvent).type, SelectionEventType.endEdgeUpdate); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/102410. testWidgets('touch long press sends select-word event', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), ) ); await tester.pumpAndSettle(); final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); renderSelectionSpy.events.clear(); final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0)); addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); expect(renderSelectionSpy.events.length, 1); expect(renderSelectionSpy.events[0], isA<SelectWordSelectionEvent>()); final SelectWordSelectionEvent selectionEvent = renderSelectionSpy.events[0] as SelectWordSelectionEvent; expect(selectionEvent.globalPosition, const Offset(200.0, 200.0)); }); testWidgets('touch long press and drag sends correct events', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), ) ); await tester.pumpAndSettle(); final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); renderSelectionSpy.events.clear(); final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0)); addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); expect(renderSelectionSpy.events.length, 1); expect(renderSelectionSpy.events[0], isA<SelectWordSelectionEvent>()); final SelectWordSelectionEvent selectionEvent = renderSelectionSpy.events[0] as SelectWordSelectionEvent; expect(selectionEvent.globalPosition, const Offset(200.0, 200.0)); renderSelectionSpy.events.clear(); await gesture.moveTo(const Offset(200.0, 50.0)); await gesture.up(); expect(renderSelectionSpy.events.length, 1); expect(renderSelectionSpy.events[0].type, SelectionEventType.endEdgeUpdate); final SelectionEdgeUpdateEvent edgeEvent = renderSelectionSpy.events[0] as SelectionEdgeUpdateEvent; expect(edgeEvent.globalPosition, const Offset(200.0, 50.0)); expect(edgeEvent.granularity, TextGranularity.word); }); testWidgets( 'touch long press cancel does not send ClearSelectionEvent', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), ), ); await tester.pumpAndSettle(); final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); renderSelectionSpy.events.clear(); final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0)); addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.cancel(); expect( renderSelectionSpy.events.any((SelectionEvent element) => element is ClearSelectionEvent), isFalse, ); }, ); testWidgets( 'scrolling after the selection does not send ClearSelectionEvent', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/128765 final UniqueKey spy = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SizedBox( height: 750, child: SingleChildScrollView( child: SizedBox( height: 2000, child: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), ), ), ), ), ); await tester.pumpAndSettle(); final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); renderSelectionSpy.events.clear(); final TestGesture selectGesture = await tester.startGesture(const Offset(200.0, 200.0)); addTearDown(selectGesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await selectGesture.up(); expect(renderSelectionSpy.events.length, 1); expect(renderSelectionSpy.events[0], isA<SelectWordSelectionEvent>()); renderSelectionSpy.events.clear(); final TestGesture scrollGesture = await tester.startGesture(const Offset(250.0, 850.0)); await tester.pump(const Duration(milliseconds: 500)); await scrollGesture.moveTo(Offset.zero); await scrollGesture.up(); await tester.pumpAndSettle(); expect(renderSelectionSpy.events.length, 0); }, ); testWidgets('mouse long press does not send select-word event', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), ), ); await tester.pumpAndSettle(); final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); renderSelectionSpy.events.clear(); final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); expect( renderSelectionSpy.events.every((SelectionEvent element) => element is SelectionEdgeUpdateEvent), isTrue, ); }); }); testWidgets('dragging handle or selecting word triggers haptic feedback on Android', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { log.add(methodCall); return null; }); addTearDown(() { tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall); }); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text('How are you?'), ), ), ); await tester.pumpAndSettle(); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 6)); // at the 'r' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); await tester.pump(const Duration(milliseconds: 500)); // `are` is selected. expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); expect( log.last, isMethodCall('HapticFeedback.vibrate', arguments: 'HapticFeedbackType.selectionClick'), ); log.clear(); final List<TextBox> boxes = paragraph.getBoxesForSelection(paragraph.selections[0]); expect(boxes.length, 1); final Offset handlePos = globalize(boxes[0].toRect().bottomRight, paragraph); await gesture.down(handlePos); final Offset endPos = Offset(textOffsetToPosition(paragraph, 8).dx, handlePos.dy); // Select 1 more character by dragging end handle to trigger feedback. await gesture.moveTo(endPos); expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 8)); // Only Android vibrate when dragging the handle. switch (defaultTargetPlatform) { case TargetPlatform.android: expect( log.last, isMethodCall('HapticFeedback.vibrate', arguments: 'HapticFeedbackType.selectionClick'), ); case TargetPlatform.fuchsia: case TargetPlatform.iOS: case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: expect(log, isEmpty); } await gesture.up(); }, variant: TargetPlatformVariant.all()); group('SelectionArea integration', () { testWidgets('mouse can select single text on desktop platforms', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Center( child: Text('How are you'), ), ), ), ); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph, 4)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4)); await gesture.moveTo(textOffsetToPosition(paragraph, 6)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6)); // Check backward selection. await gesture.moveTo(textOffsetToPosition(paragraph, 1)); await tester.pump(); expect(paragraph.selections.isEmpty, isFalse); expect(paragraph.selections[0], const TextSelection(baseOffset: 2, extentOffset: 1)); // Start a new drag. await gesture.up(); await tester.pumpAndSettle(); await gesture.down(textOffsetToPosition(paragraph, 5)); await tester.pumpAndSettle(); expect(paragraph.selections.isEmpty, isFalse); expect(paragraph.selections[0], const TextSelection.collapsed(offset: 5)); // Selecting across line should select to the end. await gesture.moveTo(textOffsetToPosition(paragraph, 5) + const Offset(0.0, 200.0)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 5, extentOffset: 11)); await gesture.up(); }, variant: TargetPlatformVariant.desktop()); testWidgets('mouse can select single text on mobile platforms', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Center( child: Text('How are you'), ), ), ), ); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph, 4)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4)); await gesture.moveTo(textOffsetToPosition(paragraph, 6)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6)); // Check backward selection. await gesture.moveTo(textOffsetToPosition(paragraph, 1)); await tester.pump(); expect(paragraph.selections.isEmpty, isFalse); expect(paragraph.selections[0], const TextSelection(baseOffset: 2, extentOffset: 1)); // Start a new drag. await gesture.up(); await tester.pumpAndSettle(); await gesture.down(textOffsetToPosition(paragraph, 5)); await tester.pumpAndSettle(); await gesture.moveTo(textOffsetToPosition(paragraph, 6)); await tester.pump(); expect(paragraph.selections.isEmpty, isFalse); expect(paragraph.selections[0], const TextSelection(baseOffset: 5, extentOffset: 6)); // Selecting across line should select to the end. await gesture.moveTo(textOffsetToPosition(paragraph, 5) + const Offset(0.0, 200.0)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 5, extentOffset: 11)); await gesture.up(); }, variant: TargetPlatformVariant.mobile()); testWidgets('mouse can select word-by-word on double click drag', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Center( child: Text('How are you'), ), ), ), ); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pump(); await gesture.down(textOffsetToPosition(paragraph, 2)); await tester.pumpAndSettle(); expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); await gesture.moveTo(textOffsetToPosition(paragraph, 3)); await tester.pumpAndSettle(); expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 4)); await gesture.moveTo(textOffsetToPosition(paragraph, 4)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); await gesture.moveTo(textOffsetToPosition(paragraph, 7)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 8)); await gesture.moveTo(textOffsetToPosition(paragraph, 8)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11)); // Check backward selection. await gesture.moveTo(textOffsetToPosition(paragraph, 1)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); // Start a new double-click drag. await gesture.up(); await tester.pump(); await gesture.down(textOffsetToPosition(paragraph, 5)); await tester.pump(); await gesture.up(); expect(paragraph.selections.isEmpty, isFalse); expect(paragraph.selections[0], const TextSelection.collapsed(offset: 5)); await tester.pump(kDoubleTapTimeout); // Double-click. await gesture.down(textOffsetToPosition(paragraph, 5)); await tester.pump(); await gesture.up(); await tester.pump(); await gesture.down(textOffsetToPosition(paragraph, 5)); await tester.pumpAndSettle(); expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); // Selecting across line should select to the end. await gesture.moveTo(textOffsetToPosition(paragraph, 5) + const Offset(0.0, 200.0)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 11)); await gesture.up(); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. testWidgets('mouse can select multiple widgets on double click drag', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pump(); await gesture.down(textOffsetToPosition(paragraph1, 2)); await tester.pumpAndSettle(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); await tester.pump(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); // Should select the rest of paragraph 1. expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11)); await gesture.up(); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. testWidgets('mouse can select multiple widgets on double click drag and return to origin word', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pump(); await gesture.down(textOffsetToPosition(paragraph1, 2)); await tester.pumpAndSettle(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); await tester.pump(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); // Should select the rest of paragraph 1. expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11)); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); // Should clear the selection on paragraph 3. expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); expect(paragraph3.selections.isEmpty, isTrue); await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); // Should clear the selection on paragraph 2. expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); expect(paragraph2.selections.isEmpty, isTrue); expect(paragraph3.selections.isEmpty, isTrue); await gesture.up(); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. testWidgets('mouse can reverse selection across multiple widgets on double click drag', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 10), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pump(); await gesture.down(textOffsetToPosition(paragraph3, 10)); await tester.pumpAndSettle(); expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11)); await gesture.moveTo(textOffsetToPosition(paragraph3, 4)); await tester.pump(); expect(paragraph3.selections[0], const TextSelection(baseOffset: 11, extentOffset: 4)); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 11, extentOffset: 0)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 14, extentOffset: 5)); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 11, extentOffset: 0)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 14, extentOffset: 0)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 12, extentOffset: 4)); await gesture.up(); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. testWidgets('mouse can select multiple widgets', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); await tester.pump(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4)); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); // Should select the rest of paragraph 1. expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); await gesture.up(); }); testWidgets('collapsing selection should clear selection of all other selectables', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(paragraph1.selections[0], const TextSelection.collapsed(offset: 2)); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); await gesture.down(textOffsetToPosition(paragraph2, 5)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(paragraph1.selections.isEmpty, isTrue); expect(paragraph2.selections[0], const TextSelection.collapsed(offset: 5)); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); await gesture.down(textOffsetToPosition(paragraph3, 13)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(paragraph1.selections.isEmpty, isTrue); expect(paragraph2.selections.isEmpty, isTrue); expect(paragraph3.selections[0], const TextSelection.collapsed(offset: 13)); }); testWidgets('mouse can work with disabled container', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), SelectionContainer.disabled(child: Text('Good, and you?')), Text('Fine, thank you.'), ], ), ), ), ); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); await tester.pump(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4)); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); // Should select the rest of paragraph 1. expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12)); // paragraph2 is in a disabled container. expect(paragraph2.selections.isEmpty, isTrue); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12)); expect(paragraph2.selections.isEmpty, isTrue); expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); await gesture.up(); }); testWidgets('mouse can reverse selection', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 10), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph3, 4)); await tester.pump(); expect(paragraph3.selections[0], const TextSelection(baseOffset: 10, extentOffset: 4)); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 10, extentOffset: 0)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 14, extentOffset: 5)); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 10, extentOffset: 0)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 14, extentOffset: 0)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 12, extentOffset: 6)); await gesture.up(); }); testWidgets( 'long press selection overlay behavior on iOS and Android', (WidgetTester tester) async { // This test verifies that all platforms wait until long press end to // show the context menu, and only Android waits until long press end to // show the selection handles. final bool isPlatformAndroid = defaultTargetPlatform == TargetPlatform.android; Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{}; final UniqueKey toolbarKey = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { buttonTypes = selectableRegionState.contextMenuButtonItems .map((ContextMenuButtonItem buttonItem) => buttonItem.type) .toSet(); return SizedBox.shrink(key: toolbarKey); }, child: const Text('How are you?'), ), ), ); expect(buttonTypes.isEmpty, true); expect(find.byKey(toolbarKey), findsNothing); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2)); addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await tester.pumpAndSettle(); // All platform except Android should show the selection handles when the // long press starts. List<FadeTransition> transitions = find.descendant( of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'), matching: find.byType(FadeTransition), ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); expect(transitions.length, isPlatformAndroid ? 0 : 2); FadeTransition? left; FadeTransition? right; if (!isPlatformAndroid) { left = transitions[0]; right = transitions[1]; expect(left.opacity.value, equals(1.0)); expect(right.opacity.value, equals(1.0)); } expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); expect(find.byKey(toolbarKey), findsNothing); await gesture.moveTo(textOffsetToPosition(paragraph, 8)); await tester.pumpAndSettle(); transitions = find.descendant( of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'), matching: find.byType(FadeTransition), ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); // All platform except Android should show the selection handles while doing // a long press drag. expect(transitions.length, isPlatformAndroid ? 0 : 2); if (!isPlatformAndroid) { left = transitions[0]; right = transitions[1]; expect(left.opacity.value, equals(1.0)); expect(right.opacity.value, equals(1.0)); } expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11)); expect(find.byKey(toolbarKey), findsNothing); await gesture.up(); await tester.pumpAndSettle(); transitions = find.descendant( of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'), matching: find.byType(FadeTransition), ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); expect(transitions.length, 2); left = transitions[0]; right = transitions[1]; // All platforms should show the selection handles and context menu when // the long press ends. expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11)); expect(left.opacity.value, equals(1.0)); expect(right.opacity.value, equals(1.0)); expect(find.byKey(toolbarKey), findsOneWidget); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }), skip: kIsWeb, // [intended] Web uses its native context menu. ); testWidgets( 'single tap on the previous selection toggles the toolbar on iOS', (WidgetTester tester) async { Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{}; final UniqueKey toolbarKey = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { buttonTypes = selectableRegionState.contextMenuButtonItems .map((ContextMenuButtonItem buttonItem) => buttonItem.type) .toSet(); return SizedBox.shrink(key: toolbarKey); }, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); expect(buttonTypes.isEmpty, true); expect(find.byKey(toolbarKey), findsNothing); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2)); addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); await tester.pumpAndSettle(); expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); expect(buttonTypes, contains(ContextMenuButtonType.copy)); expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); expect(find.byKey(toolbarKey), findsOneWidget); await gesture.down(textOffsetToPosition(paragraph, 2)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); expect(buttonTypes, contains(ContextMenuButtonType.copy)); expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); expect(find.byKey(toolbarKey), findsNothing); await gesture.down(textOffsetToPosition(paragraph, 2)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); expect(buttonTypes, contains(ContextMenuButtonType.copy)); expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); expect(find.byKey(toolbarKey), findsOneWidget); // Collapse selection. await tester.tapAt(textOffsetToPosition(paragraph, 9)); await tester.pump(); expect(paragraph.selections.isEmpty, isFalse); expect(paragraph.selections[0], const TextSelection.collapsed(offset: 9)); expect(find.byKey(toolbarKey), findsNothing); }, variant: TargetPlatformVariant.only(TargetPlatform.iOS), skip: kIsWeb, // [intended] Web uses its native context menu. ); testWidgets( 'right-click mouse can select word at position on Apple platforms', (WidgetTester tester) async { Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{}; final UniqueKey toolbarKey = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { buttonTypes = selectableRegionState.contextMenuButtonItems .map((ContextMenuButtonItem buttonItem) => buttonItem.type) .toSet(); return SizedBox.shrink(key: toolbarKey); }, child: const Center( child: Text('How are you'), ), ), ), ); expect(buttonTypes.isEmpty, true); expect(find.byKey(toolbarKey), findsNothing); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); final TestGesture primaryMouseButtonGesture = await tester.createGesture(kind: PointerDeviceKind.mouse); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton); addTearDown(primaryMouseButtonGesture.removePointer); addTearDown(gesture.removePointer); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); await gesture.up(); await tester.pump(); expect(buttonTypes, contains(ContextMenuButtonType.copy)); expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); expect(find.byKey(toolbarKey), findsOneWidget); await gesture.down(textOffsetToPosition(paragraph, 6)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); await gesture.up(); await tester.pump(); expect(buttonTypes, contains(ContextMenuButtonType.copy)); expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); expect(find.byKey(toolbarKey), findsOneWidget); await gesture.down(textOffsetToPosition(paragraph, 9)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 8, extentOffset: 11)); await gesture.up(); await tester.pump(); expect(buttonTypes, contains(ContextMenuButtonType.copy)); expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); expect(find.byKey(toolbarKey), findsOneWidget); // Collapse selection. await primaryMouseButtonGesture.down(textOffsetToPosition(paragraph, 1)); await tester.pump(); await primaryMouseButtonGesture.up(); await tester.pumpAndSettle(); // Selection is collapsed. expect(paragraph.selections.isEmpty, false); expect(paragraph.selections[0], const TextSelection.collapsed(offset: 1)); expect(find.byKey(toolbarKey), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), skip: kIsWeb, // [intended] Web uses its native context menu. ); testWidgets( 'right-click mouse at the same position as previous right-click toggles the context menu on macOS', (WidgetTester tester) async { Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{}; final UniqueKey toolbarKey = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { buttonTypes = selectableRegionState.contextMenuButtonItems .map((ContextMenuButtonItem buttonItem) => buttonItem.type) .toSet(); return SizedBox.shrink(key: toolbarKey); }, child: const Center( child: Text('How are you'), ), ), ), ); expect(buttonTypes.isEmpty, true); expect(find.byKey(toolbarKey), findsNothing); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton); final TestGesture primaryMouseButtonGesture = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(primaryMouseButtonGesture.removePointer); addTearDown(gesture.removePointer); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); await gesture.up(); await tester.pump(); expect(buttonTypes, contains(ContextMenuButtonType.copy)); expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); expect(find.byKey(toolbarKey), findsOneWidget); await gesture.down(textOffsetToPosition(paragraph, 2)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); await gesture.up(); await tester.pump(); // Right-click at same position will toggle the context menu off. expect(buttonTypes, contains(ContextMenuButtonType.copy)); expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); expect(find.byKey(toolbarKey), findsNothing); await gesture.down(textOffsetToPosition(paragraph, 9)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 8, extentOffset: 11)); await gesture.up(); await tester.pump(); expect(buttonTypes, contains(ContextMenuButtonType.copy)); expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); expect(find.byKey(toolbarKey), findsOneWidget); await gesture.down(textOffsetToPosition(paragraph, 9)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 8, extentOffset: 11)); await gesture.up(); await tester.pump(); // Right-click at same position will toggle the context menu off. expect(buttonTypes, contains(ContextMenuButtonType.copy)); expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); expect(find.byKey(toolbarKey), findsNothing); await gesture.down(textOffsetToPosition(paragraph, 6)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); await gesture.up(); await tester.pump(); expect(buttonTypes, contains(ContextMenuButtonType.copy)); expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); expect(find.byKey(toolbarKey), findsOneWidget); // Collapse selection. await primaryMouseButtonGesture.down(textOffsetToPosition(paragraph, 1)); await tester.pump(); await primaryMouseButtonGesture.up(); await tester.pumpAndSettle(); // Selection is collapsed. expect(paragraph.selections.isEmpty, false); expect(paragraph.selections[0], const TextSelection.collapsed(offset: 1)); expect(find.byKey(toolbarKey), findsNothing); }, variant: TargetPlatformVariant.only(TargetPlatform.macOS), skip: kIsWeb, // [intended] Web uses its native context menu. ); testWidgets( 'right-click mouse shows the context menu at position on Android, Fuchsia, and Windows', (WidgetTester tester) async { Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{}; final UniqueKey toolbarKey = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { buttonTypes = selectableRegionState.contextMenuButtonItems .map((ContextMenuButtonItem buttonItem) => buttonItem.type) .toSet(); return SizedBox.shrink(key: toolbarKey); }, child: const Center( child: Text('How are you'), ), ), ), ); expect(buttonTypes.isEmpty, true); expect(find.byKey(toolbarKey), findsNothing); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton); final TestGesture primaryMouseButtonGesture = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(primaryMouseButtonGesture.removePointer); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pump(); // Selection is collapsed. expect(paragraph.selections.isEmpty, false); expect(paragraph.selections[0], const TextSelection.collapsed(offset: 2)); expect(buttonTypes.length, 1); expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); expect(find.byKey(toolbarKey), findsOneWidget); await gesture.down(textOffsetToPosition(paragraph, 6)); await tester.pump(); expect(paragraph.selections.isEmpty, false); expect(paragraph.selections[0], const TextSelection.collapsed(offset: 6)); await gesture.up(); await tester.pump(); expect(buttonTypes.length, 1); expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); expect(find.byKey(toolbarKey), findsOneWidget); await gesture.down(textOffsetToPosition(paragraph, 9)); await tester.pump(); expect(paragraph.selections.isEmpty, false); expect(paragraph.selections[0], const TextSelection.collapsed(offset: 9)); await gesture.up(); await tester.pump(); expect(buttonTypes.length, 1); expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); expect(find.byKey(toolbarKey), findsOneWidget); // Collapse selection. await primaryMouseButtonGesture.down(textOffsetToPosition(paragraph, 1)); await tester.pump(); await primaryMouseButtonGesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); // Selection is collapsed. expect(paragraph.selections.isEmpty, false); expect(paragraph.selections[0], const TextSelection.collapsed(offset: 1)); expect(find.byKey(toolbarKey), findsNothing); // Create an uncollapsed selection by dragging. await primaryMouseButtonGesture.down(textOffsetToPosition(paragraph, 0)); await tester.pump(); await primaryMouseButtonGesture.moveTo(textOffsetToPosition(paragraph, 5)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); await primaryMouseButtonGesture.up(); await tester.pump(); // Right click on previous selection should not collapse the selection. await gesture.down(textOffsetToPosition(paragraph, 2)); await tester.pump(); await gesture.up(); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); expect(find.byKey(toolbarKey), findsOneWidget); // Right click anywhere outside previous selection should collapse the // selection. await gesture.down(textOffsetToPosition(paragraph, 7)); await tester.pump(); await gesture.up(); await tester.pump(); expect(paragraph.selections.isEmpty, false); expect(paragraph.selections[0], const TextSelection.collapsed(offset: 7)); expect(find.byKey(toolbarKey), findsOneWidget); // Collapse selection. await primaryMouseButtonGesture.down(textOffsetToPosition(paragraph, 1)); await tester.pump(); await primaryMouseButtonGesture.up(); await tester.pumpAndSettle(); // Selection is collapsed. expect(paragraph.selections.isEmpty, false); expect(paragraph.selections[0], const TextSelection.collapsed(offset: 1)); expect(find.byKey(toolbarKey), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.windows }), skip: kIsWeb, // [intended] Web uses its native context menu. ); testWidgets( 'right-click mouse toggles the context menu on Linux', (WidgetTester tester) async { Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{}; final UniqueKey toolbarKey = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { buttonTypes = selectableRegionState.contextMenuButtonItems .map((ContextMenuButtonItem buttonItem) => buttonItem.type) .toSet(); return SizedBox.shrink(key: toolbarKey); }, child: const Center( child: Text('How are you'), ), ), ), ); expect(buttonTypes.isEmpty, true); expect(find.byKey(toolbarKey), findsNothing); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton); final TestGesture primaryMouseButtonGesture = await tester.createGesture(kind: PointerDeviceKind.mouse); addTearDown(primaryMouseButtonGesture.removePointer); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pump(); // Selection is collapsed. expect(paragraph.selections.isEmpty, false); expect(paragraph.selections[0], const TextSelection.collapsed(offset: 2)); // Context menu toggled on. expect(buttonTypes.length, 1); expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); expect(find.byKey(toolbarKey), findsOneWidget); await gesture.down(textOffsetToPosition(paragraph, 6)); await tester.pump(); await gesture.up(); await tester.pump(); expect(paragraph.selections.isEmpty, false); expect(paragraph.selections[0], const TextSelection.collapsed(offset: 2)); // Context menu toggled off. Selection remains the same. expect(find.byKey(toolbarKey), findsNothing); await gesture.down(textOffsetToPosition(paragraph, 9)); await tester.pump(); expect(paragraph.selections.isEmpty, false); expect(paragraph.selections[0], const TextSelection.collapsed(offset: 9)); await gesture.up(); await tester.pump(); // Context menu toggled on. expect(buttonTypes.length, 1); expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); expect(find.byKey(toolbarKey), findsOneWidget); // Collapse selection. await primaryMouseButtonGesture.down(textOffsetToPosition(paragraph, 1)); await tester.pump(); await primaryMouseButtonGesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); // Selection is collapsed. expect(paragraph.selections.isEmpty, false); expect(paragraph.selections[0], const TextSelection.collapsed(offset: 1)); expect(find.byKey(toolbarKey), findsNothing); await primaryMouseButtonGesture.down(textOffsetToPosition(paragraph, 0)); await tester.pump(); await primaryMouseButtonGesture.moveTo(textOffsetToPosition(paragraph, 5)); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); await primaryMouseButtonGesture.up(); await tester.pump(); // Right click on previous selection should not collapse the selection. await gesture.down(textOffsetToPosition(paragraph, 2)); await tester.pump(); await gesture.up(); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); expect(find.byKey(toolbarKey), findsOneWidget); // Right click anywhere outside previous selection should first toggle the context // menu off. await gesture.down(textOffsetToPosition(paragraph, 7)); await tester.pump(); await gesture.up(); await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); expect(find.byKey(toolbarKey), findsNothing); // Right click again should collapse the selection and toggle the context // menu on. await gesture.down(textOffsetToPosition(paragraph, 7)); await tester.pump(); await gesture.up(); await tester.pump(); expect(paragraph.selections.isEmpty, false); expect(paragraph.selections[0], const TextSelection.collapsed(offset: 7)); expect(find.byKey(toolbarKey), findsOneWidget); // Collapse selection. await primaryMouseButtonGesture.down(textOffsetToPosition(paragraph, 1)); await tester.pump(); await primaryMouseButtonGesture.up(); await tester.pumpAndSettle(); // Selection is collapsed. expect(paragraph.selections.isEmpty, false); expect(paragraph.selections[0], const TextSelection.collapsed(offset: 1)); expect(find.byKey(toolbarKey), findsNothing); }, variant: TargetPlatformVariant.only(TargetPlatform.linux), skip: kIsWeb, // [intended] Web uses its native context menu. ); testWidgets('can copy a selection made with the mouse', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); // Select from offset 2 of paragraph 1 to offset 6 of paragraph3. final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); await gesture.up(); // keyboard copy. await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true)); final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; expect(clipboardData['text'], 'w are you?Good, and you?Fine, '); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia })); testWidgets( 'does not override TextField keyboard shortcuts if the TextField is focused - non apple', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(text: 'I am fine, thank you.'); addTearDown(controller.dispose); final FocusNode selectableRegionFocus = FocusNode(); addTearDown(selectableRegionFocus.dispose); final FocusNode textFieldFocus = FocusNode(); addTearDown(textFieldFocus.dispose); await tester.pumpWidget( MaterialApp( home: Material( child: SelectableRegion( focusNode: selectableRegionFocus, selectionControls: materialTextSelectionControls, child: Column( children: <Widget>[ const Text('How are you?'), const Text('Good, and you?'), TextField(controller: controller, focusNode: textFieldFocus), ], ), ), ), ), ); textFieldFocus.requestFocus(); await tester.pump(); // Make sure keyboard select all works on TextField. await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, control: true)); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 21)); // Make sure no selection in SelectableRegion. final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); expect(paragraph1.selections.isEmpty, isTrue); expect(paragraph2.selections.isEmpty, isTrue); // Focus selectable region. selectableRegionFocus.requestFocus(); await tester.pump(); // Reset controller selection once the TextField is unfocused. controller.selection = const TextSelection.collapsed(offset: -1); // Make sure keyboard select all will be handled by selectable region now. await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, control: true)); expect(controller.selection, const TextSelection.collapsed(offset: -1)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia }), skip: kIsWeb, // [intended] the web handles this on its own. ); testWidgets( 'does not override TextField keyboard shortcuts if the TextField is focused - apple', (WidgetTester tester) async { final TextEditingController controller = TextEditingController(text: 'I am fine, thank you.'); addTearDown(controller.dispose); final FocusNode selectableRegionFocus = FocusNode(); addTearDown(selectableRegionFocus.dispose); final FocusNode textFieldFocus = FocusNode(); addTearDown(textFieldFocus.dispose); await tester.pumpWidget( MaterialApp( home: Material( child: SelectableRegion( focusNode: selectableRegionFocus, selectionControls: materialTextSelectionControls, child: Column( children: <Widget>[ const Text('How are you?'), const Text('Good, and you?'), TextField(controller: controller, focusNode: textFieldFocus), ], ), ), ), ), ); textFieldFocus.requestFocus(); await tester.pump(); // Make sure keyboard select all works on TextField. await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, meta: true)); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 21)); // Make sure no selection in SelectableRegion. final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); expect(paragraph1.selections.isEmpty, isTrue); expect(paragraph2.selections.isEmpty, isTrue); // Focus selectable region. selectableRegionFocus.requestFocus(); await tester.pump(); // Reset controller selection once the TextField is unfocused. controller.selection = const TextSelection.collapsed(offset: -1); // Make sure keyboard select all will be handled by selectable region now. await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, meta: true)); expect(controller.selection, const TextSelection.collapsed(offset: -1)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), skip: kIsWeb, // [intended] the web handles this on its own. ); testWidgets('select all', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); await tester.pumpAndSettle(); focusNode.requestFocus(); // keyboard select all. await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, control: true)); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 16)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia })); testWidgets( 'mouse selection can handle widget span', (WidgetTester tester) async { final UniqueKey outerText = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Center( child: Text.rich( const TextSpan( children: <InlineSpan>[ TextSpan(text: 'How are you?'), WidgetSpan(child: Text('Good, and you?')), TextSpan(text: 'Fine, thank you.'), ], ), key: outerText, ), ), ), ), ); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph, 17)); // right after `Fine`. await gesture.up(); // keyboard copy. await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true)); final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; expect(clipboardData['text'], 'w are you?Good, and you?Fine'); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia }), skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 ); testWidgets( 'double click + drag mouse selection can handle widget span', (WidgetTester tester) async { final UniqueKey outerText = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Center( child: Text.rich( const TextSpan( children: <InlineSpan>[ TextSpan(text: 'How are you?'), WidgetSpan(child: Text('Good, and you?')), TextSpan(text: 'Fine, thank you.'), ], ), key: outerText, ), ), ), ), ); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 0), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pump(); await gesture.down(textOffsetToPosition(paragraph, 0)); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph, 17)); // right after `Fine`. await gesture.up(); // keyboard copy. await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true)); final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; expect(clipboardData['text'], 'How are you?Good, and you?Fine,'); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia }), skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 ); testWidgets( 'double click + drag mouse selection can handle widget span - multiline', (WidgetTester tester) async { final UniqueKey outerText = UniqueKey(); final UniqueKey innerText = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Center( child: Text.rich( TextSpan( children: <InlineSpan>[ const TextSpan(text: 'How are you\n?'), WidgetSpan( child: Text( 'Good, and you?', key: innerText, ), ), const TextSpan(text: 'Fine, thank you.'), ], ), key: outerText, ), ), ), ), ); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); final RenderParagraph innerParagraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(innerText), matching: find.byType(RichText)).first); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 0), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pump(); await gesture.down(textOffsetToPosition(paragraph, 0)); await tester.pump(); await gesture.moveTo(textOffsetToPosition(innerParagraph, 2)); // on `Good`. // Should not crash. expect(tester.takeException(), isNull); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia }), skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 ); testWidgets( 'select word event can select inline widget', (WidgetTester tester) async { final UniqueKey outerText = UniqueKey(); final UniqueKey innerText = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Center( child: Text.rich( TextSpan( children: <InlineSpan>[ const TextSpan(text: 'How are\n you?'), WidgetSpan( child: Text( 'Good, and you?', key: innerText, ), ), const TextSpan(text: 'Fine, thank you.'), ], ), key: outerText, ), ), ), ), ); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); final RenderParagraph innerParagraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(innerText), matching: find.byType(RichText)).first); final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(innerText)), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pump(); // Should select "and". expect(paragraph.selections.isEmpty, isTrue); expect(innerParagraph.selections[0], const TextSelection(baseOffset: 6, extentOffset: 9)); }, variant: TargetPlatformVariant.only(TargetPlatform.macOS), skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 ); testWidgets( 'select word event should not crash when its position is at an unselectable inline element', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); final UniqueKey flutterLogo = UniqueKey(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Scaffold( body: Center( child: Text.rich( TextSpan( children: <InlineSpan>[ const TextSpan( text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', ), WidgetSpan(child: FlutterLogo(key: flutterLogo)), const TextSpan(text: 'Hello, world.'), ], ), ), ), ), ), ), ); final Offset gestureOffset = tester.getCenter(find.byKey(flutterLogo).first); // Right click on unselectable element. final TestGesture gesture = await tester.startGesture(gestureOffset, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pump(); // Should not crash. expect(tester.takeException(), isNull); }, variant: TargetPlatformVariant.only(TargetPlatform.macOS), skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 ); testWidgets( 'can select word when a selectables rect is completely inside of another selectables rect', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/127076. final UniqueKey outerText = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Scaffold( body: Center( child: Text.rich( const TextSpan( children: <InlineSpan>[ TextSpan( text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', ), WidgetSpan(child: Text('Some text in a WidgetSpan. ')), TextSpan(text: 'Hello, world.'), ], ), key: outerText, ), ), ), ), ), ); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); // Adjust `textOffsetToPosition` result because it returns the wrong vertical position (wrong line). // TODO(bleroux): Remove when https://github.com/flutter/flutter/issues/133637 is fixed. final Offset gestureOffset = textOffsetToPosition(paragraph, 125).translate(0, 10); // Right click to select word at position. final TestGesture gesture = await tester.startGesture(gestureOffset, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pump(); // Should select "Hello". expect(paragraph.selections[0], const TextSelection(baseOffset: 124, extentOffset: 129)); }, variant: TargetPlatformVariant.only(TargetPlatform.macOS), skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 ); testWidgets( 'can select word when selectable is broken up by an unselectable WidgetSpan', (WidgetTester tester) async { final UniqueKey outerText = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Scaffold( body: Center( child: Text.rich( const TextSpan( children: <InlineSpan>[ TextSpan( text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', ), WidgetSpan(child: SizedBox.shrink()), TextSpan(text: 'Hello, world.'), ], ), key: outerText, ), ), ), ), ), ); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); // Adjust `textOffsetToPosition` result because it returns the wrong vertical position (wrong line). // TODO(bleroux): Remove when https://github.com/flutter/flutter/issues/133637 is fixed. final Offset gestureOffset = textOffsetToPosition(paragraph, 125).translate(0, 10); // Right click to select word at position. final TestGesture gesture = await tester.startGesture(gestureOffset, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pump(); // Should select "Hello". expect(paragraph.selections[0], const TextSelection(baseOffset: 124, extentOffset: 129)); }, variant: TargetPlatformVariant.only(TargetPlatform.macOS), skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 ); testWidgets( 'widget span is ignored if it does not contain text - non Apple', (WidgetTester tester) async { final UniqueKey outerText = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Center( child: Text.rich( const TextSpan( children: <InlineSpan>[ TextSpan(text: 'How are you?'), WidgetSpan(child: Placeholder()), TextSpan(text: 'Fine, thank you.'), ], ), key: outerText, ), ), ), ), ); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph, 17)); // right after `Fine`. await gesture.up(); // keyboard copy. await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true)); final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; expect(clipboardData['text'], 'w are you?Fine'); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia }), skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 ); testWidgets( 'widget span is ignored if it does not contain text - Apple', (WidgetTester tester) async { final UniqueKey outerText = UniqueKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Center( child: Text.rich( const TextSpan( children: <InlineSpan>[ TextSpan(text: 'How are you?'), WidgetSpan(child: Placeholder()), TextSpan(text: 'Fine, thank you.'), ], ), key: outerText, ), ), ), ), ); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph, 17)); // right after `Fine`. await gesture.up(); // keyboard copy. await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, meta: true)); final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; expect(clipboardData['text'], 'w are you?Fine'); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 ); testWidgets('mouse can select across bidi text', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('جيد وانت؟', textDirection: TextDirection.rtl), Text('Fine, thank you.'), ], ), ), ), ); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); await tester.pump(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4)); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('جيد وانت؟'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); // Should select the rest of paragraph 1. expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); // Add a little offset to cross the boundary between paragraph 2 and 3. await gesture.moveTo(textOffsetToPosition(paragraph3, 6) + const Offset(0, 1)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 9)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); await gesture.up(); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/61020 testWidgets('long press and drag touch moves selection word by word', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); await tester.pumpAndSettle(); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 6)); // at the 'r' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); // `are` is selected. expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph2, 7)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 12)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 9)); await gesture.up(); }); testWidgets('can drag end handle when not covering entire screen', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/104620. final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: Column( children: <Widget>[ const Text('How are you?'), SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text('Good, and you?'), ), const Text('Fine, thank you.'), ], ), ), ); await tester.pumpAndSettle(); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph2, 7)); // at the 'a' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); await tester.pump(const Duration(milliseconds: 500)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 6, extentOffset: 9)); final List<TextBox> boxes = paragraph2.getBoxesForSelection(paragraph2.selections[0]); expect(boxes.length, 1); final Offset handlePos = globalize(boxes[0].toRect().bottomRight, paragraph2); await gesture.down(handlePos); await gesture.moveTo(textOffsetToPosition(paragraph2, 11) + Offset(0, paragraph2.size.height / 2)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11)); await gesture.up(); }); testWidgets('can drag start handle when not covering entire screen', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/104620. final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: Column( children: <Widget>[ const Text('How are you?'), SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text('Good, and you?'), ), const Text('Fine, thank you.'), ], ), ), ); await tester.pumpAndSettle(); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph2, 7)); // at the 'a' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); await tester.pump(const Duration(milliseconds: 500)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 6, extentOffset: 9)); final List<TextBox> boxes = paragraph2.getBoxesForSelection(paragraph2.selections[0]); expect(boxes.length, 1); final Offset handlePos = globalize(boxes[0].toRect().bottomLeft, paragraph2); await gesture.down(handlePos); await gesture.moveTo(textOffsetToPosition(paragraph2, 11) + Offset(0, paragraph2.size.height / 2)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 11, extentOffset: 9)); await gesture.up(); }); testWidgets('can drag start selection handle', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); await tester.pumpAndSettle(); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 7)); // at the 'h' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); await tester.pump(const Duration(milliseconds: 500)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11)); final List<TextBox> boxes = paragraph3.getBoxesForSelection(paragraph3.selections[0]); expect(boxes.length, 1); final Offset handlePos = globalize(boxes[0].toRect().bottomLeft, paragraph3); await gesture.down(handlePos); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph2, 5) + Offset(0, paragraph2.size.height / 2)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 5, extentOffset: 14)); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph1, 6) + Offset(0, paragraph1.size.height / 2)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 6, extentOffset: 12)); await gesture.up(); }); testWidgets('can drag start selection handle across end selection handle', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); await tester.pumpAndSettle(); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 7)); // at the 'h' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); await tester.pump(const Duration(milliseconds: 500)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11)); final List<TextBox> boxes = paragraph3.getBoxesForSelection(paragraph3.selections[0]); expect(boxes.length, 1); final Offset handlePos = globalize(boxes[0].toRect().bottomLeft, paragraph3); await gesture.down(handlePos); await gesture.moveTo(textOffsetToPosition(paragraph3, 14) + Offset(0, paragraph3.size.height / 2)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 14, extentOffset: 11)); await gesture.moveTo(textOffsetToPosition(paragraph3, 4) + Offset(0, paragraph3.size.height / 2)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 4, extentOffset: 11)); await gesture.up(); }); testWidgets('can drag end selection handle across start selection handle', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); await tester.pumpAndSettle(); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 7)); // at the 'h' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); await tester.pump(const Duration(milliseconds: 500)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11)); final List<TextBox> boxes = paragraph3.getBoxesForSelection(paragraph3.selections[0]); expect(boxes.length, 1); final Offset handlePos = globalize(boxes[0].toRect().bottomRight, paragraph3); await gesture.down(handlePos); await gesture.moveTo(textOffsetToPosition(paragraph3, 4) + Offset(0, paragraph3.size.height / 2)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 4)); await gesture.moveTo(textOffsetToPosition(paragraph3, 12) + Offset(0, paragraph3.size.height / 2)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 12)); await gesture.up(); }); testWidgets('can select all from toolbar', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); await tester.pumpAndSettle(); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 7)); // at the 'h' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); await tester.pump(const Duration(milliseconds: 500)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11)); expect(find.text('Select all'), findsOneWidget); await tester.tap(find.text('Select all')); await tester.pump(); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 16)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); }, skip: kIsWeb); // [intended] Web uses its native context menu. testWidgets('can copy from toolbar', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); await tester.pumpAndSettle(); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 7)); // at the 'h' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); await tester.pump(const Duration(milliseconds: 500)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11)); expect(find.text('Copy'), findsOneWidget); await tester.tap(find.text('Copy')); await tester.pump(); // Selection should be cleared. final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); expect(paragraph3.selections.isEmpty, isTrue); expect(paragraph2.selections.isEmpty, isTrue); expect(paragraph1.selections.isEmpty, isTrue); final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; expect(clipboardData['text'], 'thank'); }, skip: kIsWeb); // [intended] Web uses its native context menu. testWidgets('can use keyboard to granularly extend selection - character', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); // Select from offset 2 of paragraph1 to offset 6 of paragraph1. final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); await gesture.up(); await tester.pump(); // Ho[w ar]e you? // Good, and you? // Fine, thank you. expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 6); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true)); await tester.pump(); // Ho[w are] you? // Good, and you? // Fine, thank you. expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 7); for (int i = 0; i < 5; i += 1) { await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true)); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 8 + i); } for (int i = 0; i < 5; i += 1) { await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true)); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 11 - i); } }, variant: TargetPlatformVariant.all()); testWidgets('can use keyboard to granularly extend selection - word', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); // Select from offset 2 of paragraph1 to offset 6 of paragraph1. final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); await gesture.up(); await tester.pump(); final bool alt; final bool control; switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: alt = false; control = true; case TargetPlatform.iOS: case TargetPlatform.macOS: alt = true; control = false; } // Ho[w ar]e you? // Good, and you? // Fine, thank you. expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 6); await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, control: control)); await tester.pump(); // Ho[w are] you? // Good, and you? // Fine, thank you. expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 7); await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, control: control)); await tester.pump(); // Ho[w are you]? // Good, and you? // Fine, thank you. expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 11); await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, control: control)); await tester.pump(); // Ho[w are you?] // Good, and you? // Fine, thank you. expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 12); await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, control: control)); await tester.pump(); // Ho[w are you? // Good], and you? // Fine, thank you. final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 12); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 4); await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: alt, control: control)); await tester.pump(); // Ho[w are you? // ]Good, and you? // Fine, thank you. expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 12); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 0); await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: alt, control: control)); await tester.pump(); // Ho[w are ]you? // Good, and you? // Fine, thank you. expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 8); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 0); }, variant: TargetPlatformVariant.all()); testWidgets('can use keyboard to granularly extend selection - line', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); // Select from offset 2 of paragraph1 to offset 6 of paragraph1. final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); await gesture.up(); await tester.pump(); final bool alt; final bool meta; switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: meta = false; alt = true; case TargetPlatform.iOS: case TargetPlatform.macOS: meta = true; alt = false; } // Ho[w ar]e you? // Good, and you? // Fine, thank you. expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 6); await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, meta: meta)); await tester.pump(); // Ho[w are you?] // Good, and you? // Fine, thank you. expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 12); await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, meta: meta)); await tester.pump(); // Ho[w are you? // Good, and you?] // Fine, thank you. final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 12); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 14); await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: alt, meta: meta)); await tester.pump(); // Ho[w are you?] // Good, and you? // Fine, thank you. expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 12); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 0); await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: alt, meta: meta)); await tester.pump(); // [Ho]w are you? // Good, and you? // Fine, thank you. expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 0); expect(paragraph1.selections[0].end, 2); }, variant: TargetPlatformVariant.all()); testWidgets('can use keyboard to granularly extend selection - document', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); // Select from offset 2 of paragraph1 to offset 6 of paragraph1. final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); await gesture.up(); await tester.pump(); final bool alt; final bool meta; switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: meta = false; alt = true; case TargetPlatform.iOS: case TargetPlatform.macOS: meta = true; alt = false; } // Ho[w ar]e you? // Good, and you? // Fine, thank you. expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 6); await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, meta: meta, alt: alt)); await tester.pump(); // Ho[w are you? // Good, and you? // Fine, thank you.] final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 12); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 14); expect(paragraph3.selections.length, 1); expect(paragraph3.selections[0].start, 0); expect(paragraph3.selections[0].end, 16); await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, meta: meta, alt: alt)); await tester.pump(); // [Ho]w are you? // Good, and you? // Fine, thank you. expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 0); expect(paragraph1.selections[0].end, 2); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 0); expect(paragraph3.selections.length, 1); expect(paragraph3.selections[0].start, 0); expect(paragraph3.selections[0].end, 0); }, variant: TargetPlatformVariant.all()); testWidgets('can use keyboard to directionally extend selection', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); // Select from offset 2 of paragraph2 to offset 6 of paragraph2. final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph2, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph2, 6)); await gesture.up(); await tester.pump(); // How are you? // Go[od, ]and you? // Fine, thank you. expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 2); expect(paragraph2.selections[0].end, 6); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); await tester.pump(); // How are you? // Go[od, and you? // Fine, t]hank you. final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 2); expect(paragraph2.selections[0].end, 14); expect(paragraph3.selections.length, 1); expect(paragraph3.selections[0].start, 0); expect(paragraph3.selections[0].end, 7); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); await tester.pump(); // How are you? // Go[od, and you? // Fine, thank you.] expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 2); expect(paragraph2.selections[0].end, 14); expect(paragraph3.selections.length, 1); expect(paragraph3.selections[0].start, 0); expect(paragraph3.selections[0].end, 16); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); await tester.pump(); // How are you? // Go[od, ]and you? // Fine, thank you. expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 2); expect(paragraph2.selections[0].end, 6); expect(paragraph3.selections.length, 1); expect(paragraph3.selections[0].start, 0); expect(paragraph3.selections[0].end, 0); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); await tester.pump(); // How a[re you? // Go]od, and you? // Fine, thank you. final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 5); expect(paragraph1.selections[0].end, 12); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 2); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); await tester.pump(); // [How are you? // Go]od, and you? // Fine, thank you. expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 0); expect(paragraph1.selections[0].end, 12); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 2); }, variant: TargetPlatformVariant.all()); group('magnifier', () { late ValueNotifier<MagnifierInfo> magnifierInfo; final Widget fakeMagnifier = Container(key: UniqueKey()); testWidgets('Can drag handles to show, unshow, and update magnifier', (WidgetTester tester) async { const String text = 'Monkeys and rabbits in my soup'; final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( magnifierConfiguration: TextMagnifierConfiguration( magnifierBuilder: (_, MagnifierController controller, ValueNotifier<MagnifierInfo> localMagnifierInfo) { magnifierInfo = localMagnifierInfo; return fakeMagnifier; }, ), focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text(text), ), ), ); await tester.pumpAndSettle(); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( find.descendant( of: find.text(text), matching: find.byType(RichText))); // Show the selection handles. final TestGesture activateSelectionGesture = await tester .startGesture(textOffsetToPosition(paragraph, text.length ~/ 2)); addTearDown(activateSelectionGesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await activateSelectionGesture.up(); await tester.pump(const Duration(milliseconds: 500)); // Drag the handle around so that the magnifier shows. final TextBox selectionBox = paragraph.getBoxesForSelection(paragraph.selections.first).first; final Offset leftHandlePos = globalize(selectionBox.toRect().bottomLeft, paragraph); final TestGesture gesture = await tester.startGesture(leftHandlePos); await gesture.moveTo(textOffsetToPosition(paragraph, text.length - 2)); await tester.pump(); // Expect the magnifier to show and then store it's position. expect(find.byKey(fakeMagnifier.key!), findsOneWidget); final Offset firstDragGesturePosition = magnifierInfo.value.globalGesturePosition; await gesture.moveTo(textOffsetToPosition(paragraph, text.length)); await tester.pump(); // Expect the position the magnifier gets to have moved. expect(firstDragGesturePosition, isNot(magnifierInfo.value.globalGesturePosition)); // Lift the pointer and expect the magnifier to disappear. await gesture.up(); await tester.pump(); expect(find.byKey(fakeMagnifier.key!), findsNothing); }); }); }); testWidgets('toolbar is hidden on Android and iOS when orientation changes', (WidgetTester tester) async { addTearDown(tester.view.reset); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text('How are you?'), ), ), ); await tester.pumpAndSettle(); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 6)); // at the 'r' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); // `are` is selected. expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle(); // Text selection toolbar has appeared. expect(find.text('Copy'), findsOneWidget); // Hide the toolbar by changing orientation. tester.view.physicalSize = const Size(1800.0, 2400.0); await tester.pumpAndSettle(); expect(find.text('Copy'), findsNothing); // Handles should be hidden as well on Android expect( find.descendant( of: find.byType(CompositedTransformFollower), matching: find.byType(Padding), ), defaultTargetPlatform == TargetPlatform.android ? findsNothing : findsNWidgets(2), ); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android }), skip: kIsWeb, // [intended] Web uses its native context menu. ); testWidgets('the selection behavior when clicking `Copy` item in mobile platforms', (WidgetTester tester) async { List<ContextMenuButtonItem> buttonItems = <ContextMenuButtonItem>[]; final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { buttonItems = selectableRegionState.contextMenuButtonItems; return const SizedBox.shrink(); }, child: const Text('How are you?'), ), ), ); await tester.pumpAndSettle(); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); await tester.longPressAt(textOffsetToPosition(paragraph1, 6)); // at the 'r' await tester.pump(kLongPressTimeout); // `are` is selected. expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); // Press `Copy` item. expect(buttonItems[0].type, ContextMenuButtonType.copy); buttonItems[0].onPressed?.call(); final SelectableRegionState regionState = tester.state<SelectableRegionState>(find.byType(SelectableRegion)); // In Android copy should clear the selection. switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: expect(regionState.selectionOverlay, isNull); expect(regionState.selectionOverlay?.startHandleLayerLink, isNull); expect(regionState.selectionOverlay?.endHandleLayerLink, isNull); case TargetPlatform.iOS: expect(regionState.selectionOverlay, isNotNull); expect(regionState.selectionOverlay?.startHandleLayerLink, isNotNull); expect(regionState.selectionOverlay?.endHandleLayerLink, isNotNull); case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: // Test doesn't run these platforms. break; } }, variant: TargetPlatformVariant.mobile(), skip: kIsWeb, // [intended] Web uses its native context menu. ); testWidgets('the handles do not disappear when clicking `Select all` item in mobile platforms', (WidgetTester tester) async { List<ContextMenuButtonItem> buttonItems = <ContextMenuButtonItem>[]; final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { buttonItems = selectableRegionState.contextMenuButtonItems; return const SizedBox.shrink(); }, child: const Text('How are you?'), ), ), ); await tester.pumpAndSettle(); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); await tester.longPressAt(textOffsetToPosition(paragraph1, 6)); // at the 'r' await tester.pump(kLongPressTimeout); // `are` is selected. expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); late ContextMenuButtonItem selectAllButton; switch (defaultTargetPlatform) { case TargetPlatform.android: // On Android, the select all button is after the share button. expect(buttonItems[2].type, ContextMenuButtonType.selectAll); selectAllButton = buttonItems[2]; case TargetPlatform.iOS: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: expect(buttonItems[1].type, ContextMenuButtonType.selectAll); selectAllButton = buttonItems[1]; } // Press `Select All` item. selectAllButton.onPressed?.call(); final SelectableRegionState regionState = tester.state<SelectableRegionState>(find.byType(SelectableRegion)); switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.iOS: case TargetPlatform.fuchsia: expect(regionState.selectionOverlay, isNotNull); expect(regionState.selectionOverlay?.startHandleLayerLink, isNotNull); expect(regionState.selectionOverlay?.endHandleLayerLink, isNotNull); case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: // Test doesn't run these platforms. break; } }, variant: TargetPlatformVariant.mobile(), skip: kIsWeb, // [intended] Web uses its native context menu. ); testWidgets('Selection behavior when clicking the `Share` button on Android', (WidgetTester tester) async { List<ContextMenuButtonItem> buttonItems = <ContextMenuButtonItem>[]; final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { buttonItems = selectableRegionState.contextMenuButtonItems; return const SizedBox.shrink(); }, child: const Text('How are you?'), ), ), ); await tester.pumpAndSettle(); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( find.descendant( of: find.text('How are you?'), matching: find.byType(RichText), ), ); await tester.longPressAt(textOffsetToPosition(paragraph, 6)); // at the 'r' await tester.pump(kLongPressTimeout); // `are` is selected. expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); String? lastShare; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { if (methodCall.method == 'Share.invoke') { expect(methodCall.arguments, isA<String>()); lastShare = methodCall.arguments as String; } return null; }); addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null)); final SelectableRegionState regionState = tester.state<SelectableRegionState>(find.byType(SelectableRegion)); // Press the `Share` button. expect(buttonItems[1].type, ContextMenuButtonType.share); buttonItems[1].onPressed?.call(); expect(lastShare, 'are'); // On Android, share should clear the selection. expect(regionState.selectionOverlay, isNull); expect(regionState.selectionOverlay?.startHandleLayerLink, isNull); expect(regionState.selectionOverlay?.endHandleLayerLink, isNull); }, skip: kIsWeb, // [intended] Web uses its native context menu. ); testWidgets('builds the correct button items', (WidgetTester tester) async { List<ContextMenuButtonItem> buttonItems = <ContextMenuButtonItem>[]; final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { buttonItems = selectableRegionState.contextMenuButtonItems; return const SizedBox.shrink(); }, child: const Text('How are you?'), ), ), ); await tester.pumpAndSettle(); expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( find.descendant( of: find.text('How are you?'), matching: find.byType(RichText), ), ); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 6)); // at the 'r' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); // `are` is selected. expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); await gesture.up(); await tester.pumpAndSettle(); switch (defaultTargetPlatform) { case TargetPlatform.android: // On Android, the share button is before the select all button. expect(buttonItems.length, 3); expect(buttonItems[0].type, ContextMenuButtonType.copy); expect(buttonItems[1].type, ContextMenuButtonType.share); expect(buttonItems[2].type, ContextMenuButtonType.selectAll); case TargetPlatform.iOS: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: expect(buttonItems.length, 2); expect(buttonItems[0].type, ContextMenuButtonType.copy); expect(buttonItems[1].type, ContextMenuButtonType.selectAll); } }, variant: TargetPlatformVariant.all(), skip: kIsWeb, // [intended] Web uses its native context menu. ); testWidgets('Text processing actions are added to the toolbar', (WidgetTester tester) async { final MockProcessTextHandler mockProcessTextHandler = MockProcessTextHandler(); TestWidgetsFlutterBinding.ensureInitialized().defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.processText, mockProcessTextHandler.handleMethodCall); addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.processText, null)); Set<String?> buttonLabels = <String?>{}; final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { buttonLabels = selectableRegionState.contextMenuButtonItems .map((ContextMenuButtonItem buttonItem) => buttonItem.label) .toSet(); return const SizedBox.shrink(); }, child: const Text('How are you?'), ), ), ); await tester.pumpAndSettle(); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( find.descendant( of: find.text('How are you?'), matching: find.byType(RichText), ), ); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 6)); // at the 'r' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); // `are` is selected. expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); await gesture.up(); await tester.pumpAndSettle(); // The text processing actions are available on Android only. final bool areTextActionsSupported = defaultTargetPlatform == TargetPlatform.android; expect(buttonLabels.contains(fakeAction1Label), areTextActionsSupported); expect(buttonLabels.contains(fakeAction2Label), areTextActionsSupported); }, variant: TargetPlatformVariant.all(), skip: kIsWeb, // [intended] Web uses its native context menu. ); testWidgets('onSelectionChange is called when the selection changes through gestures', (WidgetTester tester) async { SelectedContent? content; final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( onSelectionChanged: (SelectedContent? selectedContent) => content = selectedContent, focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Center( child: Text('How are you'), ), ), ), ); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); final TestGesture mouseGesture = await tester.startGesture(textOffsetToPosition(paragraph, 4), kind: PointerDeviceKind.mouse); final TestGesture touchGesture = await tester.createGesture(); expect(content, isNull); addTearDown(mouseGesture.removePointer); addTearDown(touchGesture.removePointer); await tester.pump(); // Called on drag. await mouseGesture.moveTo(textOffsetToPosition(paragraph, 7)); await tester.pumpAndSettle(); expect(content, isNotNull); expect(content!.plainText, 'are'); // Updates on drag. await mouseGesture.moveTo(textOffsetToPosition(paragraph, 10)); await tester.pumpAndSettle(); expect(content, isNotNull); expect(content!.plainText, 'are yo'); // Called on drag end. await mouseGesture.up(); await tester.pump(); expect(content, isNotNull); expect(content!.plainText, 'are yo'); // Backwards selection. await mouseGesture.down(textOffsetToPosition(paragraph, 3)); await tester.pump(); await mouseGesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(content, isNotNull); expect(content!.plainText, ''); await mouseGesture.down(textOffsetToPosition(paragraph, 3)); await tester.pump(); await mouseGesture.moveTo(textOffsetToPosition(paragraph, 0)); await tester.pumpAndSettle(); expect(content, isNotNull); expect(content!.plainText, 'How'); await mouseGesture.up(); await tester.pump(); expect(content, isNotNull); expect(content!.plainText, 'How'); // Called on double tap. await mouseGesture.down(textOffsetToPosition(paragraph, 6)); await tester.pump(); await mouseGesture.up(); await tester.pump(); await mouseGesture.down(textOffsetToPosition(paragraph, 6)); await tester.pumpAndSettle(); expect(content, isNotNull); expect(content!.plainText, 'are'); await mouseGesture.up(); await tester.pumpAndSettle(); // Called on tap. await mouseGesture.down(textOffsetToPosition(paragraph, 0)); await tester.pumpAndSettle(); await mouseGesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(content, isNotNull); expect(content!.plainText, ''); // With touch gestures. // Called on long press start. await touchGesture.down(textOffsetToPosition(paragraph, 0)); await tester.pumpAndSettle(kLongPressTimeout); expect(content, isNotNull); expect(content!.plainText, 'How'); // Called on long press update. await touchGesture.moveTo(textOffsetToPosition(paragraph, 5)); await tester.pumpAndSettle(); expect(content, isNotNull); expect(content!.plainText, 'How are'); // Called on long press end. await touchGesture.up(); await tester.pumpAndSettle(); expect(content, isNotNull); expect(content!.plainText, 'How are'); // Long press to select 'you'. await touchGesture.down(textOffsetToPosition(paragraph, 9)); await tester.pumpAndSettle(kLongPressTimeout); expect(content, isNotNull); expect(content!.plainText, 'you'); await touchGesture.up(); await tester.pumpAndSettle(); // Called while moving selection handles. final List<TextBox> boxes = paragraph.getBoxesForSelection(paragraph.selections[0]); expect(boxes.length, 1); final Offset startHandlePos = globalize(boxes[0].toRect().bottomLeft, paragraph); final Offset endHandlePos = globalize(boxes[0].toRect().bottomRight, paragraph); final Offset startPos = Offset(textOffsetToPosition(paragraph, 4).dx, startHandlePos.dy); final Offset endPos = Offset(textOffsetToPosition(paragraph, 6).dx, endHandlePos.dy); // Start handle. await touchGesture.down(startHandlePos); await touchGesture.moveTo(startPos); await tester.pumpAndSettle(); expect(content, isNotNull); expect(content!.plainText, 'are you'); await touchGesture.up(); await tester.pumpAndSettle(); // End handle. await touchGesture.down(endHandlePos); await touchGesture.moveTo(endPos); await tester.pumpAndSettle(); expect(content, isNotNull); expect(content!.plainText, 'ar'); await touchGesture.up(); await tester.pumpAndSettle(); }); testWidgets('onSelectionChange is called when the selection changes through keyboard actions', (WidgetTester tester) async { SelectedContent? content; final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( onSelectionChanged: (SelectedContent? selectedContent) => content = selectedContent, focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ Text('How are you?'), Text('Good, and you?'), Text('Fine, thank you.'), ], ), ), ), ); expect(content, isNull); await tester.pump(); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); await gesture.up(); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 6); expect(content, isNotNull); expect(content!.plainText, 'w ar'); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true)); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 7); expect(content, isNotNull); expect(content!.plainText, 'w are'); for (int i = 0; i < 5; i += 1) { await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true)); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 8 + i); expect(content, isNotNull); } expect(content, isNotNull); expect(content!.plainText, 'w are you?'); for (int i = 0; i < 5; i += 1) { await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true)); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 11 - i); expect(content, isNotNull); } expect(content, isNotNull); expect(content!.plainText, 'w are'); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 12); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 8); expect(content, isNotNull); expect(content!.plainText, 'w are you?Good, an'); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 12); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 14); expect(paragraph3.selections.length, 1); expect(paragraph3.selections[0].start, 0); expect(paragraph3.selections[0].end, 9); expect(content, isNotNull); expect(content!.plainText, 'w are you?Good, and you?Fine, tha'); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 12); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 14); expect(paragraph3.selections.length, 1); expect(paragraph3.selections[0].start, 0); expect(paragraph3.selections[0].end, 16); expect(content, isNotNull); expect(content!.plainText, 'w are you?Good, and you?Fine, thank you.'); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 12); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 8); expect(paragraph3.selections.length, 1); expect(content, isNotNull); expect(content!.plainText, 'w are you?Good, an'); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 7); expect(paragraph2.selections.length, 1); expect(paragraph3.selections.length, 1); expect(content, isNotNull); expect(content!.plainText, 'w are'); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 0); expect(paragraph1.selections[0].end, 2); expect(paragraph2.selections.length, 1); expect(paragraph3.selections.length, 1); expect(content, isNotNull); expect(content!.plainText, 'Ho'); }); group('BrowserContextMenu', () { setUp(() async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.contextMenu, (MethodCall call) { // Just complete successfully, so that BrowserContextMenu thinks that // the engine successfully received its call. return Future<void>.value(); }); await BrowserContextMenu.disableContextMenu(); }); tearDown(() async { await BrowserContextMenu.enableContextMenu(); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.contextMenu, null); }); testWidgets('web can show flutter context menu when the browser context menu is disabled', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( onSelectionChanged: (SelectedContent? selectedContent) {}, focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Center( child: Text('How are you'), ), ), ), ); await tester.pumpAndSettle(); final SelectableRegionState state = tester.state<SelectableRegionState>(find.byType(SelectableRegion)); expect(find.text('Copy'), findsNothing); state.selectAll(SelectionChangedCause.toolbar); await tester.pumpAndSettle(); expect(find.text('Copy'), findsOneWidget); state.hideToolbar(); await tester.pumpAndSettle(); expect(find.text('Copy'), findsNothing); }, skip: !kIsWeb, // [intended] ); }); testWidgets('Multiple selectables on a single line should be in screen order', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/127942. final UniqueKey outerText = UniqueKey(); const TextStyle textStyle = TextStyle(fontSize: 10); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Scaffold( body: Center( child: Text.rich( const TextSpan( children: <InlineSpan>[ TextSpan(text: 'Hello my name is ', style: textStyle), WidgetSpan( child: Text('Dash', style: textStyle), alignment: PlaceholderAlignment.middle, ), TextSpan(text: '.', style: textStyle), ], ), key: outerText, ), ), ), ), ), ); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 0), kind: PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); // Select all. await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, control: true)); // keyboard copy. await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true)); final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; expect(clipboardData['text'], 'Hello my name is Dash.'); }); } class SelectionSpy extends LeafRenderObjectWidget { const SelectionSpy({ super.key, }); @override RenderObject createRenderObject(BuildContext context) { return RenderSelectionSpy( SelectionContainer.maybeOf(context), ); } @override void updateRenderObject(BuildContext context, covariant RenderObject renderObject) { } } class RenderSelectionSpy extends RenderProxyBox with Selectable, SelectionRegistrant { RenderSelectionSpy( SelectionRegistrar? registrar, ) { this.registrar = registrar; } final Set<VoidCallback> listeners = <VoidCallback>{}; List<SelectionEvent> events = <SelectionEvent>[]; @override Size get size => _size; Size _size = Size.zero; @override List<Rect> get boundingBoxes => <Rect>[paintBounds]; @override Size computeDryLayout(BoxConstraints constraints) { _size = Size(constraints.maxWidth, constraints.maxHeight); return _size; } @override void addListener(VoidCallback listener) => listeners.add(listener); @override void removeListener(VoidCallback listener) => listeners.remove(listener); @override SelectionResult dispatchSelectionEvent(SelectionEvent event) { events.add(event); return SelectionResult.end; } @override SelectedContent? getSelectedContent() { return const SelectedContent(plainText: 'content'); } @override final SelectionGeometry value = const SelectionGeometry( hasContent: true, status: SelectionStatus.uncollapsed, startSelectionPoint: SelectionPoint( localPosition: Offset.zero, lineHeight: 0.0, handleType: TextSelectionHandleType.left, ), endSelectionPoint: SelectionPoint( localPosition: Offset.zero, lineHeight: 0.0, handleType: TextSelectionHandleType.left, ), ); @override void pushHandleLayers(LayerLink? startHandle, LayerLink? endHandle) { } } class SelectAllWidget extends SingleChildRenderObjectWidget { const SelectAllWidget({ super.key, super.child, }); @override RenderObject createRenderObject(BuildContext context) { return RenderSelectAll( SelectionContainer.maybeOf(context), ); } @override void updateRenderObject(BuildContext context, covariant RenderObject renderObject) { } } class RenderSelectAll extends RenderProxyBox with Selectable, SelectionRegistrant { RenderSelectAll( SelectionRegistrar? registrar, ) { this.registrar = registrar; } @override List<Rect> get boundingBoxes => <Rect>[paintBounds]; final Set<VoidCallback> listeners = <VoidCallback>{}; LayerLink? startHandle; LayerLink? endHandle; @override void addListener(VoidCallback listener) => listeners.add(listener); @override void removeListener(VoidCallback listener) => listeners.remove(listener); @override SelectionResult dispatchSelectionEvent(SelectionEvent event) { value = SelectionGeometry( hasContent: true, status: SelectionStatus.uncollapsed, startSelectionPoint: SelectionPoint( localPosition: Offset(0, size.height), lineHeight: 0.0, handleType: TextSelectionHandleType.left, ), endSelectionPoint: SelectionPoint( localPosition: Offset(size.width, size.height), lineHeight: 0.0, handleType: TextSelectionHandleType.left, ), ); return SelectionResult.end; } @override SelectedContent? getSelectedContent() { return const SelectedContent(plainText: 'content'); } @override SelectionGeometry get value => _value; SelectionGeometry _value = const SelectionGeometry( hasContent: true, status: SelectionStatus.uncollapsed, startSelectionPoint: SelectionPoint( localPosition: Offset.zero, lineHeight: 0.0, handleType: TextSelectionHandleType.left, ), endSelectionPoint: SelectionPoint( localPosition: Offset.zero, lineHeight: 0.0, handleType: TextSelectionHandleType.left, ), ); set value(SelectionGeometry other) { if (other == _value) { return; } _value = other; for (final VoidCallback callback in listeners) { callback(); } } @override void pushHandleLayers(LayerLink? startHandle, LayerLink? endHandle) { this.startHandle = startHandle; this.endHandle = endHandle; } }
flutter/packages/flutter/test/widgets/selectable_region_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/selectable_region_test.dart", "repo_id": "flutter", "token_count": 69182 }
704
// 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 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('SemanticsDebugger will schedule a frame', (WidgetTester tester) async { await tester.pumpWidget( SemanticsDebugger( child: Container(), ), ); expect(tester.binding.hasScheduledFrame, isTrue); }); testWidgets('SemanticsDebugger smoke test', (WidgetTester tester) async { // This is a smoketest to verify that adding a debugger doesn't crash. await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Semantics(), Semantics( container: true, ), Semantics( label: 'label', textDirection: TextDirection.ltr, ), ], ), ), ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SemanticsDebugger( child: Stack( children: <Widget>[ Semantics(), Semantics( container: true, ), Semantics( label: 'label', textDirection: TextDirection.ltr, ), ], ), ), ), ); expect(true, isTrue); // expect that we reach here without crashing }); testWidgets('SemanticsDebugger reparents subtree', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SemanticsDebugger( child: Stack( children: <Widget>[ Semantics(label: 'label1', textDirection: TextDirection.ltr), Positioned( key: key, left: 0.0, top: 0.0, width: 100.0, height: 100.0, child: Semantics(label: 'label2', textDirection: TextDirection.ltr), ), ], ), ), ), ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SemanticsDebugger( child: Stack( children: <Widget>[ Semantics(label: 'label1', textDirection: TextDirection.ltr), Semantics( container: true, child: Stack( children: <Widget>[ Positioned( key: key, left: 0.0, top: 0.0, width: 100.0, height: 100.0, child: Semantics(label: 'label2', textDirection: TextDirection.ltr), ), Semantics(label: 'label3', textDirection: TextDirection.ltr), ], ), ), ], ), ), ), ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SemanticsDebugger( child: Stack( children: <Widget>[ Semantics(label: 'label1', textDirection: TextDirection.ltr), Semantics( container: true, child: Stack( children: <Widget>[ Positioned( key: key, left: 0.0, top: 0.0, width: 100.0, height: 100.0, child: Semantics(label: 'label2', textDirection: TextDirection.ltr), ), Semantics(label: 'label3', textDirection: TextDirection.ltr), Semantics(label: 'label4', textDirection: TextDirection.ltr), ], ), ), ], ), ), ), ); expect(tester.takeException(), isNull); }); testWidgets('SemanticsDebugger interaction test', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SemanticsDebugger( child: Material( child: ListView( children: <Widget>[ ElevatedButton( onPressed: () { log.add('top'); }, child: const Text('TOP'), ), ElevatedButton( onPressed: () { log.add('bottom'); }, child: const Text('BOTTOM'), ), ], ), ), ), ), ); await tester.tap(find.text('TOP'), warnIfMissed: false); // hitting the debugger expect(log, equals(<String>['top'])); log.clear(); await tester.tap(find.text('BOTTOM'), warnIfMissed: false); // hitting the debugger expect(log, equals(<String>['bottom'])); log.clear(); }); testWidgets('SemanticsDebugger interaction test - negative', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SemanticsDebugger( child: Material( child: ListView( children: <Widget>[ ElevatedButton( onPressed: () { log.add('top'); }, child: const Text('TOP', textDirection: TextDirection.ltr), ), ExcludeSemantics( child: ElevatedButton( onPressed: () { log.add('bottom'); }, child: const Text('BOTTOM', textDirection: TextDirection.ltr), ), ), ], ), ), ), ), ); await tester.tap(find.text('TOP'), warnIfMissed: false); // hitting the debugger expect(log, equals(<String>['top'])); log.clear(); await tester.tap(find.text('BOTTOM'), warnIfMissed: false); // hitting the debugger expect(log, equals(<String>[])); log.clear(); }); testWidgets('SemanticsDebugger scroll test', (WidgetTester tester) async { final Key childKey = UniqueKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SemanticsDebugger( child: ListView( children: <Widget>[ Container( key: childKey, height: 5000.0, color: Colors.green[500], ), ], ), ), ), ); expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(0.0)); await tester.fling(find.byType(ListView), const Offset(0.0, -200.0), 200.0, warnIfMissed: false); // hitting the debugger); await tester.pump(); expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(-480.0)); await tester.fling(find.byType(ListView), const Offset(200.0, 0.0), 200.0, warnIfMissed: false); // hitting the debugger); await tester.pump(); expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(-480.0)); await tester.fling(find.byType(ListView), const Offset(-200.0, 0.0), 200.0, warnIfMissed: false); // hitting the debugger); await tester.pump(); expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(-480.0)); await tester.fling(find.byType(ListView), const Offset(0.0, 200.0), 200.0, warnIfMissed: false); // hitting the debugger); await tester.pump(); expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(0.0)); }); testWidgets('SemanticsDebugger long press', (WidgetTester tester) async { bool didLongPress = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SemanticsDebugger( child: GestureDetector( onLongPress: () { expect(didLongPress, isFalse); didLongPress = true; }, child: const Text('target', textDirection: TextDirection.ltr), ), ), ), ); await tester.longPress(find.text('target'), warnIfMissed: false); // hitting the debugger expect(didLongPress, isTrue); }); testWidgets('SemanticsDebugger slider', (WidgetTester tester) async { double value = 0.75; await tester.pumpWidget( MaterialApp( home: Directionality( textDirection: TextDirection.ltr, child: SemanticsDebugger( child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: MediaQueryData.fromView(tester.view), child: Material( child: Center( child: Slider( value: value, onChanged: (double newValue) { value = newValue; }, ), ), ), ), ), ), ) ), ); // The fling below must be such that the velocity estimation examines an // offset greater than the kTouchSlop. Too slow or too short a distance, and // it won't trigger. The actual distance moved doesn't matter since this is // interpreted as a gesture by the semantics debugger and sent to the widget // as a semantic action that always moves by 10% of the complete track. await tester.fling(find.byType(Slider), const Offset(-100.0, 0.0), 2000.0, warnIfMissed: false); // hitting the debugger switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.macOS: expect(value, equals(0.65)); case TargetPlatform.linux: case TargetPlatform.windows: case TargetPlatform.android: case TargetPlatform.fuchsia: expect(value, equals(0.70)); } }, variant: TargetPlatformVariant.all()); testWidgets('SemanticsDebugger checkbox', (WidgetTester tester) async { final Key keyTop = UniqueKey(); final Key keyBottom = UniqueKey(); bool? valueTop = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SemanticsDebugger( child: Material( child: ListView( children: <Widget>[ Checkbox( key: keyTop, value: valueTop, onChanged: (bool? newValue) { valueTop = newValue; }, ), Checkbox( key: keyBottom, value: false, onChanged: null, ), ], ), ), ), ), ); await tester.tap(find.byKey(keyTop), warnIfMissed: false); // hitting the debugger expect(valueTop, isTrue); valueTop = false; expect(valueTop, isFalse); await tester.tap(find.byKey(keyBottom), warnIfMissed: false); // hitting the debugger expect(valueTop, isFalse); }); testWidgets('SemanticsDebugger checkbox message', (WidgetTester tester) async { final Key checkbox = UniqueKey(); final Key checkboxUnchecked = UniqueKey(); final Key checkboxDisabled = UniqueKey(); final Key checkboxDisabledUnchecked = UniqueKey(); final Key debugger = UniqueKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SemanticsDebugger( key: debugger, child: Material( child: ListView( children: <Widget>[ Semantics( container: true, key: checkbox, child: Checkbox( value: true, onChanged: (bool? _) { }, ), ), Semantics( container: true, key: checkboxUnchecked, child: Checkbox( value: false, onChanged: (bool? _) { }, ), ), Semantics( container: true, key: checkboxDisabled, child: const Checkbox( value: true, onChanged: null, ), ), Semantics( container: true, key: checkboxDisabledUnchecked, child: const Checkbox( value: false, onChanged: null, ), ), ], ), ), ), ), ); expect( _getMessageShownInSemanticsDebugger(widgetKey: checkbox, debuggerKey: debugger, tester: tester), 'checked', ); expect( _getMessageShownInSemanticsDebugger(widgetKey: checkboxUnchecked, debuggerKey: debugger, tester: tester), 'unchecked', ); expect( _getMessageShownInSemanticsDebugger(widgetKey: checkboxDisabled, debuggerKey: debugger, tester: tester), 'checked; disabled', ); expect( _getMessageShownInSemanticsDebugger(widgetKey: checkboxDisabledUnchecked, debuggerKey: debugger, tester: tester), 'unchecked; disabled', ); }); testWidgets('SemanticsDebugger ignores duplicated label and tooltip for Android', (WidgetTester tester) async { final Key child = UniqueKey(); final Key debugger = UniqueKey(); final bool isPlatformAndroid = defaultTargetPlatform == TargetPlatform.android; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SemanticsDebugger( key: debugger, child: Material( child: Semantics( container: true, key: child, label: 'text', tooltip: 'text', ), ), ), ), ); expect( _getMessageShownInSemanticsDebugger(widgetKey: child, debuggerKey: debugger, tester: tester), isPlatformAndroid ? 'text' : 'text\ntext', ); }, variant: TargetPlatformVariant.all()); testWidgets('SemanticsDebugger textfield', (WidgetTester tester) async { final UniqueKey textField = UniqueKey(); final UniqueKey debugger = UniqueKey(); await tester.pumpWidget( MaterialApp( home: SemanticsDebugger( key: debugger, child: Material( child: TextField( key: textField, ), ), ), ), ); final dynamic semanticsDebuggerPainter = _getSemanticsDebuggerPainter(debuggerKey: debugger, tester: tester); final RenderObject renderTextfield = tester.renderObject(find.descendant(of: find.byKey(textField), matching: find.byType(Semantics)).first); expect( // ignore: avoid_dynamic_calls semanticsDebuggerPainter.getMessage(renderTextfield.debugSemantics), 'textfield', ); }); testWidgets('SemanticsDebugger label style is used in the painter.', (WidgetTester tester) async { final UniqueKey debugger = UniqueKey(); const TextStyle labelStyle = TextStyle(color: Colors.amber); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SemanticsDebugger( key: debugger, labelStyle: labelStyle, child: Semantics( label: 'label', textDirection: TextDirection.ltr, ), ), ), ); // ignore: avoid_dynamic_calls expect(_getSemanticsDebuggerPainter(debuggerKey: debugger, tester: tester).labelStyle, labelStyle); }); testWidgets('SemanticsDebugger label for rtl.', (WidgetTester tester) async { final UniqueKey debugger = UniqueKey(); final Key label = UniqueKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.rtl, child: SemanticsDebugger( key: debugger, child: Semantics( label: 'ملصق', textDirection: TextDirection.rtl, key: label, ), ), ), ); expect(_getMessageShownInSemanticsDebugger(widgetKey: label, debuggerKey: debugger, tester: tester), '\u2067ملصق\u2069'); }); } String _getMessageShownInSemanticsDebugger({ required Key widgetKey, required Key debuggerKey, required WidgetTester tester, }) { final dynamic semanticsDebuggerPainter = _getSemanticsDebuggerPainter(debuggerKey: debuggerKey, tester: tester); // ignore: avoid_dynamic_calls return semanticsDebuggerPainter.getMessage(tester.renderObject(find.byKey(widgetKey)).debugSemantics) as String; } dynamic _getSemanticsDebuggerPainter({ required Key debuggerKey, required WidgetTester tester, }) { final CustomPaint customPaint = tester.widgetList(find.descendant( of: find.byKey(debuggerKey), matching: find.byType(CustomPaint), )).first as CustomPaint; final dynamic semanticsDebuggerPainter = customPaint.foregroundPainter; expect(semanticsDebuggerPainter.runtimeType.toString(), '_SemanticsDebuggerPainter'); return semanticsDebuggerPainter; }
flutter/packages/flutter/test/widgets/semantics_debugger_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/semantics_debugger_test.dart", "repo_id": "flutter", "token_count": 8590 }
705
// 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. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { tearDown(() { debugDisableShadows = true; }); testWidgets('Shadows on BoxDecoration', (WidgetTester tester) async { await tester.pumpWidget( Center( child: RepaintBoundary( child: Container( margin: const EdgeInsets.all(50.0), decoration: BoxDecoration( boxShadow: kElevationToShadow[9], ), height: 100.0, width: 100.0, ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('shadow.BoxDecoration.disabled.png'), ); debugDisableShadows = false; tester.binding.reassembleApplication(); await tester.pump(); await expectLater( find.byType(Container), matchesGoldenFile('shadow.BoxDecoration.enabled.png'), ); debugDisableShadows = true; }); group('Shadows on ShapeDecoration', () { Widget build(int elevation) { return Center( child: RepaintBoundary( child: Container( margin: const EdgeInsets.all(150.0), decoration: ShapeDecoration( shape: const BeveledRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20.0))), shadows: kElevationToShadow[elevation], ), height: 100.0, width: 100.0, ), ), ); } for (final int elevation in kElevationToShadow.keys) { testWidgets('elevation $elevation', (WidgetTester tester) async { debugDisableShadows = false; await tester.pumpWidget(build(elevation)); await expectLater( find.byType(Container), matchesGoldenFile('shadow.ShapeDecoration.$elevation.png'), ); debugDisableShadows = true; }); } }); testWidgets('Shadows with PhysicalLayer', (WidgetTester tester) async { await tester.pumpWidget( Center( child: RepaintBoundary( child: Container( margin: const EdgeInsets.all(150.0), color: Colors.yellow[200], child: PhysicalModel( elevation: 9.0, color: Colors.blue[900]!, child: const SizedBox( height: 100.0, width: 100.0, ), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('shadow.PhysicalModel.disabled.png'), ); debugDisableShadows = false; tester.binding.reassembleApplication(); await tester.pump(); await expectLater( find.byType(Container), matchesGoldenFile('shadow.PhysicalModel.enabled.png'), ); debugDisableShadows = true; }); group('Shadows with PhysicalShape', () { Widget build(double elevation) { return Center( child: RepaintBoundary( child: Container( padding: const EdgeInsets.all(150.0), color: Colors.yellow[200], child: PhysicalShape( color: Colors.green[900]!, clipper: const ShapeBorderClipper( shape: BeveledRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(20.0)), ), ), elevation: elevation, child: const SizedBox( height: 100.0, width: 100.0, ), ), ), ), ); } for (final int elevation in kElevationToShadow.keys) { testWidgets('elevation $elevation', (WidgetTester tester) async { debugDisableShadows = false; await tester.pumpWidget(build(elevation.toDouble())); await expectLater( find.byType(Container), matchesGoldenFile('shadow.PhysicalShape.$elevation.png'), ); debugDisableShadows = true; }); } }); }
flutter/packages/flutter/test/widgets/shadow_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/shadow_test.dart", "repo_id": "flutter", "token_count": 1978 }
706
// 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 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import '../rendering/sliver_utils.dart'; const double VIEWPORT_HEIGHT = 600; const double VIEWPORT_WIDTH = 300; void main() { testWidgets('SliverMainAxisGroup is laid out properly', (WidgetTester tester) async { final List<int> items = List<int>.generate(20, (int i) => i); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( _buildSliverMainAxisGroup( controller: controller, slivers: <Widget>[ _buildSliverList(itemMainAxisExtent: 300, items: items, label: (int item) => Text('Group 0 Tile $item')), _buildSliverList(itemMainAxisExtent: 200, items: items, label: (int item) => Text('Group 1 Tile $item')), ], ), ); await tester.pumpAndSettle(); expect(controller.offset, 0); expect(find.text('Group 0 Tile 0'), findsOneWidget); expect(find.text('Group 0 Tile 1'), findsOneWidget); expect(find.text('Group 0 Tile 2'), findsNothing); expect(find.text('Group 1 Tile 0'), findsNothing); const double scrollOffset = 19 * 300.0; controller.jumpTo(scrollOffset); await tester.pumpAndSettle(); expect(controller.offset, scrollOffset); expect(find.text('Group 0 Tile 18'), findsNothing); expect(find.text('Group 0 Tile 19'), findsOneWidget); expect(find.text('Group 1 Tile 0'), findsOneWidget); final List<RenderSliverList> renderSlivers = tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; expect(first.geometry!.layoutExtent, equals(300.0)); expect(second.geometry!.layoutExtent, equals(300.0)); expect(first.geometry!.scrollExtent, equals(20 * 300.0)); expect(second.geometry!.scrollExtent, equals(20 * 200.0)); expect((first.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); expect(first.constraints.scrollOffset, equals(19 * 300.0)); expect((second.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(1 * 300.0)); final RenderSliverMainAxisGroup renderGroup = tester.renderObject<RenderSliverMainAxisGroup>(find.byType(SliverMainAxisGroup)); expect(renderGroup.geometry!.scrollExtent, equals(300 * 20 + 200 * 20)); expect(renderGroup.geometry!.hasVisualOverflow, isTrue); }); testWidgets('SliverMainAxisGroup is laid out properly when reversed', (WidgetTester tester) async { final List<int> items = List<int>.generate(20, (int i) => i); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( _buildSliverMainAxisGroup( controller: controller, reverse: true, slivers: <Widget>[ _buildSliverList(itemMainAxisExtent: 300, items: items, label: (int item) => Text('Group 0 Tile $item')), _buildSliverList(itemMainAxisExtent: 200, items: items, label: (int item) => Text('Group 1 Tile $item')), ], ), ); await tester.pumpAndSettle(); expect(controller.offset, 0); expect(find.text('Group 0 Tile 0'), findsOneWidget); expect(find.text('Group 0 Tile 1'), findsOneWidget); expect(find.text('Group 0 Tile 2'), findsNothing); expect(find.text('Group 1 Tile 0'), findsNothing); const double scrollOffset = 19 * 300.0; controller.jumpTo(scrollOffset); await tester.pumpAndSettle(); expect(controller.offset, scrollOffset); expect(find.text('Group 0 Tile 18'), findsNothing); expect(find.text('Group 0 Tile 19'), findsOneWidget); expect(find.text('Group 1 Tile 0'), findsOneWidget); final List<RenderSliverList> renderSlivers = tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; expect(first.geometry!.layoutExtent, equals(300.0)); expect(second.geometry!.layoutExtent, equals(300.0)); expect(first.geometry!.scrollExtent, equals(20 * 300.0)); expect(second.geometry!.scrollExtent, equals(20 * 200.0)); expect((first.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); expect(first.constraints.scrollOffset, equals(19 * 300.0)); expect((second.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(1 * 300.0)); final RenderSliverMainAxisGroup renderGroup = tester.renderObject<RenderSliverMainAxisGroup>(find.byType(SliverMainAxisGroup)); expect(renderGroup.geometry!.scrollExtent, equals(300 * 20 + 200 * 20)); expect(renderGroup.geometry!.hasVisualOverflow, isTrue); }); testWidgets('SliverMainAxisGroup is laid out properly when horizontal', (WidgetTester tester) async { final List<int> items = List<int>.generate(20, (int i) => i); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( _buildSliverMainAxisGroup( controller: controller, scrollDirection: Axis.horizontal, slivers: <Widget>[ _buildSliverList(itemMainAxisExtent: 300, items: items, label: (int item) => Text('Group 0 Tile $item'), scrollDirection: Axis.horizontal), _buildSliverList(itemMainAxisExtent: 200, items: items, label: (int item) => Text('Group 1 Tile $item'), scrollDirection: Axis.horizontal), ], ), ); await tester.pumpAndSettle(); expect(controller.offset, 0); expect(find.text('Group 0 Tile 0'), findsOneWidget); expect(find.text('Group 0 Tile 1'), findsNothing); expect(find.text('Group 1 Tile 0'), findsNothing); const double scrollOffset = 19 * 300.0; controller.jumpTo(scrollOffset); await tester.pumpAndSettle(); expect(controller.offset, scrollOffset); expect(find.text('Group 0 Tile 18'), findsNothing); expect(find.text('Group 0 Tile 19'), findsOneWidget); expect(find.text('Group 1 Tile 0'), findsNothing); const double scrollOffset2 = 20 * 300.0; controller.jumpTo(scrollOffset2); await tester.pumpAndSettle(); expect(find.text('Group 0 Tile 19'), findsNothing); expect(find.text('Group 1 Tile 0'), findsOneWidget); final List<RenderSliverList> renderSlivers = tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; expect(first.geometry!.layoutExtent, equals(0.0)); expect(second.geometry!.layoutExtent, equals(300.0)); expect(first.geometry!.scrollExtent, equals(20 * 300.0)); expect(second.geometry!.scrollExtent, equals(20 * 200.0)); expect((first.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); expect(first.constraints.scrollOffset, equals(20 * 300.0)); expect((second.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); final RenderSliverMainAxisGroup renderGroup = tester.renderObject<RenderSliverMainAxisGroup>(find.byType(SliverMainAxisGroup)); expect(renderGroup.geometry!.scrollExtent, equals(300 * 20 + 200 * 20)); expect(renderGroup.geometry!.hasVisualOverflow, isTrue); }); testWidgets('SliverMainAxisGroup is laid out properly when horizontal, reversed', (WidgetTester tester) async { final List<int> items = List<int>.generate(20, (int i) => i); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( _buildSliverMainAxisGroup( controller: controller, scrollDirection: Axis.horizontal, reverse: true, slivers: <Widget>[ _buildSliverList(itemMainAxisExtent: 300, items: items, label: (int item) => Text('Group 0 Tile $item'), scrollDirection: Axis.horizontal), _buildSliverList(itemMainAxisExtent: 200, items: items, label: (int item) => Text('Group 1 Tile $item'), scrollDirection: Axis.horizontal), ], ), ); await tester.pumpAndSettle(); expect(controller.offset, 0); expect(find.text('Group 0 Tile 0'), findsOneWidget); expect(find.text('Group 0 Tile 1'), findsNothing); expect(find.text('Group 1 Tile 0'), findsNothing); const double scrollOffset = 19 * 300.0; controller.jumpTo(scrollOffset); await tester.pumpAndSettle(); expect(controller.offset, scrollOffset); expect(find.text('Group 0 Tile 18'), findsNothing); expect(find.text('Group 0 Tile 19'), findsOneWidget); expect(find.text('Group 1 Tile 0'), findsNothing); const double scrollOffset2 = 20 * 300.0; controller.jumpTo(scrollOffset2); await tester.pumpAndSettle(); expect(find.text('Group 0 Tile 19'), findsNothing); expect(find.text('Group 1 Tile 0'), findsOneWidget); final List<RenderSliverList> renderSlivers = tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; expect(first.geometry!.layoutExtent, equals(0.0)); expect(second.geometry!.layoutExtent, equals(300.0)); expect(first.geometry!.scrollExtent, equals(20 * 300.0)); expect(second.geometry!.scrollExtent, equals(20 * 200.0)); expect((first.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); expect(first.constraints.scrollOffset, equals(20 * 300.0)); expect((second.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); final RenderSliverMainAxisGroup renderGroup = tester.renderObject<RenderSliverMainAxisGroup>(find.byType(SliverMainAxisGroup)); expect(renderGroup.geometry!.scrollExtent, equals(300 * 20 + 200 * 20)); expect(renderGroup.geometry!.hasVisualOverflow, isTrue); }); testWidgets('Hit test works properly on various parts of SliverMainAxisGroup', (WidgetTester tester) async { final List<int> items = List<int>.generate(20, (int i) => i); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); String? clickedTile; int group = 0; int tile = 0; await tester.pumpWidget(_buildSliverMainAxisGroup( controller: controller, slivers: <Widget>[ _buildSliverList( itemMainAxisExtent: 300, items: items, label: (int item) => tile == item && group == 0 ? TextButton( onPressed: () => clickedTile = 'Group 0 Tile $item', child: Text('Group 0 Tile $item'), ) : Text('Group 0 Tile $item'), ), _buildSliverList( items: items, label: (int item) => tile == item && group == 1 ? TextButton( onPressed: () => clickedTile = 'Group 1 Tile $item', child: Text('Group 1 Tile $item'), ) : Text('Group 1 Tile $item'), ), ]), ); await tester.pumpAndSettle(); await tester.tap(find.byType(TextButton)); await tester.pumpAndSettle(); expect(clickedTile, equals('Group 0 Tile 0')); clickedTile = null; group = 1; tile = 2; await tester.pumpWidget(_buildSliverMainAxisGroup( controller: controller, slivers: <Widget>[ _buildSliverList( itemMainAxisExtent: 300, items: items, label: (int item) => tile == item && group == 0 ? TextButton( onPressed: () => clickedTile = 'Group 0 Tile $item', child: Text('Group 0 Tile $item'), ) : Text('Group 0 Tile $item'), ), _buildSliverList( items: items, label: (int item) => tile == item && group == 1 ? TextButton( onPressed: () => clickedTile = 'Group 1 Tile $item', child: Text('Group 1 Tile $item'), ) : Text('Group 1 Tile $item'), ), ]), ); controller.jumpTo(300.0 * 20); await tester.pumpAndSettle(); await tester.tap(find.byType(TextButton)); await tester.pumpAndSettle(); expect(clickedTile, equals('Group 1 Tile 2')); }); testWidgets('applyPaintTransform is implemented properly', (WidgetTester tester) async { await tester.pumpWidget(_buildSliverMainAxisGroup( slivers: <Widget>[ const SliverToBoxAdapter(child: Text('first box')), const SliverToBoxAdapter(child: Text('second box')), ]), ); await tester.pumpAndSettle(); // localToGlobal calculates offset via applyPaintTransform final RenderBox first = tester.renderObject(find.text('first box')) as RenderBox; final RenderBox second = tester.renderObject(find.text('second box')); expect(first.localToGlobal(Offset.zero), Offset.zero); expect(second.localToGlobal(Offset.zero), Offset(0, first.size.height)); }); testWidgets('visitChildrenForSemantics visits children in the correct order', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(_buildSliverMainAxisGroup( controller: controller, slivers: const <Widget>[ SliverToBoxAdapter(child: SizedBox(height: 200)), SliverToBoxAdapter(child: SizedBox(height: 300)), SliverToBoxAdapter(child: SizedBox(height: 500)), SliverToBoxAdapter(child: SizedBox(height: 400)), ]), ); controller.jumpTo(300); await tester.pumpAndSettle(); final List<RenderSliver> visitedChildren = <RenderSliver>[]; final RenderSliverMainAxisGroup renderGroup = tester.renderObject<RenderSliverMainAxisGroup>(find.byType(SliverMainAxisGroup)); void visitor(RenderObject child) { visitedChildren.add(child as RenderSliver); } renderGroup.visitChildrenForSemantics(visitor); expect(visitedChildren.length, equals(2)); expect(visitedChildren[0].geometry!.scrollExtent, equals(300)); expect(visitedChildren[1].geometry!.scrollExtent, equals(500)); }); testWidgets('SliverPinnedPersistentHeader is painted within bounds of SliverMainAxisGroup', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(_buildSliverMainAxisGroup( controller: controller, slivers: <Widget>[ SliverPersistentHeader( delegate: TestDelegate(), pinned: true, ), const SliverToBoxAdapter(child: SizedBox(height: 600)), ], otherSlivers: <Widget>[ const SliverToBoxAdapter(child: SizedBox(height: 2400)), ], )); final RenderSliverMainAxisGroup renderGroup = tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; // Scroll extent is the total of the box sliver and the sliver persistent header. expect(renderGroup.geometry!.scrollExtent, equals(600.0 + 60.0)); controller.jumpTo(620); await tester.pumpAndSettle(); final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; // Paint extent after header's layout is 60.0, so we must offset by -20.0 to fit within the 40.0 remaining extent. expect(renderHeader.geometry!.paintExtent, equals(60.0)); expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-20.0)); }); testWidgets('SliverFloatingPersistentHeader is painted within bounds of SliverMainAxisGroup', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(_buildSliverMainAxisGroup( controller: controller, slivers: <Widget>[ SliverPersistentHeader( delegate: TestDelegate(), floating: true, ), const SliverToBoxAdapter(child: SizedBox(height: 600)), ], otherSlivers: <Widget>[ const SliverToBoxAdapter(child: SizedBox(height: 2400)), ], )); await tester.pumpAndSettle(); final RenderSliverMainAxisGroup renderGroup = tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; expect(renderGroup.geometry!.scrollExtent, equals(660)); controller.jumpTo(660.0); await tester.pumpAndSettle(); final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); await gesture.moveBy(const Offset(0.0, 40)); await tester.pump(); final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; // Paint extent after header's layout is 40.0, so no need to correct the paintOffset. expect(renderHeader.geometry!.paintExtent, equals(40.0)); expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); }); testWidgets('SliverPinnedPersistentHeader is painted within bounds of SliverMainAxisGroup with different minExtent/maxExtent', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(_buildSliverMainAxisGroup( controller: controller, slivers: <Widget>[ SliverPersistentHeader( delegate: TestDelegate(minExtent: 40.0), pinned: true, ), const SliverToBoxAdapter(child: SizedBox(height: 600)), ], otherSlivers: <Widget>[ const SliverToBoxAdapter(child: SizedBox(height: 2400)), ], )); final RenderSliverMainAxisGroup renderGroup = tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; expect(renderGroup.geometry!.scrollExtent, equals(660)); controller.jumpTo(630); await tester.pumpAndSettle(); // Paint extent of the header is 40.0, so we must provide an offset of -10.0 to make it fit in the 30.0 remaining paint extent of the group. expect(renderHeader.geometry!.paintExtent, equals(40.0)); expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-10.0)); controller.jumpTo(610); await tester.pumpAndSettle(); expect(renderHeader.geometry!.paintExtent, equals(40.0)); expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); }); testWidgets('SliverFloatingPersistentHeader is painted within bounds of SliverMainAxisGroup with different minExtent/maxExtent', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(_buildSliverMainAxisGroup( controller: controller, slivers: <Widget>[ SliverPersistentHeader( delegate: TestDelegate(minExtent: 40.0), floating: true, ), const SliverToBoxAdapter(child: SizedBox(height: 600)), ], otherSlivers: <Widget>[ const SliverToBoxAdapter(child: SizedBox(height: 2400)), ], )); await tester.pumpAndSettle(); final RenderSliverMainAxisGroup renderGroup = tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; expect(renderGroup.geometry!.scrollExtent, equals(660)); controller.jumpTo(660); await tester.pumpAndSettle(); final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); await gesture.moveBy(const Offset(0.0, 30.0)); await tester.pump(); // Paint extent after header's layout is 30.0, so no need to correct the paintOffset. expect(renderHeader.geometry!.paintExtent, equals(30.0)); expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); // Floating headers should expand to maximum extent as we continue scrolling. await gesture.moveBy(const Offset(0.0, 20.0)); await tester.pump(); expect(renderHeader.geometry!.paintExtent, equals(50.0)); expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); }); testWidgets('SliverPinnedFloatingPersistentHeader is painted within bounds of SliverMainAxisGroup with different minExtent/maxExtent', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(_buildSliverMainAxisGroup( controller: controller, slivers: <Widget>[ SliverPersistentHeader( delegate: TestDelegate(minExtent: 40.0), pinned: true, floating: true, ), const SliverToBoxAdapter(child: SizedBox(height: 600)), ], otherSlivers: <Widget>[ const SliverToBoxAdapter(child: SizedBox(height: 2400)), ], )); await tester.pumpAndSettle(); final RenderSliverMainAxisGroup renderGroup = tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; expect(renderGroup.geometry!.scrollExtent, equals(660)); controller.jumpTo(660); await tester.pumpAndSettle(); final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); await gesture.moveBy(const Offset(0.0, 30.0)); await tester.pump(); // Paint extent after header's layout is 40.0, so we need to adjust by -10.0. expect(renderHeader.geometry!.paintExtent, equals(40.0)); expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-10.0)); // Pinned floating headers should expand to maximum extent as we continue scrolling. await gesture.moveBy(const Offset(0.0, 20.0)); await tester.pump(); expect(renderHeader.geometry!.paintExtent, equals(50.0)); expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); }); testWidgets('SliverAppBar with floating: false, pinned: false, snap: false is painted within bounds of SliverMainAxisGroup', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(_buildSliverMainAxisGroup( controller: controller, slivers: <Widget>[ const SliverAppBar( toolbarHeight: 30, expandedHeight: 60, ), const SliverToBoxAdapter(child: SizedBox(height: 600)), ], otherSlivers: <Widget>[ const SliverToBoxAdapter(child: SizedBox(height: 2400)), ], )); await tester.pumpAndSettle(); final RenderSliverMainAxisGroup renderGroup = tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; expect(renderGroup.geometry!.scrollExtent, equals(660)); controller.jumpTo(660); await tester.pumpAndSettle(); controller.jumpTo(630); await tester.pumpAndSettle(); // At a scroll offset of 630, a normal scrolling header should be out of view. final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; expect(renderHeader.constraints.scrollOffset, equals(630)); expect(renderHeader.geometry!.layoutExtent, equals(0.0)); }); testWidgets('SliverAppBar with floating: true, pinned: false, snap: true is painted within bounds of SliverMainAxisGroup', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(_buildSliverMainAxisGroup( controller: controller, slivers: <Widget>[ const SliverAppBar( toolbarHeight: 30, expandedHeight: 60, floating: true, snap: true, ), const SliverToBoxAdapter(child: SizedBox(height: 600)), ], otherSlivers: <Widget>[ const SliverToBoxAdapter(child: SizedBox(height: 2400)), ], )); await tester.pumpAndSettle(); final RenderSliverMainAxisGroup renderGroup = tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; expect(renderGroup.geometry!.scrollExtent, equals(660)); controller.jumpTo(660); await tester.pumpAndSettle(); final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); await gesture.moveBy(const Offset(0.0, 10)); await tester.pump(); // The snap animation does not go through until the gesture is released. expect(renderHeader.geometry!.paintExtent, equals(10)); expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); // Once it is released, the header's paint extent becomes the maximum and the group sets an offset of -50.0. await gesture.up(); await tester.pumpAndSettle(); expect(renderHeader.geometry!.paintExtent, equals(60)); expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-50.0)); }); testWidgets('SliverAppBar with floating: true, pinned: true, snap: true is painted within bounds of SliverMainAxisGroup', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(_buildSliverMainAxisGroup( controller: controller, slivers: <Widget>[ const SliverAppBar( toolbarHeight: 30, expandedHeight: 60, floating: true, pinned: true, snap: true, ), const SliverToBoxAdapter(child: SizedBox(height: 600)), ], otherSlivers: <Widget>[ const SliverToBoxAdapter(child: SizedBox(height: 2400)), ], )); await tester.pumpAndSettle(); final RenderSliverMainAxisGroup renderGroup = tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; expect(renderGroup.geometry!.scrollExtent, equals(660)); controller.jumpTo(660); await tester.pumpAndSettle(); final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); await gesture.moveBy(const Offset(0.0, 10)); await tester.pump(); expect(renderHeader.geometry!.paintExtent, equals(30.0)); expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-20.0)); // Once we lift the gesture up, the animation should finish. await gesture.up(); await tester.pumpAndSettle(); expect(renderHeader.geometry!.paintExtent, equals(60.0)); expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-50.0)); }); testWidgets('SliverMainAxisGroup skips painting invisible children', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); int counter = 0; void incrementCounter() { counter += 1; } await tester.pumpWidget( _buildSliverMainAxisGroup( controller: controller, slivers: <Widget>[ MockSliverToBoxAdapter( incrementCounter: incrementCounter, child: Container( height: 1000, decoration: const BoxDecoration(color: Colors.amber), ), ), MockSliverToBoxAdapter( incrementCounter: incrementCounter, child: Container( height: 400, decoration: const BoxDecoration(color: Colors.amber) ), ), MockSliverToBoxAdapter( incrementCounter: incrementCounter, child: Container( height: 500, decoration: const BoxDecoration(color: Colors.amber) ), ), MockSliverToBoxAdapter( incrementCounter: incrementCounter, child: Container( height: 300, decoration: const BoxDecoration(color: Colors.amber) ), ), ], ), ); // Can only see top sliver. expect(counter, equals(1)); // Reset paint counter. counter = 0; controller.jumpTo(1000); await tester.pumpAndSettle(); // Can only see second and third slivers. expect(controller.offset, 1000); expect(counter, equals(2)); }); testWidgets('SliverMainAxisGroup does not cause extra builds for lazy sliver children', (WidgetTester tester) async { // By setting the correct SliverGeometry in the first SliverMainAxisGroup, // the following SliverMainAxisGroups will not perform extra work. final Map<int, int> buildsPerGroup = <int, int>{ 0 : 0, 1 : 0, 2 : 0, }; await tester.pumpWidget(MaterialApp( home: CustomScrollView( slivers: <Widget>[ for (int groupIndex = 0; groupIndex < 3; groupIndex++) SliverMainAxisGroup( slivers: <Widget>[ SliverList.builder( itemCount: 100, itemBuilder: (BuildContext context, int index) { buildsPerGroup[groupIndex] = buildsPerGroup[groupIndex]! + 1; return const SizedBox.square(dimension: 50); }, ), ], ), ] ), )); await tester.pumpAndSettle(); expect(buildsPerGroup[0], 17); // First sliver filled the screen and cache extent expect(buildsPerGroup[1], 1); // Second only lays out one child expect(buildsPerGroup[2], 1); // Third only lays out one child final RenderSliverMainAxisGroup renderGroup = tester.renderObject( find.byType(SliverMainAxisGroup).first, ) as RenderSliverMainAxisGroup; expect(renderGroup.geometry!.cacheExtent, 850.0); }); testWidgets('SliverMainAxisGroup correctly handles ensureVisible', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget( _buildSliverMainAxisGroup( viewportHeight: 300, slivers: <Widget>[ const SliverToBoxAdapter(child: SizedBox(height: 300)), SliverToBoxAdapter(child: SizedBox(key: key, height: 100)), const SliverToBoxAdapter(child: SizedBox(height: 300)), ] ) ); Scrollable.ensureVisible(key.currentContext!); await tester.pumpAndSettle(); expect(tester.getTopLeft(find.byKey(key)), Offset.zero); }); } Widget _buildSliverList({ double itemMainAxisExtent = 100, List<int> items = const <int>[], required Widget Function(int) label, Axis scrollDirection = Axis.vertical, }) { return SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int i) { return scrollDirection == Axis.vertical ? SizedBox( key: ValueKey<int>(items[i]), height: itemMainAxisExtent, child: label(items[i]), ) : SizedBox( key: ValueKey<int>(items[i]), width: itemMainAxisExtent, child: label(items[i])); }, findChildIndexCallback: (Key key) { final ValueKey<int> valueKey = key as ValueKey<int>; final int index = items.indexOf(valueKey.value); return index == -1 ? null : index; }, childCount: items.length, ), ); } Widget _buildSliverMainAxisGroup({ required List<Widget> slivers, ScrollController? controller, double viewportHeight = VIEWPORT_HEIGHT, double viewportWidth = VIEWPORT_WIDTH, Axis scrollDirection = Axis.vertical, bool reverse = false, List<Widget> otherSlivers = const <Widget>[], }) { return MaterialApp( home: Directionality( textDirection: TextDirection.ltr, child: Align( alignment: Alignment.topLeft, child: SizedBox( height: viewportHeight, width: viewportWidth, child: CustomScrollView( scrollDirection: scrollDirection, reverse: reverse, controller: controller, slivers: <Widget>[SliverMainAxisGroup(slivers: slivers), ...otherSlivers], ), ), ), ), ); } class TestDelegate extends SliverPersistentHeaderDelegate { TestDelegate({ this.maxExtent = 60.0, this.minExtent = 60.0 }); @override final double maxExtent; @override final double minExtent; @override Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { return Container(height: maxExtent); } @override bool shouldRebuild(TestDelegate oldDelegate) => true; }
flutter/packages/flutter/test/widgets/sliver_main_axis_group_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/sliver_main_axis_group_test.dart", "repo_id": "flutter", "token_count": 12463 }
707
// 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 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; Future<void> test(WidgetTester tester, double offset, { double anchor = 0.0 }) { final ViewportOffset viewportOffset = ViewportOffset.fixed(offset); addTearDown(viewportOffset.dispose); return tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Viewport( anchor: anchor / 600.0, offset: viewportOffset, slivers: const <Widget>[ SliverToBoxAdapter(child: SizedBox(height: 400.0)), SliverToBoxAdapter(child: SizedBox(height: 400.0)), SliverToBoxAdapter(child: SizedBox(height: 400.0)), SliverToBoxAdapter(child: SizedBox(height: 400.0)), SliverToBoxAdapter(child: SizedBox(height: 400.0)), ], ), ), ); } Future<void> testSliverFixedExtentList(WidgetTester tester, List<String> items) { return tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ SliverFixedExtentList( itemExtent: 900, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return Center( key: ValueKey<String>(items[index]), child: KeepAlive( items[index], ), ); }, childCount : items.length, findChildIndexCallback: (Key key) { final ValueKey<String> valueKey = key as ValueKey<String>; return items.indexOf(valueKey.value); }, ), ), ], ), ), ); } void verify(WidgetTester tester, List<Offset> idealPositions, List<bool> idealVisibles) { final List<Offset> actualPositions = tester.renderObjectList<RenderBox>(find.byType(SizedBox, skipOffstage: false)).map<Offset>( (RenderBox target) => target.localToGlobal(Offset.zero), ).toList(); final List<bool> actualVisibles = tester.renderObjectList<RenderSliverToBoxAdapter>(find.byType(SliverToBoxAdapter, skipOffstage: false)).map<bool>( (RenderSliverToBoxAdapter target) => target.geometry!.visible, ).toList(); expect(actualPositions, equals(idealPositions)); expect(actualVisibles, equals(idealVisibles)); } void main() { testWidgets('Viewport basic test', (WidgetTester tester) async { await test(tester, 0.0); expect(tester.renderObject<RenderBox>(find.byType(Viewport)).size, equals(const Size(800.0, 600.0))); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 400.0), const Offset(0.0, 800.0), const Offset(0.0, 1200.0), const Offset(0.0, 1600.0), ], <bool>[true, true, false, false, false]); await test(tester, 200.0); verify(tester, <Offset>[ const Offset(0.0, -200.0), const Offset(0.0, 200.0), const Offset(0.0, 600.0), const Offset(0.0, 1000.0), const Offset(0.0, 1400.0), ], <bool>[true, true, false, false, false]); await test(tester, 600.0); verify(tester, <Offset>[ const Offset(0.0, -600.0), const Offset(0.0, -200.0), const Offset(0.0, 200.0), const Offset(0.0, 600.0), const Offset(0.0, 1000.0), ], <bool>[false, true, true, false, false]); await test(tester, 900.0); verify(tester, <Offset>[ const Offset(0.0, -900.0), const Offset(0.0, -500.0), const Offset(0.0, -100.0), const Offset(0.0, 300.0), const Offset(0.0, 700.0), ], <bool>[false, false, true, true, false]); }); testWidgets('Viewport anchor test', (WidgetTester tester) async { await test(tester, 0.0, anchor: 100.0); expect(tester.renderObject<RenderBox>(find.byType(Viewport)).size, equals(const Size(800.0, 600.0))); verify(tester, <Offset>[ const Offset(0.0, 100.0), const Offset(0.0, 500.0), const Offset(0.0, 900.0), const Offset(0.0, 1300.0), const Offset(0.0, 1700.0), ], <bool>[true, true, false, false, false]); await test(tester, 200.0, anchor: 100.0); verify(tester, <Offset>[ const Offset(0.0, -100.0), const Offset(0.0, 300.0), const Offset(0.0, 700.0), const Offset(0.0, 1100.0), const Offset(0.0, 1500.0), ], <bool>[true, true, false, false, false]); await test(tester, 600.0, anchor: 100.0); verify(tester, <Offset>[ const Offset(0.0, -500.0), const Offset(0.0, -100.0), const Offset(0.0, 300.0), const Offset(0.0, 700.0), const Offset(0.0, 1100.0), ], <bool>[false, true, true, false, false]); await test(tester, 900.0, anchor: 100.0); verify(tester, <Offset>[ const Offset(0.0, -800.0), const Offset(0.0, -400.0), Offset.zero, const Offset(0.0, 400.0), const Offset(0.0, 800.0), ], <bool>[false, false, true, true, false]); }); testWidgets('Multiple grids and lists', (WidgetTester tester) async { await tester.pumpWidget( Center( child: SizedBox( width: 44.4, height: 60.0, child: Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate( const <Widget>[ SizedBox(height: 22.2, child: Text('TOP')), SizedBox(height: 22.2), SizedBox(height: 22.2), ], ), ), SliverFixedExtentList( itemExtent: 22.2, delegate: SliverChildListDelegate( const <Widget>[ SizedBox(), Text('A'), SizedBox(), ], ), ), SliverGrid( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, ), delegate: SliverChildListDelegate( const <Widget>[ SizedBox(), Text('B'), SizedBox(), ], ), ), SliverList( delegate: SliverChildListDelegate( const <Widget>[ SizedBox(height: 22.2), SizedBox(height: 22.2), SizedBox(height: 22.2, child: Text('BOTTOM')), ], ), ), ], ), ), ), ), ); final TestGesture gesture = await tester.startGesture(const Offset(400.0, 300.0)); expect(find.text('TOP'), findsOneWidget); expect(find.text('A'), findsNothing); expect(find.text('B'), findsNothing); expect(find.text('BOTTOM'), findsNothing); await gesture.moveBy(const Offset(0.0, -70.0)); await tester.pump(); expect(find.text('TOP'), findsNothing); expect(find.text('A'), findsOneWidget); expect(find.text('B'), findsNothing); expect(find.text('BOTTOM'), findsNothing); await gesture.moveBy(const Offset(0.0, -70.0)); await tester.pump(); expect(find.text('TOP'), findsNothing); expect(find.text('A'), findsNothing); expect(find.text('B'), findsOneWidget); expect(find.text('BOTTOM'), findsNothing); await gesture.moveBy(const Offset(0.0, -70.0)); await tester.pump(); expect(find.text('TOP'), findsNothing); expect(find.text('A'), findsNothing); expect(find.text('B'), findsNothing); expect(find.text('BOTTOM'), findsOneWidget); }); testWidgets('Sliver grid can replace intermediate items', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/138749. // The bug happens when items in between first and last item changed while // the sliver layout only display a item in the middle of the list. final List<int> items = <int>[0, 1, 2, 3, 4, 5]; final List<int> replacedItems = <int>[0, 2, 9, 10, 11, 12, 5]; Future<void> pumpSliverGrid(bool replace) async { await tester.pumpWidget( Center( child: SizedBox( width: 200, height: 200, child: Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ SliverGrid( gridDelegate: TestGridDelegate(replace), delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { final int item = replace ? replacedItems[index] : items[index]; return Container( key: ValueKey<int>(item), alignment: Alignment.center, child: Text('item $item'), ); }, childCount: replace ? 7 : 6, findChildIndexCallback: (Key key) { final int item = (key as ValueKey<int>).value; final int index = replace ? replacedItems.indexOf(item) : items.indexOf(item); return index >= 0 ? index : null; }, ), ), ], ), ), ), ), ); } await pumpSliverGrid(false); expect(find.text('item 0'), findsOneWidget); expect(find.text('item 1'), findsOneWidget); expect(find.text('item 2'), findsOneWidget); expect(find.text('item 3'), findsOneWidget); expect(find.text('item 4'), findsOneWidget); await pumpSliverGrid(true); // The TestGridDelegate only show child at index 1 when not expand. expect(find.text('item 0'), findsNothing); expect(find.text('item 1'), findsNothing); expect(find.text('item 2'), findsOneWidget); expect(find.text('item 3'), findsNothing); expect(find.text('item 4'), findsNothing); }); testWidgets('SliverFixedExtentList correctly clears garbage', (WidgetTester tester) async { final List<String> items = <String>['1', '2', '3', '4', '5', '6']; await testSliverFixedExtentList(tester, items); // Keep alive widgets require 1 frame to notify their parents. Pumps in between // drags to ensure widgets are kept alive. await tester.drag(find.byType(CustomScrollView),const Offset(0.0, -1200.0)); await tester.pump(); await tester.drag(find.byType(CustomScrollView),const Offset(0.0, -1200.0)); await tester.pump(); await tester.drag(find.byType(CustomScrollView),const Offset(0.0, -800.0)); await tester.pump(); expect(find.text('1'), findsNothing); expect(find.text('2'), findsNothing); expect(find.text('3'), findsNothing); expect(find.text('4'), findsOneWidget); expect(find.text('5'), findsOneWidget); // Indexes [0, 1, 2] are kept alive and [3, 4] are in viewport, thus the sliver // will need to keep updating the elements at these indexes whenever a rebuild is // triggered. The current child list in RenderSliverFixedExtentList is // '4' -> '5' -> null. // // With the insertion below, all items will get shifted back 1 position. The sliver // will have to update indexes [0, 1, 2, 3, 4, 5]. Since this is the first time // item '0' gets initialized, mounting the element will cause it to attach to // child list in RenderSliverFixedExtentList. This will create a gap. // '0' -> '4' -> '5' -> null. items.insert(0, '0'); await testSliverFixedExtentList(tester, items); // Sliver should collect leading and trailing garbage correctly. // // The child list update should occur in following order. // '0' -> '4' -> '5' -> null Started with Original list. // '4' -> null Removed 1 leading garbage and 1 trailing garbage. // '3' -> '4' -> null Prepended '3' because viewport is still at [3, 4]. expect(find.text('0'), findsNothing); expect(find.text('1'), findsNothing); expect(find.text('2'), findsNothing); expect(find.text('3'), findsOneWidget); expect(find.text('4'), findsOneWidget); }); testWidgets('SliverFixedExtentList handles underflow when its children changes', (WidgetTester tester) async { final List<String> items = <String>['1', '2', '3', '4', '5', '6']; final List<String> initializedChild = <String>[]; List<Widget> children = <Widget>[]; for (final String item in items) { children.add( StateInitSpy( item, () => initializedChild.add(item), key: ValueKey<String>(item), ), ); } final ScrollController controller = ScrollController(initialScrollOffset: 5400); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( controller: controller, slivers: <Widget>[ SliverFixedExtentList( itemExtent: 900, delegate: SliverChildListDelegate(children), ), ], ), ), ); await tester.pumpAndSettle(); expect(find.text('1'), findsNothing); expect(find.text('2'), findsNothing); expect(find.text('3'), findsNothing); expect(find.text('4'), findsNothing); expect(find.text('5'), findsNothing); expect(find.text('6'), findsOneWidget); expect(listEquals<String>(initializedChild, <String>['6']), isTrue); // move to item 1 and swap the children at the same time controller.jumpTo(0); final Widget temp = children[5]; children[5] = children[0]; children[0] = temp; children = List<Widget>.from(children); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( controller: controller, slivers: <Widget>[ SliverFixedExtentList( itemExtent: 900, delegate: SliverChildListDelegate(children), ), ], ), ), ); expect(find.text('1'), findsNothing); expect(find.text('2'), findsNothing); expect(find.text('3'), findsNothing); expect(find.text('4'), findsNothing); expect(find.text('5'), findsNothing); expect(find.text('6'), findsOneWidget); // None of the children should be built. expect(listEquals<String>(initializedChild, <String>['6']), isTrue); }); testWidgets( 'SliverGrid Correctly layout children after rearranging', (WidgetTester tester) async { await tester.pumpWidget(const TestSliverGrid( <Widget>[ Text('item0', key: Key('0')), Text('item1', key: Key('1')), ], )); await tester.pumpWidget(const TestSliverGrid( <Widget>[ Text('item0', key: Key('0')), Text('item3', key: Key('3')), Text('item4', key: Key('4')), Text('item1', key: Key('1')), ], )); expect(find.text('item0'), findsOneWidget); expect(find.text('item3'), findsOneWidget); expect(find.text('item4'), findsOneWidget); expect(find.text('item1'), findsOneWidget); final Offset item0Location = tester.getCenter(find.text('item0')); final Offset item3Location = tester.getCenter(find.text('item3')); final Offset item4Location = tester.getCenter(find.text('item4')); final Offset item1Location = tester.getCenter(find.text('item1')); expect(isRight(item0Location, item3Location) && sameHorizontal(item0Location, item3Location), true); expect(isBelow(item0Location, item4Location) && sameVertical(item0Location, item4Location), true); expect(isBelow(item0Location, item1Location) && isRight(item0Location, item1Location), true); }, ); testWidgets( 'SliverGrid negative usableCrossAxisExtent', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: 4, height: 4, child: CustomScrollView( slivers: <Widget>[ SliverGrid( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 8, mainAxisSpacing: 8, ), delegate: SliverChildListDelegate( <Widget>[ const Center(child: Text('A')), const Center(child: Text('B')), const Center(child: Text('C')), const Center(child: Text('D')), ], ), ), ], ), ), ), ), ); expect(tester.takeException(), isNull); }, ); testWidgets( 'SliverList can handle inaccurate scroll offset due to changes in children list', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/pull/59888. bool skip = true; Widget buildItem(BuildContext context, int index) { return !skip || index.isEven ? Card( child: ListTile( title: Text( 'item$index', style: const TextStyle(fontSize: 80), ), ), ) : Container(); } await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: CustomScrollView( slivers: <Widget> [ SliverList( delegate: SliverChildBuilderDelegate( buildItem, childCount: 30, ), ), ], ), ), ), ); // Only even items 0~12 are on the screen. expect(find.text('item0'), findsOneWidget); expect(find.text('item12'), findsOneWidget); expect(find.text('item14'), findsNothing); await tester.drag(find.byType(CustomScrollView), const Offset(0.0, -750.0)); await tester.pump(); // Only even items 16~28 are on the screen. expect(find.text('item15'), findsNothing); expect(find.text('item16'), findsOneWidget); expect(find.text('item28'), findsOneWidget); skip = false; await tester.pumpWidget( MaterialApp( home: Scaffold( body: CustomScrollView( slivers: <Widget> [ SliverList( delegate: SliverChildBuilderDelegate( buildItem, childCount: 30, ), ), ], ), ), ), ); // Only items 12~19 are on the screen. expect(find.text('item11'), findsNothing); expect(find.text('item12'), findsOneWidget); expect(find.text('item19'), findsOneWidget); expect(find.text('item20'), findsNothing); await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0)); await tester.pump(); // Only items 10~16 are on the screen. expect(find.text('item9'), findsNothing); expect(find.text('item10'), findsOneWidget); expect(find.text('item16'), findsOneWidget); expect(find.text('item17'), findsNothing); // The inaccurate scroll offset should reach zero at this point await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0)); await tester.pump(); // Only items 7~13 are on the screen. expect(find.text('item6'), findsNothing); expect(find.text('item7'), findsOneWidget); expect(find.text('item13'), findsOneWidget); expect(find.text('item14'), findsNothing); // It will be corrected as we scroll, so we have to drag multiple times. await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0)); await tester.pump(); await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0)); await tester.pump(); await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0)); await tester.pump(); // Only items 0~6 are on the screen. expect(find.text('item0'), findsOneWidget); expect(find.text('item6'), findsOneWidget); expect(find.text('item7'), findsNothing); }, ); testWidgets( 'SliverFixedExtentList Correctly layout children after rearranging', (WidgetTester tester) async { await tester.pumpWidget(const TestSliverFixedExtentList( <Widget>[ Text('item0', key: Key('0')), Text('item2', key: Key('2')), Text('item1', key: Key('1')), ], )); await tester.pumpWidget(const TestSliverFixedExtentList( <Widget>[ Text('item0', key: Key('0')), Text('item3', key: Key('3')), Text('item1', key: Key('1')), Text('item4', key: Key('4')), Text('item2', key: Key('2')), ], )); expect(find.text('item0'), findsOneWidget); expect(find.text('item3'), findsOneWidget); expect(find.text('item1'), findsOneWidget); expect(find.text('item4'), findsOneWidget); expect(find.text('item2'), findsOneWidget); final Offset item0Location = tester.getCenter(find.text('item0')); final Offset item3Location = tester.getCenter(find.text('item3')); final Offset item1Location = tester.getCenter(find.text('item1')); final Offset item4Location = tester.getCenter(find.text('item4')); final Offset item2Location = tester.getCenter(find.text('item2')); expect(isBelow(item0Location, item3Location) && sameVertical(item0Location, item3Location), true); expect(isBelow(item3Location, item1Location) && sameVertical(item3Location, item1Location), true); expect(isBelow(item1Location, item4Location) && sameVertical(item1Location, item4Location), true); expect(isBelow(item4Location, item2Location) && sameVertical(item4Location, item2Location), true); }, ); testWidgets('Can override ErrorWidget.build', (WidgetTester tester) async { const Text errorText = Text('error'); final ErrorWidgetBuilder oldBuilder = ErrorWidget.builder; ErrorWidget.builder = (FlutterErrorDetails details) => errorText; final SliverChildBuilderDelegate builderThrowsDelegate = SliverChildBuilderDelegate( (_, __) => throw 'builder', addAutomaticKeepAlives: false, addRepaintBoundaries: false, addSemanticIndexes: false, ); final KeyedSubtree wrapped = builderThrowsDelegate.build(_NullBuildContext(), 0)! as KeyedSubtree; expect(wrapped.child, errorText); expect(tester.takeException(), 'builder'); ErrorWidget.builder = oldBuilder; }); testWidgets('SliverFixedExtentList with SliverChildBuilderDelegate auto-correct scroll offset - super fast', (WidgetTester tester) async { final ScrollController controller = ScrollController(initialScrollOffset: 600); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( controller: controller, cacheExtent: 0, slivers: <Widget>[ SliverFixedExtentList( itemExtent: 200, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { if (index <= 6) { return Center(child: Text('Page $index')); } return null; }, ), ), ], ), ), ); expect(find.text('Page 0'), findsNothing); expect(find.text('Page 6'), findsNothing); await tester.drag(find.text('Page 5'), const Offset(0, -1000)); // Controller will be temporarily over-scrolled (before the frame triggered by the drag) because // SliverFixedExtentList doesn't report its size until it has built its last child, so the // maxScrollExtent is infinite, so when we move by 1000 pixels in one go, we go all the way. // // This never actually gets rendered, it's just the controller state before we lay out. expect(controller.offset, 1600.0); // However, once we pump, the scroll offset gets clamped to the newly discovered maximum, which // is the itemExtent (200) times the number of items (7) minus the height of the viewport (600). // This adds up to 800.0. await tester.pump(); expect(find.text('Page 0'), findsNothing); expect(find.text('Page 6'), findsOneWidget); expect(controller.offset, 800.0); expect(await tester.pumpAndSettle(), 1); // there should be no animation here expect(controller.offset, 800.0); }); testWidgets('SliverFixedExtentList with SliverChildBuilderDelegate auto-correct scroll offset - reasonable', (WidgetTester tester) async { final ScrollController controller = ScrollController(initialScrollOffset: 600); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( controller: controller, cacheExtent: 0, slivers: <Widget>[ SliverFixedExtentList( itemExtent: 200, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { if (index <= 6) { return Center(child: Text('Page $index')); } return null; }, ), ), ], ), ), ); await tester.drag(find.text('Page 5'), const Offset(0, -210)); // Controller will be temporarily over-scrolled. expect(controller.offset, 810.0); await tester.pumpAndSettle(); // It will be corrected after a auto scroll animation. expect(controller.offset, 800.0); }); Widget boilerPlate(Widget sliver) { return Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: CustomScrollView(slivers: <Widget>[sliver]), ), ), ); } group('SliverOffstage - ', () { testWidgets('offstage true', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget(boilerPlate( const SliverOffstage( sliver: SliverToBoxAdapter( child: Text('a'), ), ), )); expect(semantics.nodesWith(label: 'a'), hasLength(0)); expect(find.byType(Text), findsNothing); final RenderViewport renderViewport = tester.renderObject(find.byType(Viewport)); final RenderSliver renderSliver = renderViewport.lastChild!; expect(renderSliver.geometry!.scrollExtent, 0.0); expect(find.byType(SliverOffstage), findsNothing); semantics.dispose(); }); testWidgets('offstage false', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget(boilerPlate( const SliverOffstage( offstage: false, sliver: SliverToBoxAdapter( child: Text('a'), ), ), )); expect(semantics.nodesWith(label: 'a'), hasLength(1)); expect(find.byType(Text), findsOneWidget); final RenderViewport renderViewport = tester.renderObject(find.byType(Viewport)); final RenderSliver renderSliver = renderViewport.lastChild!; expect(renderSliver.geometry!.scrollExtent, 14.0); expect(find.byType(SliverOffstage), paints..paragraph()); semantics.dispose(); }); }); group('SliverOpacity - ', () { testWidgets('painting & semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); // Opacity 1.0: Semantics and painting await tester.pumpWidget(boilerPlate( const SliverOpacity( sliver: SliverToBoxAdapter( child: Text( 'a', textDirection: TextDirection.rtl, ), ), opacity: 1.0, ), )); expect(semantics.nodesWith(label: 'a'), hasLength(1)); expect(find.byType(SliverOpacity), paints..paragraph()); // Opacity 0.0: Nothing await tester.pumpWidget(boilerPlate( const SliverOpacity( sliver: SliverToBoxAdapter( child: Text( 'a', textDirection: TextDirection.rtl, ), ), opacity: 0.0, ), )); expect(semantics.nodesWith(label: 'a'), hasLength(0)); expect(find.byType(SliverOpacity), paintsNothing); // Opacity 0.0 with semantics: Just semantics await tester.pumpWidget(boilerPlate( const SliverOpacity( sliver: SliverToBoxAdapter( child: Text( 'a', textDirection: TextDirection.rtl, ), ), opacity: 0.0, alwaysIncludeSemantics: true, ), )); expect(semantics.nodesWith(label: 'a'), hasLength(1)); expect(find.byType(SliverOpacity), paintsNothing); // Opacity 0.0 without semantics: Nothing await tester.pumpWidget(boilerPlate( const SliverOpacity( sliver: SliverToBoxAdapter( child: Text( 'a', textDirection: TextDirection.rtl, ), ), opacity: 0.0, ), )); expect(semantics.nodesWith(label: 'a'), hasLength(0)); expect(find.byType(SliverOpacity), paintsNothing); // Opacity 0.1: Semantics and painting await tester.pumpWidget(boilerPlate( const SliverOpacity( sliver: SliverToBoxAdapter( child: Text( 'a', textDirection: TextDirection.rtl, ), ), opacity: 0.1, ), )); expect(semantics.nodesWith(label: 'a'), hasLength(1)); expect(find.byType(SliverOpacity), paints..paragraph()); // Opacity 0.1 without semantics: Still has semantics and painting await tester.pumpWidget(boilerPlate( const SliverOpacity( sliver: SliverToBoxAdapter( child: Text( 'a', textDirection: TextDirection.rtl, ), ), opacity: 0.1, ), )); expect(semantics.nodesWith(label: 'a'), hasLength(1)); expect(find.byType(SliverOpacity), paints..paragraph()); // Opacity 0.1 with semantics: Semantics and painting await tester.pumpWidget(boilerPlate( const SliverOpacity( sliver: SliverToBoxAdapter( child: Text( 'a', textDirection: TextDirection.rtl, ), ), opacity: 0.1, alwaysIncludeSemantics: true, ), )); expect(semantics.nodesWith(label: 'a'), hasLength(1)); expect(find.byType(SliverOpacity), paints..paragraph()); semantics.dispose(); }); }); group('SliverIgnorePointer - ', () { testWidgets('ignores pointer events', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final List<String> events = <String>[]; await tester.pumpWidget(boilerPlate( SliverIgnorePointer( ignoringSemantics: false, sliver: SliverToBoxAdapter( child: GestureDetector( child: const Text('a'), onTap: () { events.add('tap'); }, ), ), ), )); expect(semantics.nodesWith(label: 'a'), hasLength(1)); await tester.tap(find.byType(GestureDetector), warnIfMissed: false); expect(events, equals(<String>[])); semantics.dispose(); }); testWidgets('ignores semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final List<String> events = <String>[]; await tester.pumpWidget(boilerPlate( SliverIgnorePointer( ignoring: false, ignoringSemantics: true, sliver: SliverToBoxAdapter( child: GestureDetector( child: const Text('a'), onTap: () { events.add('tap'); }, ), ), ), )); expect(semantics.nodesWith(label: 'a'), hasLength(0)); await tester.tap(find.byType(GestureDetector)); expect(events, equals(<String>['tap'])); semantics.dispose(); }); testWidgets('ignoring only block semantics actions', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget(boilerPlate( SliverIgnorePointer( sliver: SliverToBoxAdapter( child: GestureDetector( child: const Text('a'), onTap: () { }, ), ), ), )); expect(semantics, includesNodeWith(label: 'a', actions: <SemanticsAction>[])); semantics.dispose(); }); testWidgets('ignores pointer events & semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final List<String> events = <String>[]; await tester.pumpWidget(boilerPlate( SliverIgnorePointer( ignoringSemantics: true, sliver: SliverToBoxAdapter( child: GestureDetector( child: const Text('a'), onTap: () { events.add('tap'); }, ), ), ), )); expect(semantics.nodesWith(label: 'a'), hasLength(0)); await tester.tap(find.byType(GestureDetector), warnIfMissed: false); expect(events, equals(<String>[])); semantics.dispose(); }); testWidgets('ignores nothing', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final List<String> events = <String>[]; await tester.pumpWidget(boilerPlate( SliverIgnorePointer( ignoring: false, ignoringSemantics: false, sliver: SliverToBoxAdapter( child: GestureDetector( child: const Text('a'), onTap: () { events.add('tap'); }, ), ), ), )); expect(semantics.nodesWith(label: 'a'), hasLength(1)); await tester.tap(find.byType(GestureDetector)); expect(events, equals(<String>['tap'])); semantics.dispose(); }); }); testWidgets('SliverList handles 0 scrollOffsetCorrection', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/62198 await tester.pumpWidget(MaterialApp( home: Scaffold( body: CustomScrollView( physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()), slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate( const <Widget>[ SizedBox.shrink(), Text('index 1'), Text('index 2'), ], ), ), ], ), ), )); await tester.fling(find.byType(Scrollable), const Offset(0.0, -500.0), 10000.0); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); }); testWidgets('SliverGrid children can be arbitrarily placed', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/64006 int firstTapped = 0; int secondTapped = 0; final Key key = UniqueKey(); await tester.pumpWidget(MaterialApp( home: Scaffold( key: key, body: CustomScrollView( slivers: <Widget>[ SliverGrid( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return Material( color: index.isEven ? Colors.yellow : Colors.red, child: InkWell( onTap: () { index.isEven ? firstTapped++ : secondTapped++; }, child: Text('Index $index'), ), ); }, childCount: 2, ), gridDelegate: _TestArbitrarySliverGridDelegate(), ), ], ), ), )); // Assertion not triggered by arbitrary placement expect(tester.takeException(), isNull); // Verify correct hit testing await tester.tap(find.text('Index 0')); expect(firstTapped, 1); expect(secondTapped, 0); await tester.tap(find.text('Index 1')); expect(firstTapped, 1); expect(secondTapped, 1); // Check other places too final Offset bottomLeft = tester.getBottomLeft(find.byKey(key)); await tester.tapAt(bottomLeft); expect(firstTapped, 1); expect(secondTapped, 1); final Offset topRight = tester.getTopRight(find.byKey(key)); await tester.tapAt(topRight); expect(firstTapped, 1); expect(secondTapped, 1); await tester.tapAt(const Offset(100.0, 100.0)); expect(firstTapped, 1); expect(secondTapped, 1); await tester.tapAt(const Offset(700.0, 500.0)); expect(firstTapped, 1); expect(secondTapped, 1); }); testWidgets('SliverList.builder can build children', (WidgetTester tester) async { int firstTapped = 0; int secondTapped = 0; final Key key = UniqueKey(); await tester.pumpWidget(MaterialApp( home: Scaffold( key: key, body: CustomScrollView( slivers: <Widget>[ SliverList.builder( itemCount: 2, itemBuilder: (BuildContext context, int index) { return Material( color: index.isEven ? Colors.yellow : Colors.red, child: InkWell( onTap: () { index.isEven ? firstTapped++ : secondTapped++; }, child: Text('Index $index'), ), ); }, ), ], ), ), )); // Verify correct hit testing await tester.tap(find.text('Index 0')); expect(firstTapped, 1); expect(secondTapped, 0); firstTapped = 0; await tester.tap(find.text('Index 1')); expect(firstTapped, 0); expect(secondTapped, 1); }); testWidgets('SliverList.builder can build children', (WidgetTester tester) async { int firstTapped = 0; int secondTapped = 0; final Key key = UniqueKey(); await tester.pumpWidget(MaterialApp( home: Scaffold( key: key, body: CustomScrollView( slivers: <Widget>[ SliverList.builder( itemCount: 2, itemBuilder: (BuildContext context, int index) { return Material( color: index.isEven ? Colors.yellow : Colors.red, child: InkWell( onTap: () { index.isEven ? firstTapped++ : secondTapped++; }, child: Text('Index $index'), ), ); }, ), ], ), ), )); // Verify correct hit testing await tester.tap(find.text('Index 0')); expect(firstTapped, 1); expect(secondTapped, 0); firstTapped = 0; await tester.tap(find.text('Index 1')); expect(firstTapped, 0); expect(secondTapped, 1); }); testWidgets('SliverList.separated can build children', (WidgetTester tester) async { int firstTapped = 0; int secondTapped = 0; final Key key = UniqueKey(); await tester.pumpWidget(MaterialApp( home: Scaffold( key: key, body: CustomScrollView( slivers: <Widget>[ SliverList.separated( itemCount: 2, itemBuilder: (BuildContext context, int index) { return Material( color: index.isEven ? Colors.yellow : Colors.red, child: InkWell( onTap: () { index.isEven ? firstTapped++ : secondTapped++; }, child: Text('Index $index'), ), ); }, separatorBuilder: (BuildContext context, int index) => Text('Separator $index'), ), ], ), ), )); // Verify correct hit testing await tester.tap(find.text('Index 0')); expect(firstTapped, 1); expect(secondTapped, 0); firstTapped = 0; await tester.tap(find.text('Index 1')); expect(firstTapped, 0); expect(secondTapped, 1); }); testWidgets('SliverList.separated has correct number of children', (WidgetTester tester) async { final Key key = UniqueKey(); await tester.pumpWidget(MaterialApp( home: Scaffold( key: key, body: CustomScrollView( slivers: <Widget>[ SliverList.separated( itemCount: 2, itemBuilder: (BuildContext context, int index) => const Text('item'), separatorBuilder: (BuildContext context, int index) => const Text('separator'), ), ], ), ), )); expect(find.text('item'), findsNWidgets(2)); expect(find.text('separator'), findsNWidgets(1)); }); testWidgets('SliverList.list can build children', (WidgetTester tester) async { int firstTapped = 0; int secondTapped = 0; final Key key = UniqueKey(); await tester.pumpWidget(MaterialApp( home: Scaffold( key: key, body: CustomScrollView( slivers: <Widget>[ SliverList.list( children: <Widget>[ Material( color: Colors.yellow, child: InkWell( onTap: () => firstTapped++, child: const Text('Index 0'), ), ), Material( color: Colors.red, child: InkWell( onTap: () => secondTapped++, child: const Text('Index 1'), ), ), ], ), ], ), ), )); // Verify correct hit testing await tester.tap(find.text('Index 0')); expect(firstTapped, 1); expect(secondTapped, 0); firstTapped = 0; await tester.tap(find.text('Index 1')); expect(firstTapped, 0); expect(secondTapped, 1); }); testWidgets('SliverFixedExtentList.builder can build children', (WidgetTester tester) async { int firstTapped = 0; int secondTapped = 0; final Key key = UniqueKey(); await tester.pumpWidget(MaterialApp( home: Scaffold( key: key, body: CustomScrollView( slivers: <Widget>[ SliverFixedExtentList.builder( itemCount: 2, itemExtent: 100, itemBuilder: (BuildContext context, int index) { return Material( color: index.isEven ? Colors.yellow : Colors.red, child: InkWell( onTap: () { index.isEven ? firstTapped++ : secondTapped++; }, child: Text('Index $index'), ), ); }, ), ], ), ), )); // Verify correct hit testing await tester.tap(find.text('Index 0')); expect(firstTapped, 1); expect(secondTapped, 0); firstTapped = 0; await tester.tap(find.text('Index 1')); expect(firstTapped, 0); expect(secondTapped, 1); }); testWidgets('SliverList.list can build children', (WidgetTester tester) async { int firstTapped = 0; int secondTapped = 0; final Key key = UniqueKey(); await tester.pumpWidget(MaterialApp( home: Scaffold( key: key, body: CustomScrollView( slivers: <Widget>[ SliverFixedExtentList.list( itemExtent: 100, children: <Widget>[ Material( color: Colors.yellow, child: InkWell( onTap: () => firstTapped++, child: const Text('Index 0'), ), ), Material( color: Colors.red, child: InkWell( onTap: () => secondTapped++, child: const Text('Index 1'), ), ), ], ), ], ), ), )); // Verify correct hit testing await tester.tap(find.text('Index 0')); expect(firstTapped, 1); expect(secondTapped, 0); firstTapped = 0; await tester.tap(find.text('Index 1')); expect(firstTapped, 0); expect(secondTapped, 1); }); testWidgets('SliverGrid.builder can build children', (WidgetTester tester) async { int firstTapped = 0; int secondTapped = 0; final Key key = UniqueKey(); await tester.pumpWidget(MaterialApp( home: Scaffold( key: key, body: CustomScrollView( slivers: <Widget>[ SliverGrid.builder( itemCount: 2, itemBuilder: (BuildContext context, int index) { return Material( color: index.isEven ? Colors.yellow : Colors.red, child: InkWell( onTap: () { index.isEven ? firstTapped++ : secondTapped++; }, child: Text('Index $index'), ), ); }, gridDelegate: _TestArbitrarySliverGridDelegate(), ), ], ), ), )); // Verify correct hit testing await tester.tap(find.text('Index 0')); expect(firstTapped, 1); expect(secondTapped, 0); firstTapped = 0; await tester.tap(find.text('Index 1')); expect(firstTapped, 0); expect(secondTapped, 1); }); testWidgets('SliverGridRegularTileLayout.computeMaxScrollOffset handles 0 children', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/59663 final ScrollController controller = ScrollController(); addTearDown(controller.dispose); // SliverGridDelegateWithFixedCrossAxisCount await tester.pumpWidget(MaterialApp( home: Scaffold( body: CustomScrollView( controller: controller, slivers: <Widget>[ SliverGrid.builder( itemCount: 0, itemBuilder: (_, __) => Container(), gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 1, mainAxisSpacing: 10, childAspectRatio: 2.1, ), ), ], ), ), )); // Verify correct scroll extent expect(controller.position.maxScrollExtent, 0.0); // SliverGridDelegateWithMaxCrossAxisExtent await tester.pumpWidget(MaterialApp( home: Scaffold( body: CustomScrollView( controller: controller, slivers: <Widget>[ SliverGrid.builder( itemCount: 0, itemBuilder: (_, __) => Container(), gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 30, ), ), ], ), ), )); // Verify correct scroll extent expect(controller.position.maxScrollExtent, 0.0); }); } bool isRight(Offset a, Offset b) => b.dx > a.dx; bool isBelow(Offset a, Offset b) => b.dy > a.dy; bool sameHorizontal(Offset a, Offset b) => b.dy == a.dy; bool sameVertical(Offset a, Offset b) => b.dx == a.dx; class TestSliverGrid extends StatelessWidget { const TestSliverGrid(this.children, { super.key }); final List<Widget> children; @override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget> [ SliverGrid( delegate: SliverChildListDelegate( children, ), gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, ), ), ], ), ); } } class _TestArbitrarySliverGridDelegate implements SliverGridDelegate { @override SliverGridLayout getLayout(SliverConstraints constraints) { return _TestArbitrarySliverGridLayout(); } @override bool shouldRelayout(SliverGridDelegate oldDelegate) { return false; } } class _TestArbitrarySliverGridLayout implements SliverGridLayout { @override double computeMaxScrollOffset(int childCount) => 1000; @override int getMinChildIndexForScrollOffset(double scrollOffset) => 0; @override int getMaxChildIndexForScrollOffset(double scrollOffset) => 2; @override SliverGridGeometry getGeometryForChildIndex(int index) { return SliverGridGeometry( scrollOffset: index * 100.0 + 300.0, crossAxisOffset: 200.0, mainAxisExtent: 100.0, crossAxisExtent: 100.0, ); } } class TestSliverFixedExtentList extends StatelessWidget { const TestSliverFixedExtentList(this.children, { super.key }); final List<Widget> children; @override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget> [ SliverFixedExtentList( itemExtent: 10.0, delegate: SliverChildListDelegate( children, ), ), ], ), ); } } class StateInitSpy extends StatefulWidget { const StateInitSpy(this.data, this.onStateInit, { super.key }); final String data; final VoidCallback onStateInit; @override StateInitSpyState createState() => StateInitSpyState(); } class StateInitSpyState extends State<StateInitSpy> { @override void initState() { super.initState(); widget.onStateInit(); } @override Widget build(BuildContext context) { return Text(widget.data); } } class KeepAlive extends StatefulWidget { const KeepAlive(this.data, { super.key }); final String data; @override KeepAliveState createState() => KeepAliveState(); } class KeepAliveState extends State<KeepAlive> with AutomaticKeepAliveClientMixin { @override bool get wantKeepAlive => true; @override Widget build(BuildContext context) { super.build(context); return Text(widget.data); } } class _NullBuildContext implements BuildContext { @override dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError(); } class TestGridDelegate implements SliverGridDelegate { TestGridDelegate(this.replace); final bool replace; @override SliverGridLayout getLayout(SliverConstraints constraints) { return TestGridLayout(replace); } @override bool shouldRelayout(covariant TestGridDelegate oldDelegate) { return true; } } class TestGridLayout implements SliverGridLayout { TestGridLayout(this.replace); final bool replace; @override double computeMaxScrollOffset(int childCount) { return 200; } @override SliverGridGeometry getGeometryForChildIndex(int index) { return SliverGridGeometry( crossAxisOffset: 20.0 + 20 * index, crossAxisExtent: 20, mainAxisExtent: 20, scrollOffset: 0, ); } @override int getMaxChildIndexForScrollOffset(double scrollOffset) { if (replace) { return 1; } return 5; } @override int getMinChildIndexForScrollOffset(double scrollOffset) { if (replace) { return 1; } return 0; } }
flutter/packages/flutter/test/widgets/slivers_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/slivers_test.dart", "repo_id": "flutter", "token_count": 24634 }
708
// 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. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) @TestOn('!chrome') library; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Centered text', (WidgetTester tester) async { await tester.pumpWidget( Center( child: RepaintBoundary( child: Container( width: 200.0, height: 100.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: const Text('Hello', textDirection: TextDirection.ltr, textAlign: TextAlign.center, style: TextStyle(color: Color(0xffff0000)), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.Centered.png'), ); await tester.pumpWidget( Center( child: RepaintBoundary( child: Container( width: 200.0, height: 100.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: const Text('Hello world how are you today', textDirection: TextDirection.ltr, textAlign: TextAlign.center, style: TextStyle(color: Color(0xffff0000)), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.Centered.wrap.png'), ); }); testWidgets('Text Foreground', (WidgetTester tester) async { const Color black = Color(0xFF000000); const Color red = Color(0xFFFF0000); const Color blue = Color(0xFF0000FF); final Shader linearGradient = const LinearGradient( colors: <Color>[red, blue], ).createShader(const Rect.fromLTWH(0.0, 0.0, 50.0, 20.0)); await tester.pumpWidget( Align( alignment: Alignment.topLeft, child: RepaintBoundary( child: Text('Hello', textDirection: TextDirection.ltr, style: TextStyle( foreground: Paint() ..color = black ..shader = linearGradient, ), ), ), ), ); await expectLater( find.byType(RepaintBoundary), matchesGoldenFile('text_golden.Foreground.gradient.png'), ); await tester.pumpWidget( Align( alignment: Alignment.topLeft, child: RepaintBoundary( child: Text('Hello', textDirection: TextDirection.ltr, style: TextStyle( foreground: Paint() ..color = black ..style = PaintingStyle.stroke ..strokeWidth = 2.0, ), ), ), ), ); await expectLater( find.byType(RepaintBoundary), matchesGoldenFile('text_golden.Foreground.stroke.png'), ); await tester.pumpWidget( Align( alignment: Alignment.topLeft, child: RepaintBoundary( child: Text('Hello', textDirection: TextDirection.ltr, style: TextStyle( foreground: Paint() ..color = black ..style = PaintingStyle.stroke ..strokeWidth = 2.0 ..shader = linearGradient, ), ), ), ), ); await expectLater( find.byType(RepaintBoundary), matchesGoldenFile('text_golden.Foreground.stroke_and_gradient.png'), ); }); // TODO(garyq): This test requires an update when the background // drawing from the beginning of the line bug is fixed. The current // tested version is not completely correct. testWidgets('Text Background', (WidgetTester tester) async { const Color red = Colors.red; const Color blue = Colors.blue; const Color translucentGreen = Color(0x5000F000); const Color translucentDarkRed = Color(0x500F0000); await tester.pumpWidget( Align( alignment: Alignment.topLeft, child: RepaintBoundary( child: Container( width: 200.0, height: 100.0, decoration: const BoxDecoration( color: Colors.green, ), child: Text.rich( TextSpan( text: 'text1 ', style: TextStyle( color: translucentGreen, background: Paint() ..color = red.withOpacity(0.5), ), children: <InlineSpan>[ TextSpan( text: 'text2', style: TextStyle( color: translucentDarkRed, background: Paint() ..color = blue.withOpacity(0.5), ), ), ], ), textDirection: TextDirection.ltr, ), ), ), ), ); await expectLater( find.byType(RepaintBoundary), matchesGoldenFile('text_golden.Background.png'), ); }); testWidgets('Text Fade', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( backgroundColor: Colors.transparent, body: RepaintBoundary( child: Center( child: Container( width: 200.0, height: 200.0, color: Colors.green, child: Center( child: Container( width: 100.0, color: Colors.blue, child: const Text( 'Pp PPp PPPp PPPPp PPPPpp PPPPppp PPPPppppp ', style: TextStyle(color: Colors.black), maxLines: 3, overflow: TextOverflow.fade, ), ), ), ), ), ), ), ), ); await expectLater( find.byType(RepaintBoundary).first, matchesGoldenFile('text_golden.Fade.png'), ); }); testWidgets('Default Strut text', (WidgetTester tester) async { await tester.pumpWidget( Center( child: RepaintBoundary( child: Container( width: 200.0, height: 100.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: const Text('Hello\nLine 2\nLine 3', textDirection: TextDirection.ltr, style: TextStyle(), strutStyle: StrutStyle(), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.StrutDefault.png'), ); }); testWidgets('Strut text 1', (WidgetTester tester) async { await tester.pumpWidget( Center( child: RepaintBoundary( child: Container( width: 200.0, height: 100.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: const Text('Hello\nLine2\nLine3', textDirection: TextDirection.ltr, style: TextStyle(), strutStyle: StrutStyle( height: 1.5, ), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.Strut.1.png'), ); }); testWidgets('Strut text 2', (WidgetTester tester) async { await tester.pumpWidget( Center( child: RepaintBoundary( child: Container( width: 200.0, height: 100.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: const Text('Hello\nLine 2\nLine 3', textDirection: TextDirection.ltr, style: TextStyle(), strutStyle: StrutStyle( height: 1.5, fontSize: 14, ), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.Strut.2.png'), ); }); testWidgets('Strut text rich', (WidgetTester tester) async { await tester.pumpWidget( Center( child: RepaintBoundary( child: Container( width: 200.0, height: 150.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: const Text.rich( TextSpan( text: 'Hello\n', style: TextStyle( color: Colors.red, fontSize: 30, ), children: <InlineSpan>[ TextSpan( text: 'Second line!\n', style: TextStyle( fontSize: 5, color: Colors.blue, ), ), TextSpan( text: 'Third line!\n', style: TextStyle( fontSize: 25, color: Colors.white, ), ), ], ), textDirection: TextDirection.ltr, strutStyle: StrutStyle( fontSize: 14, height: 1.1, leading: 0.1, ), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.Strut.3.png'), ); }); testWidgets('Strut text font fallback', (WidgetTester tester) async { // Font Fallback await tester.pumpWidget( Center( child: RepaintBoundary( child: Container( width: 200.0, height: 100.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: const Text('Hello\nLine 2\nLine 3', textDirection: TextDirection.ltr, style: TextStyle(), strutStyle: StrutStyle( fontFamily: 'FakeFont 1', fontFamilyFallback: <String>[ 'FakeFont 2', 'EvilFont 3', 'Nice Font 4', 'ahem', ], fontSize: 14, ), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.Strut.4.png'), ); }); testWidgets('Strut text rich forceStrutHeight', (WidgetTester tester) async { await tester.pumpWidget( Center( child: RepaintBoundary( child: Container( width: 200.0, height: 100.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: const Text.rich( TextSpan( text: 'Hello\n', style: TextStyle( color: Colors.red, fontSize: 30, ), children: <InlineSpan>[ TextSpan( text: 'Second line!\n', style: TextStyle( fontSize: 9, color: Colors.blue, ), ), TextSpan( text: 'Third line!\n', style: TextStyle( fontSize: 27, color: Colors.white, ), ), ], ), textDirection: TextDirection.ltr, strutStyle: StrutStyle( fontSize: 14, height: 1.1, forceStrutHeight: true, ), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.StrutForce.1.png'), ); }); testWidgets('Decoration thickness', (WidgetTester tester) async { final TextDecoration allDecorations = TextDecoration.combine( <TextDecoration>[ TextDecoration.underline, TextDecoration.overline, TextDecoration.lineThrough, ], ); await tester.pumpWidget( Center( child: RepaintBoundary( child: Container( width: 300.0, height: 100.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: Text( 'Hello, wor!\nabcd.', style: TextStyle( fontSize: 25, decoration: allDecorations, decorationColor: Colors.blue, decorationStyle: TextDecorationStyle.dashed, ), textDirection: TextDirection.rtl, ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.Decoration.1.png'), ); }); testWidgets('Decoration thickness', (WidgetTester tester) async { final TextDecoration allDecorations = TextDecoration.combine( <TextDecoration>[ TextDecoration.underline, TextDecoration.overline, TextDecoration.lineThrough, ], ); await tester.pumpWidget( Center( child: RepaintBoundary( child: Container( width: 300.0, height: 100.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: Text( 'Hello, wor!\nabcd.', style: TextStyle( fontSize: 25, decoration: allDecorations, decorationColor: Colors.blue, decorationStyle: TextDecorationStyle.wavy, decorationThickness: 4, ), textDirection: TextDirection.rtl, ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.DecorationThickness.1.png'), ); }); testWidgets('Text Inline widget', (WidgetTester tester) async { await tester.pumpWidget( Theme(data: ThemeData(useMaterial3: false), child: Center( child: RepaintBoundary( child: Material( child: Directionality( textDirection: TextDirection.ltr, child: Container( width: 400.0, height: 200.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100), child: const Text.rich( TextSpan( text: 'C ', style: TextStyle( fontSize: 16, ), children: <InlineSpan>[ WidgetSpan( child: Checkbox(value: true, onChanged: null), ), WidgetSpan( child: Checkbox(value: false, onChanged: null), ), TextSpan(text: 'He ', style: TextStyle(fontSize: 20)), WidgetSpan( child: SizedBox( width: 50.0, height: 55.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xffffff00), ), child: Center( child:SizedBox( width: 10.0, height: 15.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xffff0000), ), ), ), ), ), ), ), TextSpan(text: 'hello world! seize the day!'), WidgetSpan( child: Checkbox(value: false, onChanged: null), ), WidgetSpan( child: SizedBox( width: 20, height: 20, child: Checkbox(value: true, onChanged: null), ), ), WidgetSpan( child: Checkbox(value: false, onChanged: null), alignment: PlaceholderAlignment.baseline, baseline: TextBaseline.alphabetic, ), WidgetSpan( child: SizedBox( width: 20, height: 20, child: Checkbox(value: true, onChanged: null), ), ), WidgetSpan( child: Text('embedded'), ), ], ), textDirection: TextDirection.ltr, ), ), ), ), ), ), )), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.TextInlineWidget.1.png'), ); }); testWidgets('Text Inline widget textfield', (WidgetTester tester) async { await tester.pumpWidget( Center( child: MaterialApp( theme: ThemeData(useMaterial3: false), home: RepaintBoundary( child: Material( child: Container( width: 400.0, height: 200.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100), child: const Text.rich( TextSpan( text: 'My name is: ', style: TextStyle( fontSize: 20, ), children: <InlineSpan>[ WidgetSpan( child: SizedBox(width: 70, height: 25, child: TextField()), ), TextSpan(text: ', and my favorite city is: ', style: TextStyle(fontSize: 20)), WidgetSpan( child: SizedBox(width: 70, height: 25, child: TextField()), ), ], ), textDirection: TextDirection.ltr, ), ), ), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.TextInlineWidget.2.png'), ); }); // This tests if multiple Text.rich widgets are able to inline nest within each other. testWidgets('Text Inline widget nesting', (WidgetTester tester) async { await tester.pumpWidget( Center( child: MaterialApp( theme: ThemeData(useMaterial3: false), home: RepaintBoundary( child: Material( child: Container( width: 400.0, height: 200.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100), child: const Text.rich( TextSpan( text: 'outer', style: TextStyle( fontSize: 20, ), children: <InlineSpan>[ WidgetSpan( child: Text.rich( TextSpan( text: 'inner', style: TextStyle(color: Color(0xf402f4ff)), children: <InlineSpan>[ WidgetSpan( child: Text.rich( TextSpan( text: 'inner2', style: TextStyle(color: Color(0xf003ffff)), children: <InlineSpan>[ WidgetSpan( child: SizedBox( width: 50.0, height: 55.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xffffff30), ), child: Center( child:SizedBox( width: 10.0, height: 15.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xff5f00f0), ), ), ), ), ), ), ), ], ), ), ), WidgetSpan( child: SizedBox( width: 50.0, height: 55.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xff5fff00), ), child: Center( child:SizedBox( width: 10.0, height: 15.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xff5f0000), ), ), ), ), ), ), ), ], ), ), ), TextSpan(text: 'outer', style: TextStyle(fontSize: 20)), WidgetSpan( child: SizedBox(width: 70, height: 25, child: TextField()), ), WidgetSpan( child: SizedBox( width: 50.0, height: 55.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xffff00ff), ), child: Center( child:SizedBox( width: 10.0, height: 15.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xff0000ff), ), ), ), ), ), ), ), ], ), textDirection: TextDirection.ltr, ), ), ), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.TextInlineWidgetNest.1.png'), ); }); testWidgets('Text Inline widget baseline', (WidgetTester tester) async { await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: Center( child: RepaintBoundary( child: Material( child: Directionality( textDirection: TextDirection.ltr, child: Container( width: 400.0, height: 200.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100), child: const Text.rich( TextSpan( text: 'C ', style: TextStyle( fontSize: 16, ), children: <InlineSpan>[ WidgetSpan( alignment: PlaceholderAlignment.baseline, baseline: TextBaseline.alphabetic, child: Checkbox(value: true, onChanged: null), ), WidgetSpan( child: Checkbox(value: false, onChanged: null), ), TextSpan(text: 'He ', style: TextStyle(fontSize: 20)), WidgetSpan( alignment: PlaceholderAlignment.baseline, baseline: TextBaseline.alphabetic, child: SizedBox( width: 50.0, height: 55.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xffffff00), ), child: Center( child:SizedBox( width: 10.0, height: 15.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xffff0000), ), ), ), ), ), ), ), TextSpan(text: 'hello world! seize the day!'), WidgetSpan( alignment: PlaceholderAlignment.baseline, baseline: TextBaseline.alphabetic, child: Checkbox(value: false, onChanged: null), ), WidgetSpan( alignment: PlaceholderAlignment.baseline, baseline: TextBaseline.alphabetic, child: SizedBox( width: 20, height: 20, child: Checkbox(value: true, onChanged: null), ), ), WidgetSpan( alignment: PlaceholderAlignment.baseline, baseline: TextBaseline.alphabetic, child: Checkbox(value: false, onChanged: null), ), WidgetSpan( alignment: PlaceholderAlignment.baseline, baseline: TextBaseline.alphabetic, child: SizedBox( width: 20, height: 20, child: Checkbox(value: true, onChanged: null), ), ), WidgetSpan( alignment: PlaceholderAlignment.baseline, baseline: TextBaseline.alphabetic, child: Text('embedded'), ), TextSpan(text: 'ref'), ], ), textDirection: TextDirection.ltr, ), ), ), ), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.TextInlineWidgetBaseline.1.png'), ); }); testWidgets('Text Inline widget aboveBaseline', (WidgetTester tester) async { await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: Center( child: RepaintBoundary( child: Material( child: Directionality( textDirection: TextDirection.ltr, child: Container( width: 400.0, height: 200.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100), child: const Text.rich( TextSpan( text: 'C ', style: TextStyle( fontSize: 16, ), children: <InlineSpan>[ WidgetSpan( alignment: PlaceholderAlignment.aboveBaseline, baseline: TextBaseline.alphabetic, child: Checkbox(value: true, onChanged: null), ), WidgetSpan( child: Checkbox(value: false, onChanged: null), ), TextSpan(text: 'He ', style: TextStyle(fontSize: 20)), WidgetSpan( alignment: PlaceholderAlignment.aboveBaseline, baseline: TextBaseline.alphabetic, child: SizedBox( width: 50.0, height: 55.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xffffff00), ), child: Center( child:SizedBox( width: 10.0, height: 15.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xffff0000), ), ), ), ), ), ), ), TextSpan(text: 'hello world! seize the day!'), WidgetSpan( alignment: PlaceholderAlignment.aboveBaseline, baseline: TextBaseline.alphabetic, child: Checkbox(value: false, onChanged: null), ), WidgetSpan( alignment: PlaceholderAlignment.aboveBaseline, baseline: TextBaseline.alphabetic, child: SizedBox( width: 20, height: 20, child: Checkbox(value: true, onChanged: null), ), ), WidgetSpan( alignment: PlaceholderAlignment.aboveBaseline, baseline: TextBaseline.alphabetic, child: Checkbox(value: false, onChanged: null), ), WidgetSpan( alignment: PlaceholderAlignment.aboveBaseline, baseline: TextBaseline.alphabetic, child: SizedBox( width: 20, height: 20, child: Checkbox(value: true, onChanged: null), ), ), WidgetSpan( alignment: PlaceholderAlignment.aboveBaseline, baseline: TextBaseline.alphabetic, child: Text('embedded'), ), TextSpan(text: 'ref'), ], ), textDirection: TextDirection.ltr, ), ), ), ), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.TextInlineWidgetAboveBaseline.1.png'), ); }); testWidgets('Text Inline widget belowBaseline', (WidgetTester tester) async { await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: Center( child: RepaintBoundary( child: Material( child: Directionality( textDirection: TextDirection.ltr, child: Container( width: 400.0, height: 200.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100), child: const Text.rich( TextSpan( text: 'C ', style: TextStyle( fontSize: 16, ), children: <InlineSpan>[ WidgetSpan( alignment: PlaceholderAlignment.belowBaseline, baseline: TextBaseline.alphabetic, child: Checkbox(value: true, onChanged: null), ), WidgetSpan( child: Checkbox(value: false, onChanged: null), ), TextSpan(text: 'He ', style: TextStyle(fontSize: 20)), WidgetSpan( alignment: PlaceholderAlignment.belowBaseline, baseline: TextBaseline.alphabetic, child: SizedBox( width: 50.0, height: 55.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xffffff00), ), child: Center( child:SizedBox( width: 10.0, height: 15.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xffff0000), ), ), ), ), ), ), ), TextSpan(text: 'hello world! seize the day!'), WidgetSpan( alignment: PlaceholderAlignment.belowBaseline, baseline: TextBaseline.alphabetic, child: Checkbox(value: false, onChanged: null), ), WidgetSpan( alignment: PlaceholderAlignment.belowBaseline, baseline: TextBaseline.alphabetic, child: SizedBox( width: 20, height: 20, child: Checkbox(value: true, onChanged: null), ), ), WidgetSpan( alignment: PlaceholderAlignment.belowBaseline, baseline: TextBaseline.alphabetic, child: Checkbox(value: false, onChanged: null), ), WidgetSpan( alignment: PlaceholderAlignment.belowBaseline, baseline: TextBaseline.alphabetic, child: SizedBox( width: 20, height: 20, child: Checkbox(value: true, onChanged: null), ), ), WidgetSpan( alignment: PlaceholderAlignment.belowBaseline, baseline: TextBaseline.alphabetic, child: Text('embedded'), ), TextSpan(text: 'ref'), ], ), textDirection: TextDirection.ltr, ), ), ), ), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.TextInlineWidgetBelowBaseline.1.png'), ); }); testWidgets('Text Inline widget top', (WidgetTester tester) async { await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: Center( child: RepaintBoundary( child: Material( child: Directionality( textDirection: TextDirection.ltr, child: Container( width: 400.0, height: 200.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100), child: const Text.rich( TextSpan( text: 'C ', style: TextStyle( fontSize: 16, ), children: <InlineSpan>[ WidgetSpan( alignment: PlaceholderAlignment.top, baseline: TextBaseline.alphabetic, child: Checkbox(value: true, onChanged: null), ), WidgetSpan( child: Checkbox(value: false, onChanged: null), ), TextSpan(text: 'He ', style: TextStyle(fontSize: 20)), WidgetSpan( alignment: PlaceholderAlignment.top, baseline: TextBaseline.alphabetic, child: SizedBox( width: 50.0, height: 55.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xffffff00), ), child: Center( child:SizedBox( width: 10.0, height: 15.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xffff0000), ), ), ), ), ), ), ), TextSpan(text: 'hello world! seize the day!'), WidgetSpan( alignment: PlaceholderAlignment.top, baseline: TextBaseline.alphabetic, child: Checkbox(value: false, onChanged: null), ), WidgetSpan( alignment: PlaceholderAlignment.top, baseline: TextBaseline.alphabetic, child: SizedBox( width: 20, height: 20, child: Checkbox(value: true, onChanged: null), ), ), WidgetSpan( alignment: PlaceholderAlignment.top, baseline: TextBaseline.alphabetic, child: Checkbox(value: false, onChanged: null), ), WidgetSpan( alignment: PlaceholderAlignment.top, baseline: TextBaseline.alphabetic, child: SizedBox( width: 20, height: 20, child: Checkbox(value: true, onChanged: null), ), ), WidgetSpan( alignment: PlaceholderAlignment.top, baseline: TextBaseline.alphabetic, child: Text('embedded'), ), TextSpan(text: 'ref'), ], ), textDirection: TextDirection.ltr, ), ), ), ), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.TextInlineWidgetTop.1.png'), ); }); testWidgets('Text Inline widget middle', (WidgetTester tester) async { await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: Center( child: RepaintBoundary( child: Material( child: Directionality( textDirection: TextDirection.ltr, child: Container( width: 400.0, height: 200.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100), child: const Text.rich( TextSpan( text: 'C ', style: TextStyle( fontSize: 16, ), children: <InlineSpan>[ WidgetSpan( alignment: PlaceholderAlignment.middle, baseline: TextBaseline.alphabetic, child: Checkbox(value: true, onChanged: null), ), WidgetSpan( child: Checkbox(value: false, onChanged: null), ), TextSpan(text: 'He ', style: TextStyle(fontSize: 20)), WidgetSpan( alignment: PlaceholderAlignment.middle, baseline: TextBaseline.alphabetic, child: SizedBox( width: 50.0, height: 55.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xffffff00), ), child: Center( child:SizedBox( width: 10.0, height: 15.0, child: DecoratedBox( decoration: BoxDecoration( color: Color(0xffff0000), ), ), ), ), ), ), ), TextSpan(text: 'hello world! seize the day!'), WidgetSpan( alignment: PlaceholderAlignment.middle, baseline: TextBaseline.alphabetic, child: Checkbox(value: false, onChanged: null), ), WidgetSpan( alignment: PlaceholderAlignment.middle, baseline: TextBaseline.alphabetic, child: SizedBox( width: 20, height: 20, child: Checkbox(value: true, onChanged: null), ), ), WidgetSpan( alignment: PlaceholderAlignment.middle, baseline: TextBaseline.alphabetic, child: Checkbox(value: false, onChanged: null), ), WidgetSpan( alignment: PlaceholderAlignment.middle, baseline: TextBaseline.alphabetic, child: SizedBox( width: 20, height: 20, child: Checkbox(value: true, onChanged: null), ), ), WidgetSpan( alignment: PlaceholderAlignment.middle, baseline: TextBaseline.alphabetic, child: Text('embedded'), ), TextSpan(text: 'ref'), ], ), textDirection: TextDirection.ltr, ), ), ), ), ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.TextInlineWidgetMiddle.1.png'), ); }); testWidgets('Text TextHeightBehavior', (WidgetTester tester) async { await tester.pumpWidget( Center( child: RepaintBoundary( child: Container( width: 200.0, height: 700.0, decoration: const BoxDecoration( color: Color(0xff00ff00), ), child: const Column( children: <Widget>[ Text('Hello\nLine 2\nLine 3', textDirection: TextDirection.ltr, style: TextStyle(height: 5), ), Text('Hello\nLine 2\nLine 3', textDirection: TextDirection.ltr, style: TextStyle(height: 5), textHeightBehavior: TextHeightBehavior( applyHeightToFirstAscent: false, applyHeightToLastDescent: false, ), ), Text('Hello', textDirection: TextDirection.ltr, style: TextStyle(height: 5), textHeightBehavior: TextHeightBehavior( applyHeightToFirstAscent: false, ), ), ], ), ), ), ), ); await expectLater( find.byType(Container), matchesGoldenFile('text_golden.TextHeightBehavior.1.png'), ); }); }
flutter/packages/flutter/test/widgets/text_golden_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/text_golden_test.dart", "repo_id": "flutter", "token_count": 32907 }
709
// 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 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Animates forward when built', (WidgetTester tester) async { final List<int> values = <int>[]; int endCount = 0; await tester.pumpWidget( TweenAnimationBuilder<int>( duration: const Duration(seconds: 1), tween: IntTween(begin: 10, end: 110), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, onEnd: () { endCount++; }, ), ); expect(endCount, 0); expect(values, <int>[10]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[10, 60]); await tester.pump(const Duration(milliseconds: 501)); expect(endCount, 1); expect(values, <int>[10, 60, 110]); await tester.pump(const Duration(milliseconds: 500)); expect(endCount, 1); expect(values, <int>[10, 60, 110]); }); testWidgets('No initial animation when begin=null', (WidgetTester tester) async { final List<int> values = <int>[]; int endCount = 0; await tester.pumpWidget( TweenAnimationBuilder<int>( duration: const Duration(seconds: 1), tween: IntTween(end: 100), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, onEnd: () { endCount++; }, ), ); expect(endCount, 0); expect(values, <int>[100]); await tester.pump(const Duration(seconds: 2)); expect(endCount, 0); expect(values, <int>[100]); }); testWidgets('No initial animation when begin=end', (WidgetTester tester) async { final List<int> values = <int>[]; int endCount = 0; await tester.pumpWidget( TweenAnimationBuilder<int>( duration: const Duration(seconds: 1), tween: IntTween(begin: 100, end: 100), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, onEnd: () { endCount++; }, ), ); expect(endCount, 0); expect(values, <int>[100]); await tester.pump(const Duration(seconds: 2)); expect(endCount, 0); expect(values, <int>[100]); }); testWidgets('Replace tween animates new tween', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween}) { return TweenAnimationBuilder<int>( duration: const Duration(seconds: 1), tween: tween, builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } await tester.pumpWidget(buildWidget(tween: IntTween(begin: 0, end: 100))); expect(values, <int>[0]); await tester.pump(const Duration(seconds: 2)); // finish first animation. expect(values, <int>[0, 100]); await tester.pumpWidget(buildWidget(tween: IntTween(begin: 100, end: 200))); expect(values, <int>[0, 100, 100]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 100, 100, 150]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 100, 100, 150, 200]); }); testWidgets('Curve is respected', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween, required Curve curve}) { return TweenAnimationBuilder<int>( duration: const Duration(seconds: 1), tween: tween, curve: curve, builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } await tester.pumpWidget(buildWidget(tween: IntTween(begin: 0, end: 100), curve: Curves.easeInExpo)); expect(values, <int>[0]); await tester.pump(const Duration(milliseconds: 500)); expect(values.last, lessThan(50)); expect(values.last, greaterThan(0)); await tester.pump(const Duration(seconds: 2)); // finish animation. values.clear(); // Update curve (and tween to re-trigger animation). await tester.pumpWidget(buildWidget(tween: IntTween(begin: 100, end: 200), curve: Curves.linear)); expect(values, <int>[100]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[100, 150]); }); testWidgets('Duration is respected', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween, required Duration duration}) { return TweenAnimationBuilder<int>( tween: tween, duration: duration, builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } await tester.pumpWidget(buildWidget(tween: IntTween(begin: 0, end: 100), duration: const Duration(seconds: 1))); expect(values, <int>[0]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50]); await tester.pump(const Duration(seconds: 2)); // finish animation. values.clear(); // Update duration (and tween to re-trigger animation). await tester.pumpWidget(buildWidget(tween: IntTween(begin: 100, end: 200), duration: const Duration(seconds: 2))); expect(values, <int>[100]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[100, 125]); }); testWidgets('Child is integrated into tree', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TweenAnimationBuilder<int>( tween: IntTween(begin: 0, end: 100), duration: const Duration(seconds: 1), builder: (BuildContext context, int i, Widget? child) { return child!; }, child: const Text('Hello World'), ), ), ); expect(find.text('Hello World'), findsOneWidget); }); group('Change tween gapless while', () { testWidgets('running forward', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween}) { return TweenAnimationBuilder<int>( tween: tween, duration: const Duration(seconds: 1), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } await tester.pumpWidget(buildWidget( tween: IntTween(begin: 0, end: 100), )); expect(values, <int>[0]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50]); // Change tween await tester.pumpWidget(buildWidget( tween: IntTween(begin: 200, end: 300), )); expect(values, <int>[0, 50, 50]); // gapless: animation continues where it left off. await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50, 50, 175]); // 175 = halfway between 50 and new target 300. // Run animation to end await tester.pump(const Duration(seconds: 2)); expect(values, <int>[0, 50, 50, 175, 300]); values.clear(); }); testWidgets('running forward and then reverse with same tween instance', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween}) { return TweenAnimationBuilder<int>( tween: tween, duration: const Duration(seconds: 1), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } final IntTween tween1 = IntTween(begin: 0, end: 100); final IntTween tween2 = IntTween(begin: 200, end: 300); await tester.pumpWidget(buildWidget( tween: tween1, )); await tester.pump(const Duration(milliseconds: 500)); await tester.pumpWidget(buildWidget( tween: tween2, )); await tester.pump(const Duration(milliseconds: 500)); await tester.pump(const Duration(seconds: 2)); expect(values, <int>[0, 50, 50, 175, 300]); values.clear(); }); }); testWidgets('Changing tween while gapless tween change is in progress', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween}) { return TweenAnimationBuilder<int>( tween: tween, duration: const Duration(seconds: 1), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } final IntTween tween1 = IntTween(begin: 0, end: 100); final IntTween tween2 = IntTween(begin: 200, end: 300); final IntTween tween3 = IntTween(begin: 400, end: 501); await tester.pumpWidget(buildWidget( tween: tween1, )); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50]); values.clear(); // Change tween await tester.pumpWidget(buildWidget( tween: tween2, )); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[50, 175]); values.clear(); await tester.pumpWidget(buildWidget( tween: tween3, )); await tester.pump(const Duration(milliseconds: 500)); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[175, 338, 501]); }); testWidgets('Changing curve while no animation is running does not trigger animation', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required Curve curve}) { return TweenAnimationBuilder<int>( tween: IntTween(begin: 0, end: 100), curve: curve, duration: const Duration(seconds: 1), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } await tester.pumpWidget(buildWidget( curve: Curves.linear, )); await tester.pump(const Duration(seconds: 2)); expect(values, <int>[0, 100]); values.clear(); await tester.pumpWidget(buildWidget( curve: Curves.easeInExpo, )); expect(values, <int>[100]); await tester.pump(const Duration(seconds: 2)); expect(values, <int>[100]); }); testWidgets('Setting same tween and direction does not trigger animation', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween}) { return TweenAnimationBuilder<int>( tween: tween, duration: const Duration(seconds: 1), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } await tester.pumpWidget(buildWidget( tween: IntTween(begin: 0, end: 100), )); await tester.pump(const Duration(milliseconds: 500)); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50, 100]); values.clear(); await tester.pumpWidget(buildWidget( tween: IntTween(begin: 0, end: 100), )); await tester.pump(const Duration(milliseconds: 500)); await tester.pump(const Duration(milliseconds: 500)); expect(values, everyElement(100)); }); testWidgets('Setting same tween and direction while gapless animation is in progress works', (WidgetTester tester) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween}) { return TweenAnimationBuilder<int>( tween: tween, duration: const Duration(seconds: 1), builder: (BuildContext context, int i, Widget? child) { values.add(i); return const Placeholder(); }, ); } await tester.pumpWidget(buildWidget( tween: IntTween(begin: 0, end: 100), )); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50]); await tester.pumpWidget(buildWidget( tween: IntTween(begin: 200, end: 300), )); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50, 50, 175]); await tester.pumpWidget(buildWidget( tween: IntTween(begin: 200, end: 300), )); expect(values, <int>[0, 50, 50, 175, 175]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50, 50, 175, 175, 300]); values.clear(); await tester.pump(const Duration(seconds: 2)); expect(values, everyElement(300)); }); testWidgets('Works with nullable tweens', (WidgetTester tester) async { final List<Size?> values = <Size?>[]; await tester.pumpWidget( TweenAnimationBuilder<Size?>( duration: const Duration(seconds: 1), tween: SizeTween(end: const Size(10,10)), builder: (BuildContext context, Size? s, Widget? child) { values.add(s); return const Placeholder(); }, ), ); expect(values, <Size>[const Size(10,10)]); await tester.pump(const Duration(seconds: 2)); expect(values, <Size>[const Size(10,10)]); }); }
flutter/packages/flutter/test/widgets/tween_animation_builder_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/tween_animation_builder_test.dart", "repo_id": "flutter", "token_count": 5440 }
710
// 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 'package:flutter/services.dart'; void main() { // Changes made in https://github.com/flutter/flutter/pull/122446 final clipboardData1 = ClipboardData(text: ''); final clipboardData2 = ClipboardData(text: ''); // Changes made in https://github.com/flutter/flutter/pull/60320 final SurfaceAndroidViewController surfaceController = SurfaceAndroidViewController( viewId: 10, viewType: 'FixTester', layoutDirection: TextDirection.ltr, ); int viewId = surfaceController.viewId; final SurfaceAndroidViewController surfaceController = SurfaceAndroidViewController( error: '', ); final TextureAndroidViewController textureController = TextureAndroidViewController( error: '', ); final TextureAndroidViewController textureController = TextureAndroidViewController( viewId: 10, viewType: 'FixTester', layoutDirection: TextDirection.ltr, ); viewId = textureController.viewId; // Changes made in https://github.com/flutter/flutter/pull/81303 await SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: <SystemUiOverlay>[SystemUiOverlay.top]); await SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: <SystemUiOverlay>[SystemUiOverlay.bottom]); await SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: <SystemUiOverlay>[SystemUiOverlay.top, SystemUiOverlay.bottom]); await SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: <SystemUiOverlay>[]); await SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, error: ''); }
flutter/packages/flutter/test_fixes/services/services.dart.expect/0
{ "file_path": "flutter/packages/flutter/test_fixes/services/services.dart.expect", "repo_id": "flutter", "token_count": 537 }
711
// 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:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { final FlutterMemoryAllocations ma = FlutterMemoryAllocations.instance; setUp(() { assert(!ma.hasListeners); }); testWidgets( '$FlutterMemoryAllocations is noop when kFlutterMemoryAllocationsEnabled is false.', (WidgetTester tester) async { ObjectEvent? receivedEvent; ObjectEvent listener(ObjectEvent event) => receivedEvent = event; ma.addListener(listener); expect(ma.hasListeners, isFalse); await _activateFlutterObjects(tester); expect(receivedEvent, isNull); expect(ma.hasListeners, isFalse); ma.removeListener(listener); }, ); } class _TestRenderObject extends RenderObject { @override void debugAssertDoesMeetConstraints() {} @override Rect get paintBounds => throw UnimplementedError(); @override void performLayout() {} @override void performResize() {} @override Rect get semanticBounds => throw UnimplementedError(); } class _TestLayer extends Layer{ @override void addToScene(SceneBuilder builder) {} } /// Create and dispose Flutter objects to fire memory allocation events. Future<void> _activateFlutterObjects(WidgetTester tester) async { final RenderObject renderObject = _TestRenderObject(); final Layer layer = _TestLayer(); renderObject.dispose(); // It is ok to use protected members for testing. // ignore: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member layer.dispose(); }
flutter/packages/flutter/test_release/rendering/memory_allocations_test.dart/0
{ "file_path": "flutter/packages/flutter/test_release/rendering/memory_allocations_test.dart", "repo_id": "flutter", "token_count": 564 }
712
// 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 'enum_util.dart'; import 'find.dart'; import 'message.dart'; /// Offset types that can be requested by [GetOffset]. enum OffsetType { /// The top left point. topLeft, /// The top right point. topRight, /// The bottom left point. bottomLeft, /// The bottom right point. bottomRight, /// The center point. center, } EnumIndex<OffsetType> _offsetTypeIndex = EnumIndex<OffsetType>(OffsetType.values); /// A Flutter Driver command that returns the [offsetType] from the RenderObject /// identified by [finder]. /// /// The requested offset is returned in logical pixels, which can be translated /// to device pixels via [dart:ui.FlutterView.devicePixelRatio]. class GetOffset extends CommandWithTarget { /// The `finder` looks for an element to get its rect. GetOffset(super.finder, this.offsetType, { super.timeout }); /// Deserializes this command from the value generated by [serialize]. GetOffset.deserialize(super.json, super.finderFactory) : offsetType = _offsetTypeIndex.lookupBySimpleName(json['offsetType']!), super.deserialize(); @override Map<String, String> serialize() => super.serialize()..addAll(<String, String>{ 'offsetType': _offsetTypeIndex.toSimpleName(offsetType), }); /// The type of the requested offset. final OffsetType offsetType; @override String get kind => 'get_offset'; } /// The result of the [GetOffset] command. /// /// The offset is provided in logical pixels, which can be translated /// to device pixels via [dart:ui.FlutterView.devicePixelRatio]. class GetOffsetResult extends Result { /// Creates a result with the offset defined by [dx] and [dy]. const GetOffsetResult({ this.dx = 0.0, this.dy = 0.0}); /// The x component of the offset in logical pixels. /// /// The value can be translated to device pixels via /// [dart:ui.FlutterView.devicePixelRatio]. final double dx; /// The y component of the offset in logical pixels. /// /// The value can be translated to device pixels via /// [dart:ui.FlutterView.devicePixelRatio]. final double dy; /// Deserializes the result from JSON. static GetOffsetResult fromJson(Map<String, dynamic> json) { return GetOffsetResult( dx: json['dx'] as double, dy: json['dy'] as double, ); } @override Map<String, dynamic> toJson() => <String, double>{ 'dx': dx, 'dy': dy, }; }
flutter/packages/flutter_driver/lib/src/common/geometry.dart/0
{ "file_path": "flutter/packages/flutter_driver/lib/src/common/geometry.dart", "repo_id": "flutter", "token_count": 785 }
713
// 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 'percentile_utils.dart'; import 'timeline.dart'; /// Summarizes [GpuSumarizer]s corresponding to GPU start and end events. class GpuSumarizer { /// Creates a RasterCacheSummarizer given the timeline events. GpuSumarizer(List<TimelineEvent> gpuEvents) { for (final TimelineEvent event in gpuEvents) { final Object? value = event.arguments!['FrameTimeMS']; if (value is String) { final double? parsedValue = double.tryParse(value); if (parsedValue != null) { _frameTimes.add(parsedValue); } } } } /// Whether or not this event is a GPU event. static const Set<String> kGpuEvents = <String>{'GPUTracer'}; final List<double> _frameTimes = <double>[]; /// Computes the average GPU time recorded. double computeAverageGPUTime() => _computeAverage(_frameTimes); /// The [percentile]-th percentile GPU time recorded. double computePercentileGPUTime(double percentile) { if (_frameTimes.isEmpty) { return 0; } return findPercentile(_frameTimes, percentile); } /// Compute the worst GPU time recorded. double computeWorstGPUTime() => _computeWorst(_frameTimes); static double _computeAverage(List<double> values) { if (values.isEmpty) { return 0; } double total = 0; for (final double data in values) { total += data; } return total / values.length; } static double _computeWorst(List<double> values) { if (values.isEmpty) { return 0; } values.sort(); return values.last; } }
flutter/packages/flutter_driver/lib/src/driver/gpu_sumarizer.dart/0
{ "file_path": "flutter/packages/flutter_driver/lib/src/driver/gpu_sumarizer.dart", "repo_id": "flutter", "token_count": 605 }
714
// 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 'package:flutter_driver/src/common/wait.dart'; import '../../common.dart'; void main() { group('WaitForCondition', () { test('WaitForCondition serialize', () { expect( const WaitForCondition(NoTransientCallbacks()).serialize(), <String, String>{'command': 'waitForCondition', 'conditionName': 'NoTransientCallbacksCondition'}); }); test('WaitForCondition serialize with timeout', () { expect( const WaitForCondition(NoTransientCallbacks(), timeout: Duration(milliseconds: 10)).serialize(), <String, String>{'command': 'waitForCondition', 'timeout': '10', 'conditionName': 'NoTransientCallbacksCondition'}); }); test('WaitForCondition deserialize', () { final Map<String, String> jsonMap = <String, String>{ 'command': 'waitForCondition', 'conditionName': 'NoTransientCallbacksCondition', }; final WaitForCondition waitForCondition = WaitForCondition.deserialize(jsonMap); expect(waitForCondition.kind, 'waitForCondition'); expect(waitForCondition.condition, equals(const NoTransientCallbacks())); }); test('WaitForCondition deserialize with timeout', () { final Map<String, String> jsonMap = <String, String>{ 'command': 'waitForCondition', 'timeout': '10', 'conditionName': 'NoTransientCallbacksCondition', }; final WaitForCondition waitForCondition = WaitForCondition.deserialize(jsonMap); expect(waitForCondition.kind, 'waitForCondition'); expect(waitForCondition.condition, equals(const NoTransientCallbacks())); expect(waitForCondition.timeout, equals(const Duration(milliseconds: 10))); }); test('WaitForCondition requiresRootWidget', () { expect( const WaitForCondition(NoTransientCallbacks()) .requiresRootWidgetAttached, isTrue); expect( const WaitForCondition(FirstFrameRasterized()) .requiresRootWidgetAttached, isFalse); }); }); group('NoTransientCallbacksCondition', () { test('NoTransientCallbacksCondition serialize', () { expect( const NoTransientCallbacks().serialize(), <String, String>{'conditionName': 'NoTransientCallbacksCondition'}); }); test('NoTransientCallbacksCondition deserialize', () { final Map<String, String> jsonMap = <String, String>{ 'conditionName': 'NoTransientCallbacksCondition', }; final NoTransientCallbacks condition = NoTransientCallbacks.deserialize(jsonMap); expect(condition, equals(const NoTransientCallbacks())); expect(condition.serialize(), equals(jsonMap)); }); test('NoTransientCallbacksCondition deserialize error', () { expect( () => NoTransientCallbacks.deserialize(<String, String>{'conditionName': 'Unknown'}), throwsA(predicate<SerializationException>((SerializationException e) => e.message == 'Error occurred during deserializing the NoTransientCallbacksCondition JSON string: {conditionName: Unknown}'))); }); }); group('NoPendingFrameCondition', () { test('NoPendingFrameCondition serialize', () { expect(const NoPendingFrame().serialize(), <String, String>{ 'conditionName': 'NoPendingFrameCondition', }); }); test('NoPendingFrameCondition deserialize', () { final Map<String, String> jsonMap = <String, String>{ 'conditionName': 'NoPendingFrameCondition', }; final NoPendingFrame condition = NoPendingFrame.deserialize(jsonMap); expect(condition, equals(const NoPendingFrame())); expect(condition.serialize(), equals(jsonMap)); }); test('NoPendingFrameCondition deserialize error', () { expect( () => NoPendingFrame.deserialize(<String, String>{'conditionName': 'Unknown'}), throwsA(predicate<SerializationException>((SerializationException e) => e.message == 'Error occurred during deserializing the NoPendingFrameCondition JSON string: {conditionName: Unknown}'))); }); }); group('FirstFrameRasterizedCondition', () { test('FirstFrameRasterizedCondition serialize', () { expect( const FirstFrameRasterized().serialize(), <String, String>{'conditionName': 'FirstFrameRasterizedCondition'}); }); test('FirstFrameRasterizedCondition deserialize', () { final Map<String, String> jsonMap = <String, String>{ 'conditionName': 'FirstFrameRasterizedCondition', }; final FirstFrameRasterized condition = FirstFrameRasterized.deserialize(jsonMap); expect(condition, equals(const FirstFrameRasterized())); expect(condition.serialize(), equals(jsonMap)); }); test('FirstFrameRasterizedCondition deserialize error', () { expect( () => FirstFrameRasterized.deserialize(<String, String>{'conditionName': 'Unknown'}), throwsA(predicate<SerializationException>((SerializationException e) => e.message == 'Error occurred during deserializing the FirstFrameRasterizedCondition JSON string: {conditionName: Unknown}'))); }); test('FirstFrameRasterizedCondition requiresRootWidget', () { expect(const FirstFrameRasterized().requiresRootWidgetAttached, isFalse); }); }); group('CombinedCondition', () { test('CombinedCondition serialize', () { const CombinedCondition combinedCondition = CombinedCondition(<SerializableWaitCondition>[ NoTransientCallbacks(), NoPendingFrame(), ]); expect(combinedCondition.serialize(), <String, String>{ 'conditionName': 'CombinedCondition', 'conditions': '[{"conditionName":"NoTransientCallbacksCondition"},{"conditionName":"NoPendingFrameCondition"}]', }); }); test('CombinedCondition serialize - empty condition list', () { const CombinedCondition combinedCondition = CombinedCondition(<SerializableWaitCondition>[]); expect(combinedCondition.serialize(), <String, String>{ 'conditionName': 'CombinedCondition', 'conditions': '[]', }); }); test('CombinedCondition deserialize - empty condition list', () { final Map<String, String> jsonMap = <String, String>{ 'conditionName': 'CombinedCondition', 'conditions': '[]', }; final CombinedCondition condition = CombinedCondition.deserialize(jsonMap); expect(condition.conditions, equals(<SerializableWaitCondition>[])); expect(condition.serialize(), equals(jsonMap)); }); test('CombinedCondition deserialize', () { final Map<String, String> jsonMap = <String, String>{ 'conditionName': 'CombinedCondition', 'conditions': '[{"conditionName":"NoPendingFrameCondition"},{"conditionName":"NoTransientCallbacksCondition"}]', }; final CombinedCondition condition = CombinedCondition.deserialize(jsonMap); expect( condition.conditions, equals(<SerializableWaitCondition>[ const NoPendingFrame(), const NoTransientCallbacks(), ])); expect(condition.serialize(), jsonMap); }); test('CombinedCondition deserialize - no condition list', () { final CombinedCondition condition = CombinedCondition.deserialize(<String, String>{'conditionName': 'CombinedCondition',}); expect(condition.conditions, equals(<SerializableWaitCondition>[])); expect(condition.serialize(), <String, String>{ 'conditionName': 'CombinedCondition', 'conditions': '[]', }); }); test('CombinedCondition deserialize error', () { expect( () => CombinedCondition.deserialize(<String, String>{'conditionName': 'Unknown'}), throwsA(predicate<SerializationException>((SerializationException e) => e.message == 'Error occurred during deserializing the CombinedCondition JSON string: {conditionName: Unknown}'))); }); test('CombinedCondition deserialize error - Unknown condition type', () { expect( () { return CombinedCondition.deserialize(<String, String>{ 'conditionName': 'CombinedCondition', 'conditions': '[{"conditionName":"UnknownCondition"},{"conditionName":"NoTransientCallbacksCondition"}]', }); }, throwsA(predicate<SerializationException>((SerializationException e) => e.message == 'Unsupported wait condition UnknownCondition in the JSON string {conditionName: UnknownCondition}'))); }); }); }
flutter/packages/flutter_driver/test/src/real_tests/wait_test.dart/0
{ "file_path": "flutter/packages/flutter_driver/test/src/real_tests/wait_test.dart", "repo_id": "flutter", "token_count": 3163 }
715
// 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 'package:flutter_goldens/flutter_goldens.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:platform/platform.dart'; enum _Comparator { post, pre, skip, local } _Comparator _testRecommendations({ bool hasFlutterRoot = false, bool hasLuci = false, bool hasCirrus = false, bool hasGold = false, bool hasTryJob = false, String branch = 'main', String os = 'macos', }) { final Platform platform = FakePlatform( environment: <String, String>{ if (hasFlutterRoot) 'FLUTTER_ROOT': '/flutter', if (hasLuci) 'SWARMING_TASK_ID': '8675309', if (hasCirrus) 'CIRRUS_CI': 'true', if (hasCirrus) 'CIRRUS_PR': '', if (hasCirrus) 'CIRRUS_BRANCH': branch, if (hasGold) 'GOLDCTL': 'goldctl', if (hasGold && hasCirrus) 'GOLD_SERVICE_ACCOUNT': 'service account...', if (hasTryJob) 'GOLD_TRYJOB': 'git/ref/12345/head', 'GIT_BRANCH': branch, }, operatingSystem: os, ); if (FlutterPostSubmitFileComparator.isForEnvironment(platform)) { return _Comparator.post; } if (FlutterPreSubmitFileComparator.isForEnvironment(platform)) { return _Comparator.pre; } if (FlutterSkippingFileComparator.isForEnvironment(platform)) { return _Comparator.skip; } return _Comparator.local; } void main() { test('Comparator recommendations - main branch', () { // If we're running locally (no CI), use a local comparator. expect(_testRecommendations(), _Comparator.local); expect(_testRecommendations(hasFlutterRoot: true), _Comparator.local); expect(_testRecommendations(hasGold: true), _Comparator.local); expect(_testRecommendations(hasFlutterRoot: true, hasGold: true), _Comparator.local); // If we don't have gold but are on CI, we skip regardless. expect(_testRecommendations(hasLuci: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(hasLuci: true, hasTryJob: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(hasCirrus: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(hasCirrus: true, hasTryJob: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(hasLuci: true, hasCirrus: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(hasLuci: true, hasCirrus: true, hasTryJob: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(hasFlutterRoot: true, hasLuci: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(hasFlutterRoot: true, hasLuci: true, hasTryJob: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(hasFlutterRoot: true, hasCirrus: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(hasFlutterRoot: true, hasCirrus: true, hasTryJob: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(hasFlutterRoot: true, hasLuci: true, hasCirrus: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(hasFlutterRoot: true, hasLuci: true, hasCirrus: true, hasTryJob: true), _Comparator.local); // TODO(ianh): this should be skip // On Luci, with Gold, post-submit. Flutter root and Cirrus variables should have no effect. expect(_testRecommendations(hasGold: true, hasLuci: true), _Comparator.post); expect(_testRecommendations(hasGold: true, hasLuci: true, hasCirrus: true), _Comparator.post); expect(_testRecommendations(hasGold: true, hasLuci: true, hasFlutterRoot: true), _Comparator.post); expect(_testRecommendations(hasGold: true, hasLuci: true, hasFlutterRoot: true, hasCirrus: true), _Comparator.post); // On Luci, with Gold, pre-submit. Flutter root and Cirrus variables should have no effect. expect(_testRecommendations(hasGold: true, hasLuci: true, hasTryJob: true), _Comparator.pre); expect(_testRecommendations(hasGold: true, hasLuci: true, hasCirrus: true, hasTryJob: true), _Comparator.pre); expect(_testRecommendations(hasGold: true, hasLuci: true, hasFlutterRoot: true, hasTryJob: true), _Comparator.pre); expect(_testRecommendations(hasGold: true, hasLuci: true, hasFlutterRoot: true, hasCirrus: true, hasTryJob: true), _Comparator.pre); // On Cirrus (with Gold and not on Luci), we skip regardless. expect(_testRecommendations(hasCirrus: true, hasGold: true, hasFlutterRoot: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(hasCirrus: true, hasGold: true, hasFlutterRoot: true, hasTryJob: true), _Comparator.local); // TODO(ianh): this should be skip }); test('Comparator recommendations - release branch', () { // If we're running locally (no CI), use a local comparator. expect(_testRecommendations(branch: 'flutter-3.16-candidate.0'), _Comparator.local); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasFlutterRoot: true), _Comparator.local); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasGold: true), _Comparator.local); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasFlutterRoot: true, hasGold: true), _Comparator.local); // If we don't have gold but are on CI, we skip regardless. expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasLuci: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasLuci: true, hasTryJob: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasCirrus: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasCirrus: true, hasTryJob: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasLuci: true, hasCirrus: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasLuci: true, hasCirrus: true, hasTryJob: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasFlutterRoot: true, hasLuci: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasFlutterRoot: true, hasLuci: true, hasTryJob: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasFlutterRoot: true, hasCirrus: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasFlutterRoot: true, hasCirrus: true, hasTryJob: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasFlutterRoot: true, hasLuci: true, hasCirrus: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasFlutterRoot: true, hasLuci: true, hasCirrus: true, hasTryJob: true), _Comparator.skip); // On Luci, with Gold, post-submit. Flutter root and Cirrus variables should have no effect. Branch should make us skip. expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasGold: true, hasLuci: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasGold: true, hasLuci: true, hasCirrus: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasGold: true, hasLuci: true, hasFlutterRoot: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasGold: true, hasLuci: true, hasFlutterRoot: true, hasCirrus: true), _Comparator.skip); // On Luci, with Gold, pre-submit. Flutter root and Cirrus variables should have no effect. Branch should make us skip. expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasGold: true, hasLuci: true, hasTryJob: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasGold: true, hasLuci: true, hasCirrus: true, hasTryJob: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasGold: true, hasLuci: true, hasFlutterRoot: true, hasTryJob: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasGold: true, hasLuci: true, hasFlutterRoot: true, hasCirrus: true, hasTryJob: true), _Comparator.skip); // On Cirrus (with Gold and not on Luci), we skip regardless. expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasCirrus: true, hasGold: true, hasFlutterRoot: true), _Comparator.skip); expect(_testRecommendations(branch: 'flutter-3.16-candidate.0', hasCirrus: true, hasGold: true, hasFlutterRoot: true, hasTryJob: true), _Comparator.skip); }); test('Comparator recommendations - Linux', () { // If we're running locally (no CI), use a local comparator. expect(_testRecommendations(os: 'linux'), _Comparator.local); expect(_testRecommendations(os: 'linux', hasFlutterRoot: true), _Comparator.local); expect(_testRecommendations(os: 'linux', hasGold: true), _Comparator.local); expect(_testRecommendations(os: 'linux', hasFlutterRoot: true, hasGold: true), _Comparator.local); // If we don't have gold but are on CI, we skip regardless. expect(_testRecommendations(os: 'linux', hasLuci: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(os: 'linux', hasLuci: true, hasTryJob: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(os: 'linux', hasCirrus: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(os: 'linux', hasCirrus: true, hasTryJob: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(os: 'linux', hasLuci: true, hasCirrus: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(os: 'linux', hasLuci: true, hasCirrus: true, hasTryJob: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(os: 'linux', hasFlutterRoot: true, hasLuci: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(os: 'linux', hasFlutterRoot: true, hasLuci: true, hasTryJob: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(os: 'linux', hasFlutterRoot: true, hasCirrus: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(os: 'linux', hasFlutterRoot: true, hasCirrus: true, hasTryJob: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(os: 'linux', hasFlutterRoot: true, hasLuci: true, hasCirrus: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(os: 'linux', hasFlutterRoot: true, hasLuci: true, hasCirrus: true, hasTryJob: true), _Comparator.local); // TODO(ianh): this should be skip // On Luci, with Gold, post-submit. Flutter root and Cirrus variables should have no effect. expect(_testRecommendations(os: 'linux', hasGold: true, hasLuci: true), _Comparator.post); expect(_testRecommendations(os: 'linux', hasGold: true, hasLuci: true, hasCirrus: true), _Comparator.post); expect(_testRecommendations(os: 'linux', hasGold: true, hasLuci: true, hasFlutterRoot: true), _Comparator.post); expect(_testRecommendations(os: 'linux', hasGold: true, hasLuci: true, hasFlutterRoot: true, hasCirrus: true), _Comparator.post); // On Luci, with Gold, pre-submit. Flutter root and Cirrus variables should have no effect. expect(_testRecommendations(os: 'linux', hasGold: true, hasLuci: true, hasTryJob: true), _Comparator.pre); expect(_testRecommendations(os: 'linux', hasGold: true, hasLuci: true, hasCirrus: true, hasTryJob: true), _Comparator.pre); expect(_testRecommendations(os: 'linux', hasGold: true, hasLuci: true, hasFlutterRoot: true, hasTryJob: true), _Comparator.pre); expect(_testRecommendations(os: 'linux', hasGold: true, hasLuci: true, hasFlutterRoot: true, hasCirrus: true, hasTryJob: true), _Comparator.pre); // On Cirrus (with Gold and not on Luci), we skip regardless. expect(_testRecommendations(os: 'linux', hasCirrus: true, hasGold: true, hasFlutterRoot: true), _Comparator.local); // TODO(ianh): this should be skip expect(_testRecommendations(os: 'linux', hasCirrus: true, hasGold: true, hasFlutterRoot: true, hasTryJob: true), _Comparator.local); // TODO(ianh): this should be skip }); test('Branch names', () { expect(_testRecommendations(hasLuci: true, hasGold: true, hasFlutterRoot: true), _Comparator.post); expect(_testRecommendations(branch: 'master', hasLuci: true, hasGold: true, hasFlutterRoot: true), _Comparator.post); expect(_testRecommendations(branch: 'the_master_of_justice', hasLuci: true, hasGold: true, hasFlutterRoot: true), _Comparator.skip); expect(_testRecommendations(branch: 'maintain_accuracy', hasLuci: true, hasGold: true, hasFlutterRoot: true), _Comparator.skip); }); }
flutter/packages/flutter_goldens/test/comparator_selection_test.dart/0
{ "file_path": "flutter/packages/flutter_goldens/test/comparator_selection_test.dart", "repo_id": "flutter", "token_count": 4571 }
716
{ "datePickerHourSemanticsLabelOne": "$hour en punt", "datePickerHourSemanticsLabelOther": "$hour en punt", "datePickerMinuteSemanticsLabelOne": "1 minut", "datePickerMinuteSemanticsLabelOther": "$minute minuts", "datePickerDateOrder": "dmy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "Avui", "alertDialogLabel": "Alerta", "timerPickerHourLabelOne": "hora", "timerPickerHourLabelOther": "hores", "timerPickerMinuteLabelOne": "min", "timerPickerMinuteLabelOther": "min", "timerPickerSecondLabelOne": "s", "timerPickerSecondLabelOther": "s", "cutButtonLabel": "Retalla", "copyButtonLabel": "Copia", "pasteButtonLabel": "Enganxa", "clearButtonLabel": "Clear", "selectAllButtonLabel": "Seleccionar-ho tot", "tabSemanticsLabel": "Pestanya $tabIndex de $tabCount", "modalBarrierDismissLabel": "Ignora", "searchTextFieldPlaceholderLabel": "Cerca", "noSpellCheckReplacementsLabel": "No s'ha trobat cap substitució", "menuDismissLabel": "Ignora el menú", "lookUpButtonLabel": "Mira amunt", "searchWebButtonLabel": "Cerca al web", "shareButtonLabel": "Comparteix..." }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ca.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ca.arb", "repo_id": "flutter", "token_count": 431 }
717
{ "datePickerHourSemanticsLabelOne": "$hour en punto", "datePickerHourSemanticsLabelOther": "$hour en punto", "datePickerMinuteSemanticsLabelOne": "1 minuto", "datePickerMinuteSemanticsLabelOther": "$minute minutos", "datePickerDateOrder": "dmy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "a. m.", "postMeridiemAbbreviation": "p. m.", "todayLabel": "Hoy", "alertDialogLabel": "Alerta", "timerPickerHourLabelOne": "hora", "timerPickerHourLabelOther": "horas", "timerPickerMinuteLabelOne": "min", "timerPickerMinuteLabelOther": "min", "timerPickerSecondLabelOne": "s", "timerPickerSecondLabelOther": "s", "cutButtonLabel": "Cortar", "copyButtonLabel": "Copiar", "pasteButtonLabel": "Pegar", "selectAllButtonLabel": "Seleccionar todo", "tabSemanticsLabel": "Pestaña $tabIndex de $tabCount", "modalBarrierDismissLabel": "Cerrar", "searchTextFieldPlaceholderLabel": "Buscar", "noSpellCheckReplacementsLabel": "No se ha encontrado ninguna sustitución", "menuDismissLabel": "Cerrar menú", "lookUpButtonLabel": "Buscador visual", "searchWebButtonLabel": "Buscar en la Web", "shareButtonLabel": "Compartir...", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_es.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_es.arb", "repo_id": "flutter", "token_count": 443 }
718
{ "datePickerHourSemanticsLabelOne": "$hour बजे", "datePickerHourSemanticsLabelOther": "$hour बजे", "datePickerMinuteSemanticsLabelOne": "1 मिनट", "datePickerMinuteSemanticsLabelOther": "$minute मिनट", "datePickerDateOrder": "dmy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "आज", "alertDialogLabel": "अलर्ट", "timerPickerHourLabelOne": "घंटा", "timerPickerHourLabelOther": "घंटे", "timerPickerMinuteLabelOne": "मिनट", "timerPickerMinuteLabelOther": "मिनट", "timerPickerSecondLabelOne": "सेकंड", "timerPickerSecondLabelOther": "सेकंड", "cutButtonLabel": "काटें", "copyButtonLabel": "कॉपी करें", "pasteButtonLabel": "चिपकाएं", "selectAllButtonLabel": "सभी चुनें", "tabSemanticsLabel": "$tabCount का टैब $tabIndex", "modalBarrierDismissLabel": "खारिज करें", "searchTextFieldPlaceholderLabel": "खोजें", "noSpellCheckReplacementsLabel": "सही वर्तनी वाला कोई शब्द नहीं मिला", "menuDismissLabel": "मेन्यू खारिज करें", "lookUpButtonLabel": "लुक अप बटन", "searchWebButtonLabel": "वेब पर खोजें", "shareButtonLabel": "शेयर करें…", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_hi.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_hi.arb", "repo_id": "flutter", "token_count": 675 }
719
{ "datePickerHourSemanticsLabelZero": "plkst. $hour", "datePickerMinuteSemanticsLabelZero": "$minute minūtes", "timerPickerHourLabelZero": "h", "timerPickerMinuteLabelZero": "min", "timerPickerSecondLabelZero": "s", "datePickerHourSemanticsLabelOne": "plkst. $hour", "datePickerHourSemanticsLabelOther": "plkst. $hour", "datePickerMinuteSemanticsLabelOne": "1 minūte", "datePickerMinuteSemanticsLabelOther": "$minute minūtes", "datePickerDateOrder": "mdy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "priekšpusdienā", "postMeridiemAbbreviation": "pēcpusdienā", "todayLabel": "Šodien", "alertDialogLabel": "Brīdinājums", "timerPickerHourLabelOne": "h", "timerPickerHourLabelOther": "h", "timerPickerMinuteLabelOne": "min", "timerPickerMinuteLabelOther": "min", "timerPickerSecondLabelOne": "s", "timerPickerSecondLabelOther": "s", "cutButtonLabel": "Izgriezt", "copyButtonLabel": "Kopēt", "pasteButtonLabel": "Ielīmēt", "selectAllButtonLabel": "Atlasīt visu", "tabSemanticsLabel": "$tabIndex. cilne no $tabCount", "modalBarrierDismissLabel": "Nerādīt", "searchTextFieldPlaceholderLabel": "Meklēšana", "noSpellCheckReplacementsLabel": "Netika atrasts neviens vārds aizstāšanai", "menuDismissLabel": "Nerādīt izvēlni", "lookUpButtonLabel": "Meklēt", "searchWebButtonLabel": "Meklēt tīmeklī", "shareButtonLabel": "Kopīgot…", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_lv.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_lv.arb", "repo_id": "flutter", "token_count": 579 }
720
{ "datePickerHourSemanticsLabelFew": "Ora $hour", "datePickerMinuteSemanticsLabelFew": "$minute minute", "timerPickerHourLabelFew": "ore", "timerPickerMinuteLabelFew": "min.", "timerPickerSecondLabelFew": "sec.", "datePickerHourSemanticsLabelOne": "Ora $hour", "datePickerHourSemanticsLabelOther": "Ora $hour", "datePickerMinuteSemanticsLabelOne": "1 minut", "datePickerMinuteSemanticsLabelOther": "$minute de minute", "datePickerDateOrder": "dmy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "a.m.", "postMeridiemAbbreviation": "p.m.", "todayLabel": "Azi", "alertDialogLabel": "Alertă", "timerPickerHourLabelOne": "oră", "timerPickerHourLabelOther": "de ore", "timerPickerMinuteLabelOne": "min.", "timerPickerMinuteLabelOther": "min.", "timerPickerSecondLabelOne": "sec.", "timerPickerSecondLabelOther": "sec.", "cutButtonLabel": "Decupați", "copyButtonLabel": "Copiați", "pasteButtonLabel": "Inserați", "selectAllButtonLabel": "Selectează tot", "tabSemanticsLabel": "Fila $tabIndex din $tabCount", "modalBarrierDismissLabel": "Închideți", "searchTextFieldPlaceholderLabel": "Căutați", "noSpellCheckReplacementsLabel": "Nu s-au găsit înlocuiri", "menuDismissLabel": "Respingeți meniul", "lookUpButtonLabel": "Privire în sus", "searchWebButtonLabel": "Căutați pe web", "shareButtonLabel": "Trimiteți…", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ro.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ro.arb", "repo_id": "flutter", "token_count": 547 }
721
{ "datePickerHourSemanticsLabelOne": "$hour بجے", "datePickerHourSemanticsLabelOther": "$hour بجے", "datePickerMinuteSemanticsLabelOne": "1 منٹ", "datePickerMinuteSemanticsLabelOther": "$minute منٹس", "datePickerDateOrder": "dmy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "آج", "alertDialogLabel": "الرٹ", "timerPickerHourLabelOne": "گھنٹہ", "timerPickerHourLabelOther": "گھنٹے", "timerPickerMinuteLabelOne": "منٹ۔", "timerPickerMinuteLabelOther": "منٹ۔", "timerPickerSecondLabelOne": "سیکنڈ۔", "timerPickerSecondLabelOther": "سیکنڈ۔", "cutButtonLabel": "کٹ کریں", "copyButtonLabel": "کاپی کریں", "pasteButtonLabel": "پیسٹ کریں", "selectAllButtonLabel": "سبھی منتخب کریں", "tabSemanticsLabel": "$tabCount میں سے $tabIndex ٹیب", "modalBarrierDismissLabel": "برخاست کریں", "searchTextFieldPlaceholderLabel": "تلاش کریں", "noSpellCheckReplacementsLabel": "کوئی تبدیلیاں نہیں ملیں", "menuDismissLabel": "مینو برخاست کریں", "lookUpButtonLabel": "تفصیل دیکھیں", "searchWebButtonLabel": "ویب تلاش کریں", "shareButtonLabel": "اشتراک کریں...", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ur.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ur.arb", "repo_id": "flutter", "token_count": 646 }
722
{ "licensesPackageDetailTextFew": "$licenseCount ліцэнзіі", "licensesPackageDetailTextMany": "$licenseCount ліцэнзій", "scriptCategory": "English-like", "timeOfDayFormat": "H:mm", "remainingTextFieldCharacterCountFew": "Засталося $remainingCount сімвалы", "selectedRowCountTitleMany": "Выбрана $selectedRowCount элементаў", "selectedRowCountTitleFew": "Выбрана $selectedRowCount элементы", "remainingTextFieldCharacterCountMany": "Засталося $remainingCount сімвалаў", "openAppDrawerTooltip": "Адкрыць меню навігацыі", "backButtonTooltip": "Назад", "closeButtonTooltip": "Закрыць", "deleteButtonTooltip": "Выдаліць", "nextMonthTooltip": "Наступны месяц", "previousMonthTooltip": "Папярэдні месяц", "nextPageTooltip": "Наступная старонка", "firstPageTooltip": "На першую старонку", "lastPageTooltip": "На апошнюю старонку", "previousPageTooltip": "Папярэдняя старонка", "showMenuTooltip": "Паказаць меню", "aboutListTileTitle": "Інфармацыя пра праграму \"$applicationName\"", "licensesPageTitle": "Ліцэнзіі", "pageRowsInfoTitle": "$firstRow–$lastRow з $rowCount", "pageRowsInfoTitleApproximate": "$firstRow–$lastRow з прыблізна $rowCount", "rowsPerPageTitle": "Радкоў на старонку:", "tabLabel": "Укладка $tabIndex з $tabCount", "selectedRowCountTitleOne": "Выбраны 1 элемент", "selectedRowCountTitleOther": "Выбрана $selectedRowCount элемента", "cancelButtonLabel": "Скасаваць", "closeButtonLabel": "Закрыць", "continueButtonLabel": "Працягнуць", "copyButtonLabel": "Капіраваць", "cutButtonLabel": "Выразаць", "scanTextButtonLabel": "Сканіраваць тэкст", "okButtonLabel": "ОК", "pasteButtonLabel": "Уставіць", "selectAllButtonLabel": "Выбраць усе", "viewLicensesButtonLabel": "Праглядзець ліцэнзіі", "anteMeridiemAbbreviation": "раніцы", "postMeridiemAbbreviation": "вечара", "timePickerHourModeAnnouncement": "Выберыце гадзіны", "timePickerMinuteModeAnnouncement": "Выберыце хвіліны", "modalBarrierDismissLabel": "Адхіліць", "signedInLabel": "Уваход выкананы", "hideAccountsLabel": "Схаваць уліковыя запісы", "showAccountsLabel": "Паказаць уліковыя запісы", "drawerLabel": "Меню навігацыі", "popupMenuLabel": "Меню ўсплывальнага акна", "dialogLabel": "Дыялогавае акно", "alertDialogLabel": "Абвестка", "searchFieldLabel": "Пошук", "reorderItemToStart": "Перамясціць у пачатак", "reorderItemToEnd": "Перамясціць у канец", "reorderItemUp": "Перамясціць уверх", "reorderItemDown": "Перамясціць уніз", "reorderItemLeft": "Перамясціць улева", "reorderItemRight": "Перамясціць управа", "expandedIconTapHint": "Згарнуць", "collapsedIconTapHint": "Разгарнуць", "remainingTextFieldCharacterCountOne": "Застаўся 1 сімвал", "remainingTextFieldCharacterCountOther": "Засталося $remainingCount сімвала", "refreshIndicatorSemanticLabel": "Абнавіць", "moreButtonTooltip": "Яшчэ", "dateSeparator": ".", "dateHelpText": "дд.мм.гггг", "selectYearSemanticsLabel": "Выберыце год", "unspecifiedDate": "Дата", "unspecifiedDateRange": "Дыяпазон дат", "dateInputLabel": "Увядзіце дату", "dateRangeStartLabel": "Дата пачатку", "dateRangeEndLabel": "Дата заканчэння", "dateRangeStartDateSemanticLabel": "Дата пачатку: $fullDate", "dateRangeEndDateSemanticLabel": "Дата заканчэння: $fullDate", "invalidDateFormatLabel": "Няправільны фармат.", "invalidDateRangeLabel": "Няправільны дыяпазон.", "dateOutOfRangeLabel": "Па-за межамі дыяпазону.", "saveButtonLabel": "Захаваць", "datePickerHelpText": "Выберыце дату", "dateRangePickerHelpText": "Выберыце дыяпазон дат", "calendarModeButtonLabel": "Пераключыцца на каляндар", "inputDateModeButtonLabel": "Пераключыцца на ўвод тэксту", "timePickerDialHelpText": "Выберыце час", "timePickerInputHelpText": "Увядзіце час", "timePickerHourLabel": "Гадзіна", "timePickerMinuteLabel": "Хвіліна", "invalidTimeLabel": "Увядзіце дапушчальны час", "dialModeButtonLabel": "Пераход у рэжым выбару часу", "inputTimeModeButtonLabel": "Пераход у рэжым уводу тэксту", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 ліцэнзія", "licensesPackageDetailTextOther": "$licenseCount ліцэнзіі", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Наступны канал", "keyboardKeyChannelUp": "Папярэдні канал", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Выняць", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "Num Lock", "keyboardKeyNumpad1": "Num 1", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad3": "Num 3", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad8": "Num 8", "keyboardKeyNumpad9": "Num 9", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEnter": "Num Enter", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyPageDown": "PgDown", "keyboardKeyPageUp": "PgUp", "keyboardKeyPower": "Сілкаванне", "keyboardKeyPowerOff": "Выключыць", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Выбраць", "keyboardKeySpace": "Прабел", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Меню \"Панэль меню\"", "currentDateLabel": "Сёння", "scrimLabel": "Палатно", "bottomSheetLabel": "Ніжні аркуш", "scrimOnTapHint": "Закрыць: $modalRouteContentName", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "двойчы націснуць, каб згарнуць", "expansionTileCollapsedHint": "двойчы націснуць, каб разгарнуць", "expansionTileExpandedTapHint": "Згарнуць", "expansionTileCollapsedTapHint": "Разгарніце, каб даведацца больш", "expandedHint": "Згорнута", "collapsedHint": "Разгорнута", "menuDismissLabel": "Закрыць меню", "lookUpButtonLabel": "Знайсці", "searchWebButtonLabel": "Пошук у сетцы", "shareButtonLabel": "Абагуліць...", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_be.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_be.arb", "repo_id": "flutter", "token_count": 3757 }
723
{ "scriptCategory": "English-like", "timeOfDayFormat": "H:mm", "openAppDrawerTooltip": "Abrir menú de navegación", "backButtonTooltip": "Atrás", "closeButtonTooltip": "Pechar", "deleteButtonTooltip": "Eliminar", "nextMonthTooltip": "Mes seguinte", "previousMonthTooltip": "Mes anterior", "nextPageTooltip": "Páxina seguinte", "previousPageTooltip": "Páxina anterior", "firstPageTooltip": "Primeira páxina", "lastPageTooltip": "Última páxina", "showMenuTooltip": "Mostrar menú", "aboutListTileTitle": "Acerca de: $applicationName", "licensesPageTitle": "Licenzas", "pageRowsInfoTitle": "$firstRow-$lastRow de $rowCount", "pageRowsInfoTitleApproximate": "$firstRow-$lastRow de aproximadamente $rowCount", "rowsPerPageTitle": "Filas por páxina:", "tabLabel": "Pestana $tabIndex de $tabCount", "selectedRowCountTitleZero": "Non se seleccionaron elementos", "selectedRowCountTitleOne": "Seleccionouse 1 elemento", "selectedRowCountTitleOther": "Seleccionáronse $selectedRowCount elementos", "cancelButtonLabel": "Cancelar", "closeButtonLabel": "Pechar", "continueButtonLabel": "Continuar", "copyButtonLabel": "Copiar", "cutButtonLabel": "Cortar", "scanTextButtonLabel": "Escanear texto", "okButtonLabel": "Aceptar", "pasteButtonLabel": "Pegar", "selectAllButtonLabel": "Seleccionar todo", "viewLicensesButtonLabel": "Ver licenzas", "anteMeridiemAbbreviation": "a.m.", "postMeridiemAbbreviation": "p.m.", "timePickerHourModeAnnouncement": "Seleccionar horas", "timePickerMinuteModeAnnouncement": "Seleccionar minutos", "signedInLabel": "Sesión iniciada", "hideAccountsLabel": "Ocultar contas", "showAccountsLabel": "Mostrar contas", "modalBarrierDismissLabel": "Ignorar", "drawerLabel": "Menú de navegación", "popupMenuLabel": "Menú emerxente", "dialogLabel": "Cadro de diálogo", "alertDialogLabel": "Alerta", "searchFieldLabel": "Buscar", "reorderItemToStart": "Mover ao inicio", "reorderItemToEnd": "Mover ao final", "reorderItemUp": "Mover cara arriba", "reorderItemDown": "Mover cara abaixo", "reorderItemLeft": "Mover cara á esquerda", "reorderItemRight": "Mover cara á dereita", "expandedIconTapHint": "Contraer", "collapsedIconTapHint": "Despregar", "remainingTextFieldCharacterCountOne": "1 carácter restante", "remainingTextFieldCharacterCountOther": "$remainingCount caracteres restantes", "refreshIndicatorSemanticLabel": "Actualizar", "moreButtonTooltip": "Máis", "dateSeparator": "/", "dateHelpText": "mm/dd/aaaa", "selectYearSemanticsLabel": "Seleccionar ano", "unspecifiedDate": "Data", "unspecifiedDateRange": "Intervalo de datas", "dateInputLabel": "Introduce a data", "dateRangeStartLabel": "Data de inicio", "dateRangeEndLabel": "Data de finalización", "dateRangeStartDateSemanticLabel": "Data de inicio: $fullDate", "dateRangeEndDateSemanticLabel": "Data de finalización: $fullDate", "invalidDateFormatLabel": "O formato non é válido.", "invalidDateRangeLabel": "O intervalo de datas non é válido.", "dateOutOfRangeLabel": "A data está fóra do intervalo.", "saveButtonLabel": "Gardar", "datePickerHelpText": "Seleccionar data", "dateRangePickerHelpText": "Seleccionar intervalo de datas", "calendarModeButtonLabel": "Cambiar ao modo de calendario", "inputDateModeButtonLabel": "Cambiar ao modo de introdución de texto", "timePickerDialHelpText": "Seleccionar hora", "timePickerInputHelpText": "Indicar hora", "timePickerHourLabel": "Hora", "timePickerMinuteLabel": "Minuto", "invalidTimeLabel": "Escribe unha hora válida", "dialModeButtonLabel": "Cambiar a modo de selector en esfera", "inputTimeModeButtonLabel": "Cambiar ao modo de escritura dos números", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 licenza", "licensesPackageDetailTextOther": "$licenseCount licenzas", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "Alt Gr", "keyboardKeyBackspace": "Retroceso", "keyboardKeyCapsLock": "Bloq Maiús", "keyboardKeyChannelDown": "Canle abaixo", "keyboardKeyChannelUp": "Canle arriba", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Supr", "keyboardKeyEject": "Expulsar", "keyboardKeyEnd": "Fin", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Inicio", "keyboardKeyInsert": "Inserir", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "Bloq Num", "keyboardKeyNumpad1": "Num 1", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad3": "Num 3", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad8": "Num 8", "keyboardKeyNumpad9": "Num 9", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEnter": "Num Intro", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyPageDown": "AvPáx", "keyboardKeyPageUp": "RePáx", "keyboardKeyPower": "Acender", "keyboardKeyPowerOff": "Apagar", "keyboardKeyPrintScreen": "Imprimir pantalla", "keyboardKeyScrollLock": "Bloq Despr", "keyboardKeySelect": "Seleccionar", "keyboardKeySpace": "Espazo", "keyboardKeyMetaMacOs": "Comando", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Menú da barra de menú", "currentDateLabel": "Hoxe", "scrimLabel": "Sombreado", "bottomSheetLabel": "Panel inferior", "scrimOnTapHint": "Pechar $modalRouteContentName", "keyboardKeyShift": "Maiús", "expansionTileExpandedHint": "toca dúas veces para contraer", "expansionTileCollapsedHint": "tocar dúas veces para despregar", "expansionTileExpandedTapHint": "Contraer", "expansionTileCollapsedTapHint": "Despregar para obter máis detalles", "expandedHint": "Contraído", "collapsedHint": "Despregado", "menuDismissLabel": "Pechar menú", "lookUpButtonLabel": "Mirar cara arriba", "searchWebButtonLabel": "Buscar na Web", "shareButtonLabel": "Compartir…", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_gl.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_gl.arb", "repo_id": "flutter", "token_count": 2383 }
724