Created
May 30, 2023 22:05
-
-
Save kenresoft/8b83d413aabaeca9ce520416672cec99 to your computer and use it in GitHub Desktop.
Comparing Dart 2 and Dart 3 Switch statements.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final RiffSwitchType type; | |
RiffSwitchType get _type => type; | |
@override | |
Widget build(BuildContext context) { | |
// Dart 2 | |
/*switch (_type) { | |
case RiffSwitchType.simple: | |
return _buildSimpleSwitch(); | |
case RiffSwitchType.decorative: | |
return _buildDecorativeSwitch(); | |
default: | |
return _buildSimpleSwitch(); | |
}*/ | |
// Using Dart 3 Pattern | |
return switch (this) { | |
RiffSwitch(_type: RiffSwitchType.simple) => _buildSimpleSwitch(), | |
RiffSwitch(_type: RiffSwitchType.decorative) => _buildDecorativeSwitch(), | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Comparing Dart 2 and Dart 3 Switch statements.
The build method returns a widget based on the value of the _type property of a RiffSwitch object.
Explanation
The build method is a method of a widget class that returns a widget tree. In this case, the widget tree returned
depends on the value of the _type property of a RiffSwitch object.
The build method first defines a private getter _type that returns the value of the _type property.
Then, there are two different implementations of the switch statement.
The first implementation is commented out
and is for Dart 2. It uses the traditional switch statement to check the value of _type and returns the
appropriate widget. If _type is
RiffSwitchType.simple
, _buildSimpleSwitch()
is called and its result is returned. If _type isRiffSwitchType.decorative
,_buildDecorativeSwitch()
is called and its result is returned.If _type is any other value,
_buildSimpleSwitch()
is called and its result is returned.The second implementation is for Dart 3 and uses the new switch expression syntax. It returns a widget based on the value of this. If this is a RiffSwitch object with _type set to
RiffSwitchType.simple
,_buildSimpleSwitch()
is called and its result is returned. If this is a RiffSwitch object with _type set toRiffSwitchType.decorative
,_buildDecorativeSwitch()
is called and its result is returned.