Skip to content

Instantly share code, notes, and snippets.

@vbuberen
Forked from ltOgt/conditional_parent_widget.dart
Last active December 24, 2021 21:31
Show Gist options
  • Save vbuberen/f45f06c91a436d127d80e2f56b87ebbf to your computer and use it in GitHub Desktop.
Save vbuberen/f45f06c91a436d127d80e2f56b87ebbf to your computer and use it in GitHub Desktop.
Flutter Widget to conditionally wrap a subtree with some parent widget
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