Forked from ltOgt/conditional_parent_widget.dart
Last active
December 24, 2021 21:31
-
-
Save vbuberen/f45f06c91a436d127d80e2f56b87ebbf to your computer and use it in GitHub Desktop.
Flutter Widget to conditionally wrap a subtree with some parent widget
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
import 'package:flutter/widgets.dart'; | |
/// Conditionally wrap a subtree with a parent widget. | |
/// | |
/// [isParentWidgetNeeded]: the condition depending on which the subtree [child] is wrapped with the parent. | |
/// [child]: The subtree that should always be build. | |
/// [conditionalBuilder]: builds the parent wrapping the subtree [child]. | |
/// | |
/// ___________ | |
/// Usage: | |
/// ```dart | |
/// return ConditionalParentWidget( | |
/// isParentWidgetNeeded: shouldIncludeParent, | |
/// child: СhildWidget(), | |
/// conditionalParentBuilder: (Widget child) => ParentWidget(child: child), | |
///); | |
/// ``` | |
/// | |
/// ___________ | |
/// Instead of: | |
/// ```dart | |
/// Widget child = ChildWidget(); | |
/// | |
/// return shouldIncludeParent ? SomeParentWidget(child: child) : child; | |
/// ``` | |
/// | |
class ConditionalParentWidget extends StatelessWidget { | |
const ConditionalParentWidget({ | |
Key? key, | |
required this.isParentWidgetNeeded, | |
required this.child, | |
required this.conditionalParentBuilder, | |
}) : super(key: key); | |
final Widget child; | |
final bool isParentWidgetNeeded; | |
final Widget Function(Widget child) conditionalParentBuilder; | |
@override | |
Widget build(BuildContext context) { | |
return isParentWidgetNeeded ? conditionalParentBuilder(child) : child; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment