Skip to content

Instantly share code, notes, and snippets.

@kenresoft
Created May 30, 2023 22:05
Show Gist options
  • Save kenresoft/8b83d413aabaeca9ce520416672cec99 to your computer and use it in GitHub Desktop.
Save kenresoft/8b83d413aabaeca9ce520416672cec99 to your computer and use it in GitHub Desktop.
Comparing Dart 2 and Dart 3 Switch statements.
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(),
};
}
@kenresoft
Copy link
Author

kenresoft commented May 30, 2023

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.

  1. 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 is RiffSwitchType.decorative, _buildDecorativeSwitch() is called and its result is returned.
    If _type is any other value, _buildSimpleSwitch() is called and its result is returned.

  2. 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 to RiffSwitchType.decorative, _buildDecorativeSwitch() is called and its result is returned.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment