Skip to content

Instantly share code, notes, and snippets.

@ltOgt
Created June 29, 2020 14:50
Show Gist options
  • Save ltOgt/3771c824fc1c8811f5ec1a81a9a4937b to your computer and use it in GitHub Desktop.
Save ltOgt/3771c824fc1c8811f5ec1a81a9a4937b to your computer and use it in GitHub Desktop.
Flutter Widget to conditionally wrap a subtree with a parent without breaking the code tree
import 'package:flutter/widgets.dart';
/// Conditionally wrap a subtree with a parent widget without breaking the code tree.
///
/// [condition]: 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 with the subtree [child].
///
/// ___________
/// Usage:
/// ```dart
/// return ConditionalParentWidget(
/// condition: shouldIncludeParent,
/// child: Widget1(
/// child: Widget2(
/// child: Widget3(),
/// ),
/// ),
/// conditionalBuilder: (Widget child) => SomeParentWidget(child: child),
///);
/// ```
///
/// ___________
/// Instead of:
/// ```dart
/// Widget child = Widget1(
/// child: Widget2(
/// child: Widget3(),
/// ),
/// );
///
/// return shouldIncludeParent ? SomeParentWidget(child: child) : child;
/// ```
///
class ConditionalParentWidget extends StatelessWidget {
const ConditionalParentWidget({
Key key,
@required this.condition,
@required this.child,
@required this.conditionalBuilder,
}) : super(key: key);
final Widget child;
final bool condition;
final Widget Function(Widget child) conditionalBuilder;
@override
Widget build(BuildContext context) {
return condition ? this.conditionalBuilder(this.child) : this.child;
}
}
@albertms10
Copy link

Brilliant.

@khoadng
Copy link

khoadng commented Sep 24, 2021

exactly what i needed, many thanks

@juanstakys
Copy link

Thanksss!!!

@ltOgt
Copy link
Author

ltOgt commented Aug 12, 2023

This is also available as a package btw

https://pub.dev/packages/conditional_parent_widget

@Muhammed-Rahif
Copy link

Muhammed-Rahif commented Feb 23, 2024

To anyone have to preserve the child/parent state without rebuilding every time the condition changes:
https://gist.github.com/Muhammed-Rahif/ce0080ea05c07d7cb9a5dde50b0f1ce2

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