Created
October 22, 2022 19:42
-
-
Save yarn-rp/e6526e0b38c391fec8bab4d47a7098d9 to your computer and use it in GitHub Desktop.
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
Widget _kDefaultWidget<T>(T value, BuildContext _) => Text('Error.'); | |
typedef BuilderFunction<T> = Widget Function(T value, BuildContext context); | |
typedef ListenerFunction<T> = void Function(T value, BuildContext context); | |
class MatchCase<Q> { | |
MatchCase( | |
this.matcher, | |
this.builder, | |
this.listener, | |
); | |
final Matcher matcher; | |
final BuilderFunction<Q> builder; | |
final ListenerFunction<Q>? listener; | |
} | |
/// {@template case_widget} | |
/// A Very Good Project created by Very Good CLI. | |
/// {@endtemplate} | |
class CaseWidget<T> extends StatelessWidget { | |
/// {@macro case_widget} | |
const CaseWidget({ | |
required this.value, | |
super.key, | |
this.onDefault, | |
}); | |
///sdfsd | |
void on( | |
Matcher matcher, | |
BuilderFunction<T> builder, { | |
ListenerFunction<T>? listener, | |
}) { | |
matchesSet.add( | |
MatchCase<T>( | |
matcher, | |
builder, | |
listener, | |
), | |
); | |
} | |
void onType<Q extends T>(BuilderFunction builder) => on( | |
isA<Q>(), | |
builder, | |
); | |
void onEquals<T>(T expectedValue, BuilderFunction builder) => on( | |
equals(expectedValue), | |
builder, | |
); | |
/// Value of the | |
final T value; | |
final BuilderFunction<T>? onDefault; | |
/// All matches cases | |
final Set<MatchCase> matchesSet = const {}; | |
@override | |
@visibleForTesting | |
Widget build(BuildContext context) { | |
final matches = matchesSet.where( | |
(element) => element.matcher.matches( | |
value, | |
<String, dynamic>{}, | |
), | |
); | |
if (matches.isNotEmpty) { | |
final firstMatch = matches.first; | |
return firstMatch.builder(value, context); | |
} | |
return _kDefaultWidget<T>(value, context); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment