Skip to content

Instantly share code, notes, and snippets.

@Muhammed-Rahif
Created February 23, 2024 20:58
Show Gist options
  • Save Muhammed-Rahif/ce0080ea05c07d7cb9a5dde50b0f1ce2 to your computer and use it in GitHub Desktop.
Save Muhammed-Rahif/ce0080ea05c07d7cb9a5dde50b0f1ce2 to your computer and use it in GitHub Desktop.
import 'package:flutter/widgets.dart';
// From https://gist.github.com/ltOgt/3771c824fc1c8811f5ec1a81a9a4937b
/// 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.
/// [parentBuilder]: builds the parent with the subtree [child].
///
/// ___________
/// Usage:
/// ```dart
/// return ConditionalParentWidget(
/// condition: shouldIncludeParent,
/// child: Widget1(
/// child: Widget2(
/// child: Widget3(),
/// ),
/// ),
/// parentBuilder: (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({
super.key,
required this.condition,
required this.child,
required this.parentBuilder,
});
final Widget child;
final bool condition;
final Widget Function(Widget child) parentBuilder;
@override
Widget build(BuildContext context) {
// Using indexed stack to avoid building the widget tree twice.
// This will help to prevent rebuilding the widget tree when the condition changes.
// Which is helpfull to preserve states of both parent and child.
// More at: https://stackoverflow.com/questions/59516450
return IndexedStack(
index: condition ? 0 : 1,
children: [
parentBuilder(child),
child,
],
);
// Or if you want to rebuild everytime the condition changes:
// return condition ? parentBuilder(child) : child;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment